@jsb188/react 1.1.11 → 1.1.12

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;
39
+
40
+ export type OpenModalScreenFn = (data: ModalRequestParams | ModalPropsFn) => void;
35
41
 
36
- export type OpenModalScreenFn = (
37
- data: ModalRequestParams | ModalPropsFn,
38
- ) => void;
42
+ export type OpenModalPopUpFn = (data: ModalRequestParams | null, err?: Partial<ServerErrorObj>) => void;
39
43
 
40
- export type OpenModalPopUpFn = (
41
- data: ModalRequestParams | null,
42
- err?: Partial<ServerErrorObj>,
43
- ) => void;
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,13 @@ class ModalPopUp extends ModalScreen {
257
279
  const screenClass = new ModalScreen('screen');
258
280
  const popUpClass = new ModalPopUp('popup', POPUP_DEFAULT_VALUES);
259
281
 
282
+ /*
283
+ * Return the resolved preset of a pop up request (e.g. 'force_reload') without opening it.
284
+ */
285
+ export function getModalPopUpPreset(data: ModalRequestParams | null): string | null {
286
+ return popUpClass.open(data)?.preset || null;
287
+ }
288
+
260
289
  /**
261
290
  * Create handler functions
262
291
  */
@@ -265,19 +294,11 @@ const popUpClass = new ModalPopUp('popup', POPUP_DEFAULT_VALUES);
265
294
  * Build the next modal screen state from either a direct open request or a state updater function.
266
295
  */
267
296
 
268
- function getNextModalScreenState(
269
- data: ModalRequestParams | ModalPropsFn,
270
- prevScreen: ModalProps | null,
271
- ) {
297
+ function getNextModalScreenState(data: ModalRequestParams | ModalPropsFn, prevScreen: ModalProps | null) {
272
298
  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
299
+ const nextScreenValue = isStateUpdater ? data(prevScreen) : screenClass.open(data);
300
+
301
+ return isStateUpdater && nextScreenValue && prevScreen?.modalSessionKey && !nextScreenValue.modalSessionKey
281
302
  ? {
282
303
  ...nextScreenValue,
283
304
  modalSessionKey: prevScreen.modalSessionKey,
@@ -304,29 +325,41 @@ function composeOpenModalScreenFn(setScreen: ModalScreenSetter) {
304
325
  };
305
326
  }
306
327
 
307
- function composeCloseModalScreenFn(
308
- setScreen: (value: ModalProps | null) => void,
309
- ) {
328
+ function composeCloseModalScreenFn(setScreen: (value: ModalProps | null) => void) {
310
329
  return () => {
311
330
  setScreen(screenClass.close());
312
331
  };
313
332
  }
314
333
 
315
- function composeOpenModalPopUpFn(setPopUp: (value: ModalProps | null) => void) {
334
+ /*
335
+ * Open a popup without letting background alerts replace a required browser reload.
336
+ */
337
+ function composeOpenModalPopUpFn(setPopUp: ModalScreenSetter) {
316
338
  return (data: ModalRequestParams | null, err?: Partial<ServerErrorObj>) => {
317
339
  const nextPopUpState = popUpClass.open(data, err);
318
340
  if (nextPopUpState) {
319
- setPopUp(nextPopUpState);
341
+ setPopUp((previous) =>
342
+ previous?.preset === 'force_reload' ? previous : { ...nextPopUpState, modalSessionKey: getModalSessionKey() },
343
+ );
320
344
  } else {
321
345
  console.warn('Invalid {popUp} data:', data, err);
322
346
  }
323
347
  };
324
348
  }
325
349
 
326
- function composeCloseModalPopUpFn(
327
- setPopUp: (value: ModalProps | null) => void,
328
- ) {
329
- return () => {
350
+ /*
351
+ * Dismiss the active popup or a matching instance, retaining reload popups if the browser cancels navigation.
352
+ */
353
+ function composeCloseModalPopUpFn(setPopUp: (value: ModalProps | null) => void, getPopUp: () => ModalProps | null) {
354
+ return (modalSessionKey?: string) => {
355
+ const popUp = getPopUp();
356
+ if (modalSessionKey !== undefined && popUp?.modalSessionKey !== modalSessionKey) {
357
+ return;
358
+ }
359
+ if (popUp?.preset === 'force_reload') {
360
+ globalThis.location?.reload();
361
+ return;
362
+ }
330
363
  setPopUp(popUpClass.close());
331
364
  };
332
365
  }
@@ -337,13 +370,8 @@ function composeCloseModalPopUpFn(
337
370
 
338
371
  export function useModalScreen(): ModalScreenProps {
339
372
  const [screen, setScreen] = useAtom(screenClass.state);
340
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
341
- setScreen,
342
- ]);
343
- const closeModalScreen = useCallback(
344
- composeCloseModalScreenFn(setScreen),
345
- [],
346
- );
373
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
374
+ const closeModalScreen = useCallback(composeCloseModalScreenFn(setScreen), []);
347
375
 
348
376
  return {
349
377
  screen,
@@ -352,15 +380,54 @@ export function useModalScreen(): ModalScreenProps {
352
380
  };
353
381
  }
354
382
 
383
+ /*
384
+ * Read the current modal screen during deferred cleanup without capturing an outdated render.
385
+ */
386
+ export function useGetModalScreen() {
387
+ const store = useStore();
388
+ return useCallback(() => store.get(screenClass.state), [store]);
389
+ }
390
+
391
+ /*
392
+ * Read popup ownership synchronously before delivering events to a potentially replaced popup.
393
+ */
394
+ export function useGetModalPopUp() {
395
+ const store = useStore();
396
+ return useCallback(() => store.get(popUpClass.state), [store]);
397
+ }
398
+
399
+ /*
400
+ * Keep global user-driven dismissal from closing a modal screen during a protected operation.
401
+ */
402
+ export function useModalScreenCloseGuard(guardId: string, active: boolean) {
403
+ const updateCloseGuard = useSetAtom(updateModalScreenCloseGuardState);
404
+
405
+ useEffect(() => {
406
+ if (!active) {
407
+ return;
408
+ }
409
+
410
+ updateCloseGuard({ active: true, guardId });
411
+ return () => {
412
+ updateCloseGuard({ active: false, guardId });
413
+ };
414
+ }, [active, guardId, updateCloseGuard]);
415
+ }
416
+
417
+ /*
418
+ * Return whether any mounted flow currently protects the active modal screen from user dismissal.
419
+ */
420
+ export function useModalScreenCloseGuarded() {
421
+ return useAtomValue(modalScreenCloseGuardsState).length > 0;
422
+ }
423
+
355
424
  /**
356
425
  * Use screen open function
357
426
  */
358
427
 
359
428
  export function useOpenModalScreen(): OpenModalScreenFn {
360
429
  const setScreen = useSetAtom(screenClass.state);
361
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
362
- setScreen,
363
- ]);
430
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
364
431
 
365
432
  return openModalScreen;
366
433
  }
@@ -370,9 +437,13 @@ export function useOpenModalScreen(): OpenModalScreenFn {
370
437
  */
371
438
 
372
439
  export function useModalPopUp(): ModalPopUpProps {
440
+ const store = useStore();
373
441
  const [popUp, setPopUp] = useAtom(popUpClass.state);
374
442
  const openModalPopUp = useCallback(composeOpenModalPopUpFn(setPopUp), []);
375
- const closeModalPopUp = useCallback(composeCloseModalPopUpFn(setPopUp), []);
443
+ const closeModalPopUp = useCallback(
444
+ composeCloseModalPopUpFn(setPopUp, () => store.get(popUpClass.state)),
445
+ [store],
446
+ );
376
447
 
377
448
  return {
378
449
  popUp,
@@ -386,18 +457,17 @@ export function useModalPopUp(): ModalPopUpProps {
386
457
  */
387
458
 
388
459
  export function useModalHandlers(): ModalHandlerProps {
460
+ const store = useStore();
389
461
  const setScreen = useSetAtom(screenClass.state);
390
462
  const setPopUp = useSetAtom(popUpClass.state);
391
463
 
392
- const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [
393
- setScreen,
394
- ]);
395
- const closeModalScreen = useCallback(
396
- composeCloseModalScreenFn(setScreen),
397
- [],
398
- );
464
+ const openModalScreen = useCallback(composeOpenModalScreenFn(setScreen), [setScreen]);
465
+ const closeModalScreen = useCallback(composeCloseModalScreenFn(setScreen), []);
399
466
  const openModalPopUp = useCallback(composeOpenModalPopUpFn(setPopUp), []);
400
- const closeModalPopUp = useCallback(composeCloseModalPopUpFn(setPopUp), []);
467
+ const closeModalPopUp = useCallback(
468
+ composeCloseModalPopUpFn(setPopUp, () => store.get(popUpClass.state)),
469
+ [store],
470
+ );
401
471
 
402
472
  return {
403
473
  openModalScreen,