@jsb188/react 1.1.11 → 1.1.13

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.
package/states/modal.ts CHANGED
@@ -1,20 +1,26 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import type { ColorEnum, ServerErrorObj } from '@jsb188/app/types/app.d.ts';
3
- import { atom, useAtom, useSetAtom } from 'jotai';
4
- import { useCallback } from 'react';
3
+ import { atom, useAtom, useAtomValue, useSetAtom, useStore } from 'jotai';
4
+ import { useCallback, useEffect } from 'react';
5
+ import { setKeyboardLayerOpenState } from './keyboardLayer';
5
6
 
6
7
  /**
7
8
  * Types
8
9
  */
9
10
 
10
- interface ModalRequestParams {
11
+ export interface ModalInitialContextProps<Context = Record<string, any>> {
12
+ // Already available display data; each screen keeps its live data source authoritative.
13
+ initialContext?: Context;
14
+ }
15
+
16
+ interface ModalRequestParams extends ModalInitialContextProps {
11
17
  name: string;
12
18
  preset?: string;
13
19
  color?: ColorEnum | null;
14
20
  props?: Record<string, any>;
15
21
  }
16
22
 
17
- export interface ModalProps {
23
+ export interface ModalProps extends ModalInitialContextProps {
18
24
  name: string;
19
25
  preset: string | null;
20
26
  modalSessionKey?: string;
@@ -29,18 +35,13 @@ export interface ModalPopUpComponentProps {
29
35
  }
30
36
 
31
37
  type ModalPropsFn = (prev: ModalProps | null) => ModalProps | null;
32
- type ModalScreenSetter = (
33
- value: ModalProps | null | ((prev: ModalProps | null) => ModalProps | null),
34
- ) => void;
38
+ type ModalScreenSetter = (value: ModalProps | null | ((prev: ModalProps | null) => ModalProps | null)) => void;
35
39
 
36
- export type OpenModalScreenFn = (
37
- data: ModalRequestParams | ModalPropsFn,
38
- ) => void;
40
+ export type OpenModalScreenFn = (data: ModalRequestParams | ModalPropsFn) => void;
39
41
 
40
- export type OpenModalPopUpFn = (
41
- data: ModalRequestParams | null,
42
- err?: Partial<ServerErrorObj>,
43
- ) => void;
42
+ export type OpenModalPopUpFn = (data: ModalRequestParams | null, err?: Partial<ServerErrorObj>) => void;
43
+
44
+ export type CloseModalPopUpFn = (modalSessionKey?: string) => void;
44
45
 
45
46
  export interface ModalScreenProps {
46
47
  screen: ModalProps | null;
@@ -51,7 +52,7 @@ export interface ModalScreenProps {
51
52
  export interface ModalPopUpProps {
52
53
  popUp: ModalProps | null;
53
54
  openModalPopUp: OpenModalPopUpFn;
54
- closeModalPopUp: () => void;
55
+ closeModalPopUp: CloseModalPopUpFn;
55
56
  }
56
57
 
57
58
  export interface ModalHandlerProps {
@@ -59,7 +60,7 @@ export interface ModalHandlerProps {
59
60
  openModalScreen: OpenModalScreenFn;
60
61
  openModalPopUp: OpenModalPopUpFn;
61
62
  closeModalScreen: () => void;
62
- closeModalPopUp: () => void;
63
+ closeModalPopUp: CloseModalPopUpFn;
63
64
  }
64
65
 
65
66
  export interface ModalHookProps extends ModalScreenProps, ModalPopUpProps {}
@@ -82,7 +83,7 @@ export const POPUP_DEFAULT_VALUES = {
82
83
  },
83
84
  not_verified_email: {
84
85
  iconName: 'mailbox',
85
- title: 'form.check_email',
86
+ title: 'c.check_email',
86
87
  message: 'auth.not_verified_yet',
87
88
  },
88
89
  not_allowed_permission: {
@@ -101,32 +102,50 @@ export const POPUP_DEFAULT_VALUES = {
101
102
  message: 'app.leaving_app_desc',
102
103
  confirmText: 'app.link_yes',
103
104
  },
104
- '20020': {
105
- // Not allowed in chat
106
- iconName: 'lock-square-rounded-filled',
107
- },
108
- '10000': {
109
- preset: 'force_reload',
110
- // iconName: '..', // This is controlled via i18n now
111
- },
112
- '10012': {
113
- preset: 'force_reload',
114
- title: 'error.login_changed',
115
- iconName: 'question-circle', // Deprecated; icon names are controlled via i18n now
116
- },
117
105
  } as Record<string, Record<string, string>>;
118
106
 
107
+ const modalScreenCloseGuardsState = atom<string[]>([]);
108
+
109
+ /*
110
+ * Add or remove one mounted modal-screen close guard without disturbing other owners.
111
+ */
112
+ const updateModalScreenCloseGuardState = atom(null, (get, set, p: { active: boolean; guardId: string }) => {
113
+ const closeGuards = get(modalScreenCloseGuardsState);
114
+ set(
115
+ modalScreenCloseGuardsState,
116
+ p.active
117
+ ? closeGuards.includes(p.guardId)
118
+ ? closeGuards
119
+ : [p.guardId, ...closeGuards]
120
+ : closeGuards.filter((guardId) => guardId !== p.guardId),
121
+ );
122
+ });
123
+
119
124
  /**
120
125
  * Modal screen class
121
126
  */
122
127
 
123
128
  class ModalScreen {
124
129
  readonly name: string;
125
- readonly state = atom<ModalProps | null>(null);
130
+ readonly state;
126
131
  readonly defaultValues?: Record<string, any>;
127
132
 
128
133
  constructor(name: string, defaultValues?: Record<string, any>) {
129
134
  this.name = `modal_${name}_state`;
135
+ const valueState = atom<ModalProps | null>(null);
136
+ this.state = atom(
137
+ (get) => get(valueState),
138
+ (get, set, value: ModalProps | null | ((previous: ModalProps | null) => ModalProps | null)) => {
139
+ const previous = get(valueState);
140
+ const next = typeof value === 'function' ? value(previous) : value;
141
+ set(valueState, next);
142
+ set(setKeyboardLayerOpenState, {
143
+ layer: name === 'screen' ? 'modal' : 'popup',
144
+ open: !!next,
145
+ reset: !!previous && !!next && (name === 'screen' ? previous.modalSessionKey !== next.modalSessionKey : previous !== next),
146
+ });
147
+ },
148
+ );
130
149
  if (defaultValues) {
131
150
  this.defaultValues = defaultValues;
132
151
  }
@@ -134,7 +153,7 @@ class ModalScreen {
134
153
 
135
154
  open(data: ModalRequestParams): ModalProps | null {
136
155
  if (data) {
137
- const { name, color, props } = data;
156
+ const { name, color, props, initialContext } = data;
138
157
  const values = this.defaultValues?.[name ?? ''];
139
158
 
140
159
  return {
@@ -142,7 +161,8 @@ class ModalScreen {
142
161
  color,
143
162
  ...values,
144
163
  ...props,
145
- modalSessionKey: getModalScreenSessionKey(),
164
+ initialContext,
165
+ modalSessionKey: getModalSessionKey(),
146
166
  };
147
167
  }
148
168
 
@@ -155,11 +175,11 @@ class ModalScreen {
155
175
  }
156
176
 
157
177
  /*
158
- * Create a unique session key for each fresh modal screen open request.
178
+ * Create a unique session key for each fresh modal screen or popup open request.
159
179
  */
160
180
 
161
- function getModalScreenSessionKey() {
162
- return `modal-screen-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
181
+ function getModalSessionKey() {
182
+ return `modal-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
163
183
  }
164
184
 
165
185
  /**
@@ -169,18 +189,16 @@ function getModalScreenSessionKey() {
169
189
  class ModalPopUp extends ModalScreen {
170
190
  readonly name: string = 'modal_popup_state';
171
191
 
172
- open(
173
- data: ModalRequestParams | null,
174
- error?: Partial<ServerErrorObj>,
175
- ): ModalProps | null {
192
+ open(data: ModalRequestParams | null, error?: Partial<ServerErrorObj>): ModalProps | null {
176
193
  if (data) {
177
- const { preset, name, props } = data;
194
+ const { preset, name, props, initialContext } = data;
178
195
  const values = this.defaultValues?.[name ?? ''];
196
+ const translatedPreset = i18n.has(`error.${name}_preset`) ? i18n.t(`error.${name}_preset`) : null;
179
197
 
180
198
  let updatedAlertValue: ModalProps = {
181
199
  // Template values
182
200
  name,
183
- preset: preset || 'normal',
201
+ preset: preset || translatedPreset || 'normal',
184
202
  // Alert props
185
203
  id: `alert-${name || 'normal'}`,
186
204
  iconName: null,
@@ -190,6 +208,8 @@ class ModalPopUp extends ModalScreen {
190
208
 
191
209
  if (values?.iconName) {
192
210
  updatedAlertValue.iconName = values.iconName;
211
+ } else if (i18n.has(`error.${name}_icon`)) {
212
+ updatedAlertValue.iconName = i18n.t(`error.${name}_icon`);
193
213
  }
194
214
 
195
215
  // NOTE: i18n() isn't ready yet, so I have to use i18n.t(..) in the logic
@@ -214,30 +234,32 @@ class ModalPopUp extends ModalScreen {
214
234
  };
215
235
  }
216
236
 
217
- if (!updatedAlertValue.title && !isNaN(Number(name))) {
237
+ if (!updatedAlertValue.title && !Number.isNaN(Number(name))) {
218
238
  updatedAlertValue.title = i18n.t('error.error');
219
239
  }
220
240
 
221
- return updatedAlertValue;
241
+ return { ...updatedAlertValue, initialContext };
222
242
  } else if (error) {
223
243
  const { errorCode } = error;
224
244
  const {
225
245
  iconName: defIconName,
246
+ preset: defPreset,
226
247
  title: defTitle,
227
248
  message: defMessage,
228
249
  ...values
229
250
  } = this.defaultValues?.[errorCode ?? ''] || {};
251
+ const translatedIconName = errorCode && i18n.has(`error.${errorCode}_icon`) ? i18n.t(`error.${errorCode}_icon`) : undefined; // Use undefined to show the default icon; null intentionally hides it.
252
+ const translatedPreset = errorCode && i18n.has(`error.${errorCode}_preset`) ? i18n.t(`error.${errorCode}_preset`) : null;
230
253
 
231
254
  return {
232
255
  // Template values
233
256
  name: 'ERROR',
234
- preset: 'normal',
257
+ preset: translatedPreset || defPreset || 'normal',
235
258
  // Alert props
236
259
  id: `gql-${errorCode}`,
237
- iconName: error.iconName || defIconName,
260
+ iconName: error.iconName || defIconName || translatedIconName,
238
261
  title: error.title || defTitle || i18n.t('error.error'),
239
- message:
240
- error.message || defMessage || i18n.t('error.unknown_error_msg'),
262
+ message: error.message || defMessage || i18n.t('error.unknown_error_msg'),
241
263
  ...values,
242
264
  };
243
265
  }
@@ -257,6 +279,24 @@ class ModalPopUp extends ModalScreen {
257
279
  const screenClass = new ModalScreen('screen');
258
280
  const popUpClass = new ModalPopUp('popup', POPUP_DEFAULT_VALUES);
259
281
 
282
+ // Remount the modal renderer to discard a screen already playing its exit animation.
283
+ export const modalScreenHostKeyState = atom(0);
284
+
285
+ /*
286
+ * Dismiss the current screen immediately, including an exit animation retained in its renderer.
287
+ */
288
+ export const resetModalScreenState = atom(null, (get, set) => {
289
+ set(screenClass.state, null);
290
+ set(modalScreenHostKeyState, get(modalScreenHostKeyState) + 1);
291
+ });
292
+
293
+ /*
294
+ * Return the resolved preset of a pop up request (e.g. 'force_reload') without opening it.
295
+ */
296
+ export function getModalPopUpPreset(data: ModalRequestParams | null): string | null {
297
+ return popUpClass.open(data)?.preset || null;
298
+ }
299
+
260
300
  /**
261
301
  * Create handler functions
262
302
  */
@@ -265,19 +305,11 @@ const popUpClass = new ModalPopUp('popup', POPUP_DEFAULT_VALUES);
265
305
  * Build the next modal screen state from either a direct open request or a state updater function.
266
306
  */
267
307
 
268
- function getNextModalScreenState(
269
- data: ModalRequestParams | ModalPropsFn,
270
- prevScreen: ModalProps | null,
271
- ) {
308
+ function getNextModalScreenState(data: ModalRequestParams | ModalPropsFn, prevScreen: ModalProps | null) {
272
309
  const isStateUpdater = typeof data === 'function';
273
- const nextScreenValue = isStateUpdater
274
- ? data(prevScreen)
275
- : screenClass.open(data);
276
-
277
- return isStateUpdater &&
278
- nextScreenValue &&
279
- prevScreen?.modalSessionKey &&
280
- !nextScreenValue.modalSessionKey
310
+ const nextScreenValue = isStateUpdater ? data(prevScreen) : screenClass.open(data);
311
+
312
+ return isStateUpdater && nextScreenValue && prevScreen?.modalSessionKey && !nextScreenValue.modalSessionKey
281
313
  ? {
282
314
  ...nextScreenValue,
283
315
  modalSessionKey: prevScreen.modalSessionKey,
@@ -304,29 +336,41 @@ function composeOpenModalScreenFn(setScreen: ModalScreenSetter) {
304
336
  };
305
337
  }
306
338
 
307
- function composeCloseModalScreenFn(
308
- setScreen: (value: ModalProps | null) => void,
309
- ) {
339
+ function composeCloseModalScreenFn(setScreen: (value: ModalProps | null) => void) {
310
340
  return () => {
311
341
  setScreen(screenClass.close());
312
342
  };
313
343
  }
314
344
 
315
- function composeOpenModalPopUpFn(setPopUp: (value: ModalProps | null) => void) {
345
+ /*
346
+ * Open a popup without letting background alerts replace a required browser reload.
347
+ */
348
+ function composeOpenModalPopUpFn(setPopUp: ModalScreenSetter) {
316
349
  return (data: ModalRequestParams | null, err?: Partial<ServerErrorObj>) => {
317
350
  const nextPopUpState = popUpClass.open(data, err);
318
351
  if (nextPopUpState) {
319
- setPopUp(nextPopUpState);
352
+ setPopUp((previous) =>
353
+ previous?.preset === 'force_reload' ? previous : { ...nextPopUpState, modalSessionKey: getModalSessionKey() },
354
+ );
320
355
  } else {
321
356
  console.warn('Invalid {popUp} data:', data, err);
322
357
  }
323
358
  };
324
359
  }
325
360
 
326
- function composeCloseModalPopUpFn(
327
- setPopUp: (value: ModalProps | null) => void,
328
- ) {
329
- return () => {
361
+ /*
362
+ * Dismiss the active popup or a matching instance, retaining reload popups if the browser cancels navigation.
363
+ */
364
+ function composeCloseModalPopUpFn(setPopUp: (value: ModalProps | null) => void, getPopUp: () => ModalProps | null) {
365
+ return (modalSessionKey?: string) => {
366
+ const popUp = getPopUp();
367
+ if (modalSessionKey !== undefined && popUp?.modalSessionKey !== modalSessionKey) {
368
+ return;
369
+ }
370
+ if (popUp?.preset === 'force_reload') {
371
+ globalThis.location?.reload();
372
+ return;
373
+ }
330
374
  setPopUp(popUpClass.close());
331
375
  };
332
376
  }
@@ -337,13 +381,8 @@ function composeCloseModalPopUpFn(
337
381
 
338
382
  export function useModalScreen(): ModalScreenProps {
339
383
  const [screen, setScreen] = useAtom(screenClass.state);
340
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
341
- setScreen,
342
- ]);
343
- const closeModalScreen = useCallback(
344
- composeCloseModalScreenFn(setScreen),
345
- [],
346
- );
384
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
385
+ const closeModalScreen = useCallback(composeCloseModalScreenFn(setScreen), []);
347
386
 
348
387
  return {
349
388
  screen,
@@ -352,15 +391,54 @@ export function useModalScreen(): ModalScreenProps {
352
391
  };
353
392
  }
354
393
 
394
+ /*
395
+ * Read the current modal screen during deferred cleanup without capturing an outdated render.
396
+ */
397
+ export function useGetModalScreen() {
398
+ const store = useStore();
399
+ return useCallback(() => store.get(screenClass.state), [store]);
400
+ }
401
+
402
+ /*
403
+ * Read popup ownership synchronously before delivering events to a potentially replaced popup.
404
+ */
405
+ export function useGetModalPopUp() {
406
+ const store = useStore();
407
+ return useCallback(() => store.get(popUpClass.state), [store]);
408
+ }
409
+
410
+ /*
411
+ * Keep global user-driven dismissal from closing a modal screen during a protected operation.
412
+ */
413
+ export function useModalScreenCloseGuard(guardId: string, active: boolean) {
414
+ const updateCloseGuard = useSetAtom(updateModalScreenCloseGuardState);
415
+
416
+ useEffect(() => {
417
+ if (!active) {
418
+ return;
419
+ }
420
+
421
+ updateCloseGuard({ active: true, guardId });
422
+ return () => {
423
+ updateCloseGuard({ active: false, guardId });
424
+ };
425
+ }, [active, guardId, updateCloseGuard]);
426
+ }
427
+
428
+ /*
429
+ * Return whether any mounted flow currently protects the active modal screen from user dismissal.
430
+ */
431
+ export function useModalScreenCloseGuarded() {
432
+ return useAtomValue(modalScreenCloseGuardsState).length > 0;
433
+ }
434
+
355
435
  /**
356
436
  * Use screen open function
357
437
  */
358
438
 
359
439
  export function useOpenModalScreen(): OpenModalScreenFn {
360
440
  const setScreen = useSetAtom(screenClass.state);
361
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
362
- setScreen,
363
- ]);
441
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
364
442
 
365
443
  return openModalScreen;
366
444
  }
@@ -370,9 +448,13 @@ export function useOpenModalScreen(): OpenModalScreenFn {
370
448
  */
371
449
 
372
450
  export function useModalPopUp(): ModalPopUpProps {
451
+ const store = useStore();
373
452
  const [popUp, setPopUp] = useAtom(popUpClass.state);
374
453
  const openModalPopUp = useCallback(composeOpenModalPopUpFn(setPopUp), []);
375
- const closeModalPopUp = useCallback(composeCloseModalPopUpFn(setPopUp), []);
454
+ const closeModalPopUp = useCallback(
455
+ composeCloseModalPopUpFn(setPopUp, () => store.get(popUpClass.state)),
456
+ [store],
457
+ );
376
458
 
377
459
  return {
378
460
  popUp,
@@ -386,18 +468,17 @@ export function useModalPopUp(): ModalPopUpProps {
386
468
  */
387
469
 
388
470
  export function useModalHandlers(): ModalHandlerProps {
471
+ const store = useStore();
389
472
  const setScreen = useSetAtom(screenClass.state);
390
473
  const setPopUp = useSetAtom(popUpClass.state);
391
474
 
392
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
393
- setScreen,
394
- ]);
395
- const closeModalScreen = useCallback(
396
- composeCloseModalScreenFn(setScreen),
397
- [],
398
- );
475
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
476
+ const closeModalScreen = useCallback(composeCloseModalScreenFn(setScreen), []);
399
477
  const openModalPopUp = useCallback(composeOpenModalPopUpFn(setPopUp), []);
400
- const closeModalPopUp = useCallback(composeCloseModalPopUpFn(setPopUp), []);
478
+ const closeModalPopUp = useCallback(
479
+ composeCloseModalPopUpFn(setPopUp, () => store.get(popUpClass.state)),
480
+ [store],
481
+ );
401
482
 
402
483
  return {
403
484
  openModalScreen,