-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathstackflow.tsx
More file actions
416 lines (363 loc) · 11.6 KB
/
stackflow.tsx
File metadata and controls
416 lines (363 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import type {
ActivityRegisteredEvent,
CoreStore,
PushedEvent,
StackflowActions,
} from "@stackflow/core";
import { makeCoreStore, makeEvent } from "@stackflow/core";
import { memo, useMemo } from "react";
import type { ActivityComponentType } from "../__internal__/ActivityComponentType";
import MainRenderer from "../__internal__/MainRenderer";
import type { StackflowReactPlugin } from "../__internal__/StackflowReactPlugin";
import {
findActivityById,
findLatestActiveActivity,
makeActivityId,
makeStepId,
} from "../__internal__/activity";
import { CoreProvider } from "../__internal__/core";
import { PluginsProvider } from "../__internal__/plugins";
import { isBrowser, makeRef } from "../__internal__/utils";
import type { BaseActivities } from "./BaseActivities";
import { lazyActivityPlugin } from "./lazyActivityPlugin";
import type { UseActionsOutputType } from "./useActions";
import { useActions } from "./useActions";
import type { UseStepActionsOutputType } from "./useStepActions";
import { useStepActions } from "./useStepActions";
import { version } from "react";
function parseActionOptions(options?: { animate?: boolean }) {
if (!options) {
return { skipActiveState: false };
}
const isNullableAnimateOption = options.animate == null;
if (isNullableAnimateOption) {
return { skipActiveState: false };
}
return { skipActiveState: !options.animate };
}
export type StackComponentType = React.FC<{
initialContext?: any;
}>;
type StackflowPluginsEntry<T extends BaseActivities> =
| StackflowReactPlugin<T>
| StackflowPluginsEntry<T>[];
type NoInfer<T> = [T][T extends any ? 0 : never];
export type StackflowOptions<T extends BaseActivities> = {
/**
* Register activities used in your app
*/
activities: T;
/**
* Transition duration for stack animation (millisecond)
*/
transitionDuration: number;
/**
* Set the first activity to load at the bottom
* (It can be overwritten by plugin)
*/
initialActivity?: () => Extract<keyof NoInfer<T>, string>;
/**
* Inject stackflow plugins
*/
plugins?: Array<StackflowPluginsEntry<NoInfer<T>>>;
};
export type StackflowOutput<T extends BaseActivities> = {
/**
* Return activities
*/
activities: T;
/**
* Created `<Stack />` component
*/
Stack: StackComponentType;
/**
* Created `useFlow()` hooks
*/
useFlow: () => UseActionsOutputType<T>;
/**
* Created `useStepFlow()` hooks
*/
useStepFlow: <K extends Extract<keyof T, string>>(
activityName: K,
) => UseStepActionsOutputType<
T[K] extends
| ActivityComponentType<infer U>
| { component: ActivityComponentType<infer U> }
? U
: {}
>;
/**
* Add activity imperatively
*/
addActivity: (options: {
name: string;
component: ActivityComponentType<any>;
paramsSchema?: ActivityRegisteredEvent["activityParamsSchema"];
}) => void;
/**
* Add plugin imperatively
*/
addPlugin: (plugin: StackflowPluginsEntry<T>) => void;
/**
* Created action triggers
*/
actions: Pick<StackflowActions, "dispatchEvent" | "getStack"> &
Pick<UseActionsOutputType<T>, "push" | "pop" | "replace"> &
Pick<UseStepActionsOutputType<{}>, "stepPush" | "stepReplace" | "stepPop">;
};
/**
* Make `<Stack />` component and `useFlow()` hooks that strictly typed with `activities`
*/
export function stackflow<T extends BaseActivities>(
options: StackflowOptions<T>,
): StackflowOutput<T> {
const activityComponentMap = Object.entries(options.activities).reduce(
(acc, [key, Activity]) => ({
...acc,
[key]:
"component" in Activity ? memo(Activity.component) : memo(Activity),
}),
{} as {
[key: string]: ActivityComponentType;
},
);
const plugins: StackflowReactPlugin[] = [
...(options.plugins ?? [])
.flat(Number.POSITIVE_INFINITY as 0)
.map((p) => p as StackflowReactPlugin),
];
const majorReactVersion = Number.parseInt(version);
/**
* TODO: This plugin depends on internal APIs of React.
* A proper solution (e.g. Suspense integration) should be implemented in the next major version.
*/
if (majorReactVersion >= 18 && majorReactVersion <= 19) {
plugins.push(lazyActivityPlugin(activityComponentMap));
}
const enoughPastTime = () =>
new Date().getTime() - options.transitionDuration * 2;
const staticCoreStore = makeCoreStore({
initialEvents: [
makeEvent("Initialized", {
transitionDuration: options.transitionDuration,
eventDate: enoughPastTime(),
}),
...Object.entries(options.activities).map(([activityName, Activity]) =>
makeEvent("ActivityRegistered", {
activityName,
eventDate: enoughPastTime(),
...("component" in Activity
? {
activityParamsSchema: Activity.paramsSchema,
}
: null),
}),
),
],
plugins: [],
});
const [getCoreStore, setCoreStore] = makeRef<CoreStore>();
const Stack: StackComponentType = memo((props) => {
const coreStore = useMemo(() => {
const prevCoreStore = getCoreStore();
// In a browser environment,
// memoize `coreStore` so that only one `coreStore` exists throughout the entire app.
if (isBrowser() && prevCoreStore) {
return prevCoreStore;
}
const initialPushedEventsByOption = options.initialActivity
? [
makeEvent("Pushed", {
activityId: makeActivityId(),
activityName: options.initialActivity(),
activityParams: {},
eventDate: enoughPastTime(),
skipEnterActiveState: false,
}),
]
: [];
const store = makeCoreStore({
initialEvents: [
...staticCoreStore.pullEvents(),
...initialPushedEventsByOption,
],
initialContext: props.initialContext,
plugins,
handlers: {
onInitialActivityIgnored: (initialPushedEvents) => {
if (isBrowser()) {
console.warn(
`Stackflow - Some plugin overrides an "initialActivity" option. The "initialActivity" option you set to "${
(initialPushedEvents[0] as PushedEvent).activityName
}" in the "stackflow" is ignored.`,
);
}
},
onInitialActivityNotFound: () => {
if (isBrowser()) {
console.warn(
"Stackflow -" +
" There is no initial activity." +
" If you want to set the initial activity," +
" add the `initialActivity` option of the `stackflow()` function or" +
" add a plugin that sets the initial activity. (e.g. `@stackflow/plugin-history-sync`)",
);
}
},
},
});
if (isBrowser()) {
store.init();
setCoreStore(store);
}
return store;
}, []);
return (
<PluginsProvider value={coreStore.pluginInstances}>
<CoreProvider coreStore={coreStore}>
<MainRenderer
activityComponentMap={activityComponentMap}
initialContext={props.initialContext}
/>
</CoreProvider>
</PluginsProvider>
);
});
Stack.displayName = "Stack";
return {
activities: options.activities,
Stack,
useFlow: useActions,
useStepFlow: useStepActions,
addActivity(activity) {
if (getCoreStore()) {
console.warn(
"Stackflow -" +
" `addActivity()` API cannot be called after a `<Stack />` component has been rendered",
);
return;
}
activityComponentMap[activity.name] = memo(activity.component);
staticCoreStore.actions.dispatchEvent("ActivityRegistered", {
activityName: activity.name,
activityParamsSchema: activity.paramsSchema,
eventDate: enoughPastTime(),
});
},
addPlugin(plugin) {
if (getCoreStore()) {
console.warn(
"Stackflow -" +
" `addPlugin()` API cannot be called after a `<Stack />` component has been rendered",
);
return;
}
[plugin]
.flat(Number.POSITIVE_INFINITY as 0)
.map((p) => p as StackflowReactPlugin)
.forEach((p) => {
plugins.push(p);
});
},
actions: {
getStack() {
return (
getCoreStore()?.actions.getStack() ??
staticCoreStore.actions.getStack()
);
},
dispatchEvent(name, parameters) {
return getCoreStore()?.actions.dispatchEvent(name, parameters);
},
push(activityName, activityParams, options) {
const activityId = makeActivityId();
getCoreStore()?.actions.push({
activityId,
activityName,
activityParams,
skipEnterActiveState: parseActionOptions(options).skipActiveState,
});
return {
activityId,
};
},
replace(activityName, activityParams, options) {
const activityId = options?.activityId ?? makeActivityId();
getCoreStore()?.actions.replace({
activityId: options?.activityId ?? makeActivityId(),
activityName,
activityParams,
skipEnterActiveState: parseActionOptions(options).skipActiveState,
});
return {
activityId,
};
},
pop(
count?: number | { animate?: boolean } | undefined,
options?: { animate?: boolean } | undefined,
) {
let _count = 1;
let _options: { animate?: boolean } = {};
if (typeof count === "object") {
_options = {
...count,
};
}
if (typeof count === "number") {
_count = count;
}
if (options) {
_options = {
...options,
};
}
for (let i = 0; i < _count; i += 1) {
getCoreStore()?.actions.pop({
skipExitActiveState:
i === 0 ? parseActionOptions(_options).skipActiveState : true,
});
}
},
stepPush(params, options) {
const activities = getCoreStore()?.actions.getStack().activities;
const findTargetActivity = options?.targetActivityId
? findActivityById(options.targetActivityId)
: findLatestActiveActivity;
const targetActivity = activities && findTargetActivity(activities);
if (!targetActivity)
throw new Error("The target activity is not found.");
const stepParams =
typeof params === "function" ? params(targetActivity.params) : params;
const stepId = makeStepId();
return getCoreStore()?.actions.stepPush({
stepId,
stepParams,
targetActivityId: options?.targetActivityId,
});
},
stepReplace(params, options) {
const activities = getCoreStore()?.actions.getStack().activities;
const findTargetActivity = options?.targetActivityId
? findActivityById(options.targetActivityId)
: findLatestActiveActivity;
const targetActivity = activities && findTargetActivity(activities);
if (!targetActivity)
throw new Error("The target activity is not found.");
const stepParams =
typeof params === "function" ? params(targetActivity.params) : params;
const stepId = makeStepId();
return getCoreStore()?.actions.stepReplace({
stepId,
stepParams,
targetActivityId: options?.targetActivityId,
});
},
stepPop(options) {
return getCoreStore()?.actions.stepPop({
targetActivityId: options?.targetActivityId,
});
},
},
};
}