Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions core/src/Stack.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { BaseDomainEvent } from "event-types/_base";
import type {
DomainEvent,
PausedEvent,
PoppedEvent,
PushedEvent,
ReplacedEvent,
ResumedEvent,
StepPoppedEvent,
StepPushedEvent,
StepReplacedEvent,
Expand Down Expand Up @@ -35,6 +37,7 @@ export type Activity = {
context?: {};
enteredBy: PushedEvent | ReplacedEvent;
exitedBy?: ReplacedEvent | PoppedEvent;
resumedBy?: ResumedEvent;
steps: ActivityStep[];
isTop: boolean;
isActive: boolean;
Expand Down
11 changes: 11 additions & 0 deletions core/src/activity-utils/findTargetActivityIndices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,17 @@ export function findTargetActivityIndices(

break;
}
case "Resumed":
case "Paused": {
const activity = activities.find(
(activity) => activity.id === event.activityId,
);

if (activity) {
targetActivities.push(activities.indexOf(activity));
}
break;
}
default:
break;
}
Expand Down
29 changes: 27 additions & 2 deletions core/src/activity-utils/makeActivityReducer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Activity, ActivityTransitionState } from "../Stack";
import type {
DomainEvent,
PausedEvent,
PoppedEvent,
ReplacedEvent,
ResumedEvent,
StepPoppedEvent,
StepPushedEvent,
StepReplacedEvent,
Expand Down Expand Up @@ -124,7 +126,30 @@ export function makeActivityReducer(context: {
Initialized: noop,
ActivityRegistered: noop,
Pushed: noop,
Paused: noop,
Resumed: noop,
Paused: (activity: Activity, event: PausedEvent): Activity => {
if (activity.exitedBy || activity.resumedBy) {
return activity;
}

return {
...activity,
transitionState: "enter-active",
};
},
Resumed: (activity: Activity, event: ResumedEvent): Activity => {
if (activity.exitedBy || activity.resumedBy) {
return activity;
}

const isTransitionDone =
context.now - (context.resumedAt ?? event.eventDate) >=
context.transitionDuration;

return {
...activity,
transitionState: isTransitionDone ? "enter-done" : "enter-active",
resumedBy: event,
};
},
} as const);
}
45 changes: 34 additions & 11 deletions core/src/activity-utils/makeStackReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@ import { makeActivitiesReducer } from "./makeActivitiesReducer";
import { makeActivityReducer } from "./makeActivityReducer";
import { makeReducer } from "./makeReducer";

function calculateGlobalTransitionState(
activities: Activity[],
currentState: Stack["globalTransitionState"],
): Stack["globalTransitionState"] {
if (currentState === "paused") {
return "paused";
}

const hasActiveTransition = activities.some(
(activity) =>
activity.transitionState === "enter-active" ||
activity.transitionState === "exit-active",
);

return hasActiveTransition ? "loading" : "idle";
}

function withPauseReducer<T extends DomainEvent>(
reducer: (stack: Stack, event: T) => Stack,
) {
Expand Down Expand Up @@ -63,20 +80,25 @@ function withActivitiesReducer<T extends DomainEvent>(
);
}

const isLoading = activities.find(
(activity) =>
activity.transitionState === "enter-active" ||
activity.transitionState === "exit-active",
const globalTransitionState = calculateGlobalTransitionState(
activities,
stack.globalTransitionState,
);

const globalTransitionState =
stack.globalTransitionState === "paused"
? "paused"
: isLoading
? "loading"
: "idle";
const result = reducer(
{ ...stack, activities, globalTransitionState },
event,
);

const updatedGlobalTransitionState = calculateGlobalTransitionState(
result.activities,
result.globalTransitionState,
);

return reducer({ ...stack, activities, globalTransitionState }, event);
return {
...result,
globalTransitionState: updatedGlobalTransitionState,
};
Comment on lines +83 to +101
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

global transition state should be evaluated latest (another with hof?)

};
}

Expand Down Expand Up @@ -123,6 +145,7 @@ export function makeStackReducer(context: {
return {
...stack,
globalTransitionState: "paused",
pausedEvents: stack.pausedEvents ?? [],
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug fix

};
}, context),
),
Expand Down
74 changes: 74 additions & 0 deletions core/src/aggregate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4088,6 +4088,78 @@ test("aggregate - Pause되면 이벤트가 반영되지 않고, globalTransition
});
});

test("aggregate - PausedEvent inserts source activity entering event into pausedEvents", () => {
let pushedEvent1: PushedEvent;
let pushedEvent2: PushedEvent;

const t = nowTime();

const events = [
initializedEvent({
transitionDuration: 300,
}),
registeredEvent({
activityName: "a",
}),
registeredEvent({
activityName: "b",
}),
(pushedEvent1 = makeEvent("Pushed", {
activityId: "activity-1",
activityName: "a",
eventDate: enoughPastTime(),
activityParams: {},
})),
(pushedEvent2 = makeEvent("Pushed", {
activityId: "activity-2",
activityName: "b",
activityParams: {},
eventDate: enoughPastTime(),
})),
makeEvent("Paused", {
eventDate: t - 150,
activityId: "activity-2",
}),
];

const output = aggregate(events, t);

expect(output).toStrictEqual({
activities: [
activity({
id: "activity-1",
name: "a",
transitionState: "enter-done",
params: {},
steps: [
{
id: "activity-1",
params: {},
enteredBy: pushedEvent1,
zIndex: 0,
},
],
enteredBy: pushedEvent1,
isActive: true,
isTop: true,
isRoot: true,
zIndex: 0,
}),
],
registeredActivities: [
{
name: "a",
},
{
name: "b",
},
],
transitionDuration: 300,
globalTransitionState: "paused",
pausedEvents: [pushedEvent2],
});
});

test("aggregate - Resumed 되면 해당 시간 이후로 Transition이 정상작동합니다", () => {
let pushedEvent1: PushedEvent;
let pushedEvent2: PushedEvent;
Expand All @@ -4109,6 +4181,7 @@ test("aggregate - Resumed 되면 해당 시간 이후로 Transition이 정상작
activityParams: {},
})),
makeEvent("Paused", {
activityId: "activity-1",
eventDate: enoughPastTime(),
}),
(pushedEvent2 = makeEvent("Pushed", {
Expand All @@ -4118,6 +4191,7 @@ test("aggregate - Resumed 되면 해당 시간 이후로 Transition이 정상작
activityParams: {},
})),
makeEvent("Resumed", {
activityId: "activity-1",
eventDate: nowTime() - 150,
}),
];
Expand Down
7 changes: 6 additions & 1 deletion core/src/event-types/PausedEvent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import type { BaseDomainEvent } from "./_base";

export type PausedEvent = BaseDomainEvent<"Paused", {}>;
export type PausedEvent = BaseDomainEvent<
"Paused",
{
activityId: string;
}
>;
7 changes: 6 additions & 1 deletion core/src/event-types/ResumedEvent.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import type { BaseDomainEvent } from "./_base";

export type ResumedEvent = BaseDomainEvent<"Resumed", {}>;
export type ResumedEvent = BaseDomainEvent<
"Resumed",
{
activityId: string;
}
>;
30 changes: 30 additions & 0 deletions integrations/react/src/__internal__/suspensePlugin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Suspense, useEffect } from "react";
import type { StackflowReactPlugin } from "./StackflowReactPlugin";
import { useCoreActions } from "./core";

export function suspensePlugin(): StackflowReactPlugin {
return () => ({
key: "plugin-suspense",
wrapActivity: ({ activity }) => {
return (
<Suspense fallback={<SuspenseFallback />}>{activity.render()}</Suspense>
);
},
});
}

export function SuspenseFallback() {
const { pause, resume } = useCoreActions();

useEffect(() => {
console.log("lets pause");
pause();

return () => {
console.log("lets resume");
resume();
};
}, []);

return null;
}
41 changes: 5 additions & 36 deletions integrations/react/src/future/loader/loaderPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,7 @@ function createBeforeRouteHandler<
[activityName in RegisteredActivityName]: ActivityComponentType<any>;
},
>(input: StackflowInput<T, R>): OnBeforeRoute {
return ({
actionParams,
actions: { overrideActionParams, pause, resume },
}) => {
return ({ actionParams, actions: { overrideActionParams } }) => {
const { activityName, activityParams, activityContext } = actionParams;

const matchActivity = input.config.activities.find(
Expand All @@ -106,28 +103,15 @@ function createBeforeRouteHandler<

const loaderDataPromise =
loaderData instanceof Promise ? loaderData : undefined;
const lazyComponentPromise =
"_load" in matchActivityComponent
? matchActivityComponent._load?.()
: undefined;

if (loaderDataPromise || lazyComponentPromise) {
pause();
}
Promise.allSettled([loaderDataPromise, lazyComponentPromise])
.then(([loaderDataPromiseResult, lazyComponentPromiseResult]) => {
Promise.allSettled([loaderDataPromise]).then(
([loaderDataPromiseResult]) => {
printLoaderDataPromiseError({
promiseResult: loaderDataPromiseResult,
activityName: matchActivity.name,
});
printLazyComponentPromiseError({
promiseResult: lazyComponentPromiseResult,
activityName: matchActivity.name,
});
})
.finally(() => {
resume();
});
},
);

overrideActionParams({
...actionParams,
Expand All @@ -153,18 +137,3 @@ function printLoaderDataPromiseError({
);
}
}

function printLazyComponentPromiseError({
promiseResult,
activityName,
}: {
promiseResult: PromiseSettledResult<any>;
activityName: string;
}) {
if (promiseResult.status === "rejected") {
console.error(promiseResult.reason);
console.error(
`The above error occurred while loading a lazy react component of the "${activityName}" activity`,
);
}
}
6 changes: 2 additions & 4 deletions integrations/react/src/future/stackflow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import MainRenderer from "../__internal__/MainRenderer";
import { makeActivityId } from "../__internal__/activity";
import { CoreProvider } from "../__internal__/core";
import { PluginsProvider } from "../__internal__/plugins";
import { suspensePlugin } from "../__internal__/suspensePlugin";
import { isBrowser, makeRef } from "../__internal__/utils";
import type { StackflowReactPlugin } from "../stable";
import type { Actions } from "./Actions";
Expand Down Expand Up @@ -57,11 +58,8 @@ export function stackflow<
...(input.plugins ?? [])
.flat(Number.POSITIVE_INFINITY as 0)
.map((p) => p as StackflowReactPlugin),

/**
* `loaderPlugin()` must be placed after `historySyncPlugin()`
*/
loaderPlugin(input),
suspensePlugin(),
];

const enoughPastTime = () =>
Expand Down
Loading