@nocobase/flow-engine 2.1.0-alpha.35 → 2.1.0-alpha.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,6 +28,122 @@ export const GLOBAL_EMBED_CONTAINER_ID = 'nocobase-embed-container';
28
28
  /** Dataset key used to signal embed replacement in progress (skip style reset on close) */
29
29
  export const EMBED_REPLACING_DATA_KEY = 'nocobaseEmbedReplacing';
30
30
 
31
+ type GlobalEmbedActiveView = {
32
+ close: (result?: any, force?: boolean) => Promise<boolean | void> | boolean | void;
33
+ destroy: (result?: any) => void;
34
+ };
35
+
36
+ type PendingGlobalEmbedActions = {
37
+ beforeClose?: any;
38
+ destroyed?: { result?: any };
39
+ update?: any;
40
+ footer?: React.ReactNode;
41
+ header?: { title?: React.ReactNode; extra?: React.ReactNode };
42
+ };
43
+
44
+ function isPromiseLike<T = any>(value: unknown): value is PromiseLike<T> {
45
+ return !!value && typeof (value as PromiseLike<T>).then === 'function';
46
+ }
47
+
48
+ function closeReplacingGlobalEmbed(target: HTMLElement, activeView: GlobalEmbedActiveView) {
49
+ target.dataset[EMBED_REPLACING_DATA_KEY] = '1';
50
+ try {
51
+ const closeResult = activeView.close();
52
+ if (isPromiseLike(closeResult)) {
53
+ return Promise.resolve(closeResult).finally(() => {
54
+ delete target.dataset[EMBED_REPLACING_DATA_KEY];
55
+ });
56
+ }
57
+ delete target.dataset[EMBED_REPLACING_DATA_KEY];
58
+ return closeResult;
59
+ } catch (error) {
60
+ delete target.dataset[EMBED_REPLACING_DATA_KEY];
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ function createPendingGlobalEmbedView(
66
+ openedPromise: Promise<{ page: any | null }>,
67
+ inputArgs: any,
68
+ preventClose: boolean,
69
+ ) {
70
+ let openedPage: any;
71
+ const pendingActions: PendingGlobalEmbedActions = {};
72
+
73
+ const readyPromise = openedPromise.then(({ page }) => {
74
+ openedPage = page;
75
+ if (openedPage) {
76
+ if ('beforeClose' in pendingActions) {
77
+ openedPage.beforeClose = pendingActions.beforeClose;
78
+ }
79
+ if ('update' in pendingActions) {
80
+ openedPage.update(pendingActions.update);
81
+ }
82
+ if ('footer' in pendingActions) {
83
+ openedPage.setFooter(pendingActions.footer);
84
+ }
85
+ if ('header' in pendingActions) {
86
+ openedPage.setHeader(pendingActions.header);
87
+ }
88
+ if (pendingActions.destroyed) {
89
+ openedPage.destroy(pendingActions.destroyed.result);
90
+ }
91
+ }
92
+ return { page };
93
+ });
94
+
95
+ return Object.assign(
96
+ readyPromise.then(({ page }) => (page ? page : false)),
97
+ {
98
+ type: 'embed' as const,
99
+ inputArgs,
100
+ preventClose,
101
+ Header: null,
102
+ Footer: null,
103
+ get beforeClose() {
104
+ return openedPage?.beforeClose ?? pendingActions.beforeClose;
105
+ },
106
+ set beforeClose(value) {
107
+ if (openedPage) {
108
+ openedPage.beforeClose = value;
109
+ } else {
110
+ pendingActions.beforeClose = value;
111
+ }
112
+ },
113
+ close: (result?: any, force?: boolean) =>
114
+ readyPromise.then(({ page }) => (page ? page.close(result, force) : false)),
115
+ destroy: (result?: any) => {
116
+ if (openedPage) {
117
+ openedPage.destroy(result);
118
+ } else {
119
+ pendingActions.destroyed = { result };
120
+ }
121
+ },
122
+ update: (newConfig: any) => {
123
+ if (openedPage) {
124
+ openedPage.update(newConfig);
125
+ } else {
126
+ pendingActions.update = { ...pendingActions.update, ...newConfig };
127
+ }
128
+ },
129
+ setFooter: (footer: React.ReactNode) => {
130
+ if (openedPage) {
131
+ openedPage.setFooter(footer);
132
+ } else {
133
+ pendingActions.footer = footer;
134
+ }
135
+ },
136
+ setHeader: (header: { title?: React.ReactNode; extra?: React.ReactNode }) => {
137
+ if (openedPage) {
138
+ openedPage.setHeader(header);
139
+ } else {
140
+ pendingActions.header = header;
141
+ }
142
+ },
143
+ },
144
+ );
145
+ }
146
+
31
147
  // 稳定的 Holder 组件,避免在父组件重渲染时更换组件类型导致卸载, 否则切换主题时会丢失所有页面内容
32
148
  const PageElementsHolder = React.memo(
33
149
  React.forwardRef((props: any, ref: any) => {
@@ -39,218 +155,279 @@ const PageElementsHolder = React.memo(
39
155
 
40
156
  export function usePage() {
41
157
  const holderRef = React.useRef(null);
42
- const globalEmbedActiveRef = React.useRef<null | { destroy: () => void }>(null);
158
+ const globalEmbedActiveRef = React.useRef<null | GlobalEmbedActiveView>(null);
159
+ const globalEmbedReplacementTokenRef = React.useRef(0);
43
160
 
44
161
  const open = (config, flowContext) => {
45
- const parentEngine = flowContext?.engine;
46
- uuid += 1;
47
- const pageRef = React.createRef<{
48
- destroy: () => void;
49
- update: (config: any) => void;
50
- setFooter: (footer: React.ReactNode) => void;
51
- setHeader: (header: { title?: React.ReactNode; extra?: React.ReactNode }) => void;
52
- }>();
53
-
54
- let closeFunc: (() => void) | undefined;
55
- let resolvePromise: (value?: any) => void;
56
- const promise = new Promise((resolve) => {
57
- resolvePromise = resolve;
58
- });
59
-
60
- // Footer 组件实现
61
- const FooterComponent: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
62
- React.useEffect(() => {
63
- pageRef.current?.setFooter(children);
64
-
65
- return () => {
66
- pageRef.current?.setFooter(null);
67
- };
68
- }, [children]);
69
-
70
- return null; // Footer 组件本身不渲染内容
71
- };
72
-
73
- // Header 组件实现
74
- const HeaderComponent: React.FC<{ title?: React.ReactNode; extra?: React.ReactNode }> = (props) => {
75
- React.useEffect(() => {
76
- pageRef.current?.setHeader(props);
77
-
78
- return () => {
79
- pageRef.current?.setHeader(null);
80
- };
81
- }, [props]);
82
-
83
- return null; // Header 组件本身不渲染内容
84
- };
85
-
86
162
  const {
87
163
  target,
88
164
  content,
89
165
  preventClose,
90
166
  inheritContext = true,
91
167
  inputArgs: viewInputArgs = {},
168
+ onOpenCancelled,
92
169
  ...restConfig
93
170
  } = config;
94
171
  const isGlobalEmbedContainer = target instanceof HTMLElement && target.id === GLOBAL_EMBED_CONTAINER_ID;
95
172
 
96
- // Global embed container uses "replace" behavior: opening a new view destroys the previous one.
97
- if (isGlobalEmbedContainer && globalEmbedActiveRef.current) {
98
- try {
99
- // Avoid style "reset flicker" when replacing: tell embed wrappers to skip resetting container styles.
100
- target.dataset[EMBED_REPLACING_DATA_KEY] = '1';
101
- globalEmbedActiveRef.current.destroy();
102
- } finally {
103
- delete target.dataset[EMBED_REPLACING_DATA_KEY];
104
- globalEmbedActiveRef.current = null;
105
- }
106
- }
107
-
108
- const ctx = new FlowContext();
109
- // 为当前视图创建作用域引擎(隔离实例与缓存)
110
- const scopedEngine = createViewScopedEngine(flowContext.engine);
111
- const openerEngine = resolveOpenerEngine(parentEngine, scopedEngine);
112
-
113
- ctx.defineProperty('engine', { value: scopedEngine });
114
- ctx.addDelegate(scopedEngine.context);
115
- if (inheritContext) {
116
- ctx.addDelegate(flowContext);
117
- } else {
118
- ctx.addDelegate(flowContext.engine.context);
119
- }
173
+ const openCurrentPage = () => {
174
+ const parentEngine = flowContext?.engine;
175
+ uuid += 1;
176
+ const pageRef = React.createRef<{
177
+ destroy: () => void;
178
+ update: (config: any) => void;
179
+ setFooter: (footer: React.ReactNode) => void;
180
+ setHeader: (header: { title?: React.ReactNode; extra?: React.ReactNode }) => void;
181
+ }>();
182
+
183
+ let closeFunc: (() => void) | undefined;
184
+ let resolvePromise: (value?: any) => void;
185
+ const promise = new Promise((resolve) => {
186
+ resolvePromise = resolve;
187
+ });
188
+
189
+ // Footer 组件实现
190
+ const FooterComponent: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
191
+ React.useEffect(() => {
192
+ pageRef.current?.setFooter(children);
120
193
 
121
- // 构造 currentPage 实例
122
- const currentPage = {
123
- type: 'embed' as const,
124
- inputArgs: viewInputArgs,
125
- preventClose: !!config.preventClose,
126
- beforeClose: undefined,
127
- destroy: (result?: any) => {
128
- config.onClose?.();
129
- resolvePromise?.(result);
130
- pageRef.current?.destroy();
131
- closeFunc?.();
194
+ return () => {
195
+ pageRef.current?.setFooter(null);
196
+ };
197
+ }, [children]);
132
198
 
133
- if (isGlobalEmbedContainer) {
134
- globalEmbedActiveRef.current = null;
135
- }
199
+ return null; // Footer 组件本身不渲染内容
200
+ };
136
201
 
137
- // Notify opener view that it becomes active again.
138
- const isReplacing =
139
- isGlobalEmbedContainer && target instanceof HTMLElement && target.dataset?.[EMBED_REPLACING_DATA_KEY] === '1';
140
- if (!isReplacing) {
141
- const openerEmitter = openerEngine?.emitter;
142
- bumpViewActivatedVersion(openerEmitter);
143
- openerEmitter?.emit?.(VIEW_ACTIVATED_EVENT, { type: 'embed', viewUid: currentPage?.inputArgs?.viewUid });
144
- }
145
-
146
- // 关闭时修正 previous/next 指针
147
- scopedEngine.unlinkFromStack();
148
- },
149
- update: (newConfig) => pageRef.current?.update(newConfig),
150
- close: async (result?: any, force?: boolean) => {
151
- if (preventClose && !force) {
152
- return false;
153
- }
202
+ // Header 组件实现
203
+ const HeaderComponent: React.FC<{ title?: React.ReactNode; extra?: React.ReactNode }> = (props) => {
204
+ React.useEffect(() => {
205
+ pageRef.current?.setHeader(props);
206
+
207
+ return () => {
208
+ pageRef.current?.setHeader(null);
209
+ };
210
+ }, [props]);
211
+
212
+ return null; // Header 组件本身不渲染内容
213
+ };
214
+
215
+ const ctx = new FlowContext();
216
+ // 为当前视图创建作用域引擎(隔离实例与缓存)
217
+ const scopedEngine = createViewScopedEngine(flowContext.engine);
218
+ const openerEngine = resolveOpenerEngine(parentEngine, scopedEngine);
219
+
220
+ ctx.defineProperty('engine', { value: scopedEngine });
221
+ ctx.addDelegate(scopedEngine.context);
222
+ if (inheritContext) {
223
+ ctx.addDelegate(flowContext);
224
+ } else {
225
+ ctx.addDelegate(flowContext.engine.context);
226
+ }
154
227
 
155
- const shouldClose = await runViewBeforeClose(currentPage, { result, force });
156
- if (!shouldClose) {
157
- return false;
158
- }
228
+ // 构造 currentPage 实例
229
+ let destroyed = false;
230
+ let closingPromise: Promise<boolean | void> | undefined;
231
+ const currentPage = {
232
+ type: 'embed' as const,
233
+ inputArgs: viewInputArgs,
234
+ preventClose: !!config.preventClose,
235
+ beforeClose: undefined,
236
+ destroy: (result?: any) => {
237
+ if (destroyed) return;
238
+ destroyed = true;
239
+ config.onClose?.();
240
+ resolvePromise?.(result);
241
+ pageRef.current?.destroy();
242
+ closeFunc?.();
243
+
244
+ if (isGlobalEmbedContainer && globalEmbedActiveRef.current === currentPage) {
245
+ globalEmbedActiveRef.current = null;
246
+ }
247
+
248
+ // Notify opener view that it becomes active again.
249
+ const isReplacing =
250
+ isGlobalEmbedContainer &&
251
+ target instanceof HTMLElement &&
252
+ target.dataset?.[EMBED_REPLACING_DATA_KEY] === '1';
253
+ if (!isReplacing) {
254
+ const openerEmitter = openerEngine?.emitter;
255
+ bumpViewActivatedVersion(openerEmitter);
256
+ openerEmitter?.emit?.(VIEW_ACTIVATED_EVENT, { type: 'embed', viewUid: currentPage?.inputArgs?.viewUid });
257
+ }
258
+
259
+ // 关闭时修正 previous/next 指针
260
+ scopedEngine.unlinkFromStack();
261
+ },
262
+ update: (newConfig) => pageRef.current?.update(newConfig),
263
+ close: (result?: any, force?: boolean) => {
264
+ if (destroyed) {
265
+ return Promise.resolve(true);
266
+ }
267
+ if (closingPromise) {
268
+ return closingPromise;
269
+ }
270
+
271
+ closingPromise = (async () => {
272
+ try {
273
+ if (preventClose && !force) {
274
+ closingPromise = undefined;
275
+ return false;
276
+ }
277
+
278
+ const shouldClose = await runViewBeforeClose(currentPage, { result, force });
279
+ if (destroyed) {
280
+ return true;
281
+ }
282
+ if (!shouldClose) {
283
+ closingPromise = undefined;
284
+ return false;
285
+ }
286
+
287
+ if (config.triggerByRouter && config.inputArgs?.navigation?.back) {
288
+ // 交由路由系统来销毁当前视图
289
+ config.inputArgs.navigation.back();
290
+ return true;
291
+ }
292
+
293
+ currentPage.destroy(result);
294
+ return true;
295
+ } catch (error) {
296
+ if (!destroyed) {
297
+ closingPromise = undefined;
298
+ }
299
+ throw error;
300
+ }
301
+ })();
302
+
303
+ return closingPromise;
304
+ },
305
+ Header: HeaderComponent,
306
+ Footer: FooterComponent,
307
+ setFooter: (footer: React.ReactNode) => {
308
+ pageRef.current?.setFooter(footer);
309
+ },
310
+ setHeader: (header: { title?: React.ReactNode; extra?: React.ReactNode }) => {
311
+ pageRef.current?.setHeader(header);
312
+ },
313
+ navigation: config.inputArgs?.navigation,
314
+ get record() {
315
+ // 当视图正在查看与父 record 同一条记录时,复用父记录深拷贝;否则走服务端解析
316
+ return getViewRecordFromParent(flowContext, ctx);
317
+ },
318
+ };
319
+
320
+ ctx.defineProperty('view', {
321
+ get: () => currentPage,
322
+ // 仅当访问关联字段或前端无本地记录数据时,才交给服务端解析
323
+ resolveOnServer: createViewRecordResolveOnServer(ctx, () => getViewRecordFromParent(flowContext, ctx)),
324
+ });
325
+ // embed 视图不注册 destroyView,afterSuccess 关闭弹窗时自然跳过
326
+ // 顶层 popup 变量:弹窗记录/数据源/上级弹窗链(去重封装)
327
+ registerPopupVariable(ctx, currentPage);
328
+
329
+ const PageWithContext = observer(
330
+ () => {
331
+ // eslint-disable-next-line react-hooks/rules-of-hooks
332
+ const mountedRef = React.useRef(false);
333
+ // 支持 content 为函数,传递 currentPage
334
+ // eslint-disable-next-line react-hooks/rules-of-hooks
335
+ const pageContent = React.useMemo(
336
+ () => (typeof content === 'function' ? content(currentPage, ctx) : content),
337
+ [],
338
+ );
339
+ // 响应themeToken的响应式更新
340
+ void ctx.themeToken;
341
+ // eslint-disable-next-line react-hooks/rules-of-hooks
342
+ React.useEffect(() => {
343
+ config.onOpen?.(currentPage, ctx);
344
+ }, []);
345
+
346
+ if (config.inputArgs?.hidden?.value && !mountedRef.current) {
347
+ return null;
348
+ }
349
+
350
+ mountedRef.current = true;
351
+
352
+ return (
353
+ <PageComponent
354
+ ref={pageRef}
355
+ hidden={config.inputArgs?.hidden?.value}
356
+ {...restConfig}
357
+ onClose={() => {
358
+ return currentPage.close(config.result);
359
+ }}
360
+ >
361
+ {pageContent}
362
+ </PageComponent>
363
+ );
364
+ },
365
+ {
366
+ displayName: 'PageWithContext',
367
+ },
368
+ );
369
+
370
+ const key = viewInputArgs?.viewUid || `page-${uuid}`;
371
+ const page = (
372
+ <FlowEngineProvider key={key} engine={scopedEngine}>
373
+ <FlowViewContextProvider context={ctx}>
374
+ <PageWithContext />
375
+ </FlowViewContextProvider>
376
+ </FlowEngineProvider>
377
+ );
378
+
379
+ if (target && target instanceof HTMLElement) {
380
+ closeFunc = holderRef.current?.patchElement(ReactDOM.createPortal(page, target, key));
381
+ } else {
382
+ closeFunc = holderRef.current?.patchElement(page);
383
+ }
159
384
 
160
- if (config.triggerByRouter && config.inputArgs?.navigation?.back) {
161
- // 交由路由系统来销毁当前视图
162
- config.inputArgs.navigation.back();
163
- return true;
164
- }
385
+ if (isGlobalEmbedContainer) {
386
+ globalEmbedActiveRef.current = currentPage;
387
+ }
165
388
 
166
- currentPage.destroy(result);
167
- return true;
168
- },
169
- Header: HeaderComponent,
170
- Footer: FooterComponent,
171
- setFooter: (footer: React.ReactNode) => {
172
- pageRef.current?.setFooter(footer);
173
- },
174
- setHeader: (header: { title?: React.ReactNode; extra?: React.ReactNode }) => {
175
- pageRef.current?.setHeader(header);
176
- },
177
- navigation: config.inputArgs?.navigation,
178
- get record() {
179
- // 当视图正在查看与父 record 同一条记录时,复用父记录深拷贝;否则走服务端解析
180
- return getViewRecordFromParent(flowContext, ctx);
181
- },
389
+ return Object.assign(promise, currentPage);
182
390
  };
183
391
 
184
- ctx.defineProperty('view', {
185
- get: () => currentPage,
186
- // 仅当访问关联字段或前端无本地记录数据时,才交给服务端解析
187
- resolveOnServer: createViewRecordResolveOnServer(ctx, () => getViewRecordFromParent(flowContext, ctx)),
188
- });
189
- // embed 视图不注册 destroyView,afterSuccess 关闭弹窗时自然跳过
190
- // 顶层 popup 变量:弹窗记录/数据源/上级弹窗链(去重封装)
191
- registerPopupVariable(ctx, currentPage);
192
-
193
- const PageWithContext = observer(
194
- () => {
195
- // eslint-disable-next-line react-hooks/rules-of-hooks
196
- const mountedRef = React.useRef(false);
197
- // 支持 content 为函数,传递 currentPage
198
- // eslint-disable-next-line react-hooks/rules-of-hooks
199
- const pageContent = React.useMemo(
200
- () => (typeof content === 'function' ? content(currentPage, ctx) : content),
201
- [],
202
- );
203
- // 响应themeToken的响应式更新
204
- void ctx.themeToken;
205
- // eslint-disable-next-line react-hooks/rules-of-hooks
206
- React.useEffect(() => {
207
- config.onOpen?.(currentPage, ctx);
208
- }, []);
209
-
210
- if (config.inputArgs?.hidden?.value && !mountedRef.current) {
211
- return null;
212
- }
392
+ // Global embed container uses "replace" behavior. The previous view still owns beforeClose.
393
+ if (isGlobalEmbedContainer && globalEmbedActiveRef.current) {
394
+ const replacementToken = (globalEmbedReplacementTokenRef.current += 1);
395
+ const cancelOpen = () => onOpenCancelled?.();
396
+ let closeResult: Promise<boolean | void> | boolean | void;
397
+ try {
398
+ closeResult = closeReplacingGlobalEmbed(target, globalEmbedActiveRef.current);
399
+ } catch (error) {
400
+ cancelOpen();
401
+ throw error;
402
+ }
213
403
 
214
- mountedRef.current = true;
215
-
216
- return (
217
- <PageComponent
218
- ref={pageRef}
219
- hidden={config.inputArgs?.hidden?.value}
220
- {...restConfig}
221
- onClose={() => {
222
- currentPage.close(config.result);
223
- }}
224
- >
225
- {pageContent}
226
- </PageComponent>
404
+ if (isPromiseLike(closeResult)) {
405
+ return createPendingGlobalEmbedView(
406
+ Promise.resolve(closeResult).then(
407
+ (closed) => {
408
+ if (closed === false || replacementToken !== globalEmbedReplacementTokenRef.current) {
409
+ cancelOpen();
410
+ return { page: null };
411
+ }
412
+ return { page: openCurrentPage() };
413
+ },
414
+ (error) => {
415
+ cancelOpen();
416
+ throw error;
417
+ },
418
+ ),
419
+ viewInputArgs,
420
+ !!config.preventClose,
227
421
  );
228
- },
229
- {
230
- displayName: 'PageWithContext',
231
- },
232
- );
233
-
234
- const key = viewInputArgs?.viewUid || `page-${uuid}`;
235
- const page = (
236
- <FlowEngineProvider key={key} engine={scopedEngine}>
237
- <FlowViewContextProvider context={ctx}>
238
- <PageWithContext />
239
- </FlowViewContextProvider>
240
- </FlowEngineProvider>
241
- );
242
-
243
- if (target && target instanceof HTMLElement) {
244
- closeFunc = holderRef.current?.patchElement(ReactDOM.createPortal(page, target, key));
245
- } else {
246
- closeFunc = holderRef.current?.patchElement(page);
247
- }
422
+ }
248
423
 
249
- if (isGlobalEmbedContainer) {
250
- globalEmbedActiveRef.current = { destroy: currentPage.destroy };
424
+ if (closeResult === false) {
425
+ cancelOpen();
426
+ return createPendingGlobalEmbedView(Promise.resolve({ page: null }), viewInputArgs, !!config.preventClose);
427
+ }
251
428
  }
252
429
 
253
- return Object.assign(promise, currentPage);
430
+ return openCurrentPage();
254
431
  };
255
432
 
256
433
  const api = React.useMemo(() => ({ open }), []);