@jsb188/react 1.0.4 → 1.1.3

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/package.json CHANGED
@@ -1,22 +1,20 @@
1
1
  {
2
2
  "name": "@jsb188/react",
3
- "version": "1.0.4",
3
+ "version": "1.1.3",
4
4
  "description": "Contains react (and DOM) related utils and hooks.",
5
5
  "license": "ISC",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "exports": {
9
9
  "./states": "./states/index.ts",
10
- "./dom": "./utils/dom.ts",
11
10
  "./hooks": "./utils/hooks.ts",
12
- "./icons": "./icons/Icon.tsx",
13
- "./priorityTimeout": "./utils/priorityTimeout.ts",
14
- "./types/dom": "./types/dom.d.ts"
11
+ "./schema": "./utils/schema.ts",
12
+ "./types/PopOver.d": "./types/PopOver.d.ts"
15
13
  },
16
14
  "peerDependencies": {
17
- "@jsb188/app": "^1.0.4",
18
- "jotai": "^2.12.1",
19
- "react": "^18.2.0"
15
+ "@jsb188/app": "1.1.3",
16
+ "jotai": "^2.12.5",
17
+ "react": "^19.1.0"
20
18
  },
21
19
  "scripts": {
22
20
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -0,0 +1,418 @@
1
+ import { clearAppCache, fetchLightModeSetting, isSystemDarkMode, saveAuthTokenToPlatform } from '@jsb188/app/platform';
2
+ import type { AccountData, AccountSettings, AuthenticationData, LightModeEnum } from '@jsb188/app/types/auth.d';
3
+ import { setAuthToken } from '@jsb188/app/utils/api';
4
+ import { guessFirstName, buildSingleText } from '@jsb188/app/utils/string';
5
+ import { createContext, useContext } from 'react';
6
+
7
+ /**
8
+ * Type; Reducer action for App Context
9
+ */
10
+
11
+ type AppContextAction = {
12
+ __type: (
13
+ // App initialization
14
+ | 'APP_INIT'
15
+ // Auth setup
16
+ | 'APP_LOGIN'
17
+ | 'APP_GUEST'
18
+ | 'APP_EDIT_AUTH'
19
+ | 'APP_EDIT_ACCOUNT'
20
+ // Account theme
21
+ | 'APP_THEME'
22
+ | 'APP_SYSTEM_LIGHT_MODE'
23
+ | 'APP_LIGHT_MODE'
24
+ // App events
25
+ | 'APP_KEY_DOWN'
26
+ );
27
+ data?: any;
28
+ };
29
+
30
+ export type AppContextDispatch = (action: AppContextAction) => void;
31
+
32
+ /**
33
+ * Types
34
+ */
35
+
36
+ export type AppAppearanceType = {
37
+ realLightMode: LightModeEnum;
38
+ lightMode: LightModeEnum;
39
+ previewLightMode: LightModeEnum;
40
+ previewTheme: string | null;
41
+ };
42
+
43
+ export type AppContextData = {
44
+ // Required for app
45
+ init: 0 | 1 | 2; // 0 = not initialized,; 1 = loading; 2 = initialized
46
+ authorization: string; // This is token
47
+ networkError: boolean;
48
+
49
+ // Authentication data
50
+ account: AccountData | null;
51
+ primaryOrganizationId: string | null;
52
+
53
+ // Account settings & state
54
+ settings: AccountSettings;
55
+ activated: boolean;
56
+ hasPassword: boolean;
57
+ version: string | null;
58
+
59
+ // Preview theme overrides active theme
60
+ systemLightMode: 'LIGHT' | 'DARK';
61
+ previewLightMode: LightModeEnum | null;
62
+ previewTheme: string | null;
63
+
64
+ // This needs to get migrated to Jotai
65
+ keyDown: {
66
+ metaKey: boolean;
67
+ pressed: string | null;
68
+ alert: boolean;
69
+ modal: boolean;
70
+ };
71
+ };
72
+
73
+ /**
74
+ * Context default values
75
+ */
76
+
77
+ export const DEFAULT_APP_CONTEXT = {
78
+ init: 0,
79
+ authorization: '',
80
+ networkError: false,
81
+
82
+ account: null,
83
+ primaryOrganizationId: null,
84
+
85
+ settings: {
86
+ theme: null,
87
+ lightMode: 'LIGHT',
88
+ timeZone: null,
89
+ showSelfAvatar: true,
90
+ isBubbleOther: false,
91
+ showOtherAvatar: false,
92
+ },
93
+ activated: false,
94
+ hasPassword: false,
95
+ version: null,
96
+
97
+ systemLightMode: 'LIGHT',
98
+ previewLightMode: null,
99
+ previewTheme: null,
100
+
101
+ keyDown: {
102
+ metaKey: false,
103
+ pressed: null,
104
+ alert: false,
105
+ modal: false,
106
+ }
107
+ } as AppContextData;
108
+
109
+ /**
110
+ * Helper for light mode
111
+ */
112
+
113
+ function ensureLightModeSetting(lightMode?: LightModeEnum): LightModeEnum {
114
+ return lightMode && ['LIGHT', 'DARK', 'SYSTEM'].includes(lightMode || '') ? lightMode : 'LIGHT';
115
+ }
116
+
117
+ /**
118
+ * App log in with Promise
119
+ */
120
+
121
+ export function onAccountLogin(auth: any, dispatchApp: AppContextDispatch, otherCB?: (auth: any) => void) {
122
+ if (auth && auth?.token && auth.activated && auth.account) {
123
+ console.log('.. 🥝 logged into account ..');
124
+
125
+ saveAuthTokenToPlatform(auth.token, () => {
126
+ clearAppCache();
127
+ dispatchApp({
128
+ __type: 'APP_LOGIN',
129
+ data: auth,
130
+ });
131
+
132
+ if (otherCB) {
133
+ otherCB(auth);
134
+ }
135
+ });
136
+ } else {
137
+ console.log(auth);
138
+ console.warn('Developer error in onAccountLogin()');
139
+ }
140
+ }
141
+
142
+ /**
143
+ * App guest init
144
+ */
145
+
146
+ export function onGuestInit(error: any, dispatchApp: AppContextDispatch) {
147
+ fetchLightModeSetting(null, (lightMode) => {
148
+ dispatchApp({
149
+ __type: 'APP_GUEST',
150
+ data: {
151
+ error,
152
+ lightMode,
153
+ },
154
+ });
155
+ });
156
+ }
157
+
158
+ /**
159
+ * Get active/current or preview theme
160
+ */
161
+
162
+ export function getTheme(
163
+ appState: AppContextData,
164
+ priority: 'PREVIEW' | 'ACCOUNT' | 'ACTIVE'
165
+ ) {
166
+ let lightMode = appState.previewLightMode || appState.settings.lightMode;
167
+ if (lightMode === 'SYSTEM') {
168
+ lightMode = appState.systemLightMode;
169
+ }
170
+
171
+ const theme = (
172
+ (priority === 'PREVIEW' && appState.previewTheme) ||
173
+ appState.settings.theme ||
174
+ ''
175
+ );
176
+
177
+ return {
178
+ lightMode,
179
+ theme,
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Get theme; but prioritize preview theme
185
+ */
186
+
187
+ export function getPreviewAppearance(appState: AppContextData) {
188
+ let realLightMode = appState.previewLightMode || appState.settings.lightMode;
189
+ if (realLightMode === 'SYSTEM') {
190
+ realLightMode = appState.systemLightMode;
191
+ }
192
+
193
+ return {
194
+ realLightMode,
195
+ lightMode: appState.settings.lightMode,
196
+ previewLightMode: appState.previewLightMode,
197
+ previewTheme: appState.previewTheme,
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Merge sign in mutation auth values to context
203
+ */
204
+
205
+ export function mergeAuthToDefaultValues(
206
+ auth?: AuthenticationData | null,
207
+ authToken?: string | null,
208
+ ) {
209
+ if (auth?.token && auth?.account?.id) {
210
+ let systemLightMode = 'LIGHT';
211
+ if (isSystemDarkMode()) {
212
+ systemLightMode = 'DARK';
213
+ }
214
+
215
+ setAuthToken(auth.token);
216
+
217
+ const authSettings = {
218
+ ...DEFAULT_APP_CONTEXT.settings,
219
+ ...auth.settings
220
+ };
221
+
222
+ authSettings.lightMode = ensureLightModeSetting(authSettings.lightMode);
223
+
224
+ return {
225
+ ...DEFAULT_APP_CONTEXT,
226
+ init: 1, // Always 1 because we're always using SSR for authentication
227
+ authorization: auth.token,
228
+ account: auth.account,
229
+ primaryOrganizationId: auth.primaryOrganizationId || null,
230
+ settings: authSettings || DEFAULT_APP_CONTEXT.settings,
231
+ hasPassword: auth.hasPassword,
232
+ version: auth.version,
233
+
234
+ // Theme
235
+ systemLightMode,
236
+ previewLightMode: null,
237
+ previewTheme: null,
238
+ };
239
+ } else if (authToken) {
240
+ setAuthToken(authToken);
241
+ return {
242
+ ...DEFAULT_APP_CONTEXT,
243
+ authorization: authToken || ''
244
+ };
245
+ }
246
+
247
+ setAuthToken(null);
248
+ return DEFAULT_APP_CONTEXT;
249
+ }
250
+
251
+ /**
252
+ * App reducer
253
+ */
254
+
255
+ export const appReducer = (state: Partial<AppContextData>, action: AppContextAction) => {
256
+ const { __type, data } = action;
257
+
258
+ switch (__type) {
259
+ case 'APP_INIT': {
260
+ return {
261
+ ...state,
262
+ init: state.init === 1 ? 2 : 1,
263
+ };
264
+ }
265
+ case 'APP_LOGIN': {
266
+ return mergeAuthToDefaultValues(data);
267
+ }
268
+ case 'APP_GUEST': {
269
+ const networkError = data.error?.errorCode === 'network_error';
270
+ if (networkError) {
271
+ console.log('.. ❌ network error ..');
272
+ } else {
273
+ console.log('.. 🥝 guest entered ..');
274
+ }
275
+
276
+ clearAppCache();
277
+ setAuthToken(null);
278
+
279
+ return {
280
+ ...DEFAULT_APP_CONTEXT,
281
+ init: 2,
282
+ authorization: '',
283
+ networkError,
284
+
285
+ // Theme
286
+ previewLightMode: null,
287
+ previewTheme: null,
288
+ };
289
+ }
290
+ case 'APP_EDIT_AUTH': {
291
+ if (data.id === state.account?.id) {
292
+ return {
293
+ ...state,
294
+ hasPassword: typeof data.hasPassword === 'boolean' ? data.hasPassword : state.hasPassword,
295
+ };
296
+ }
297
+ return state;
298
+ }
299
+ case 'APP_EDIT_ACCOUNT': {
300
+ if (data.id === state.account?.id) {
301
+ return {
302
+ ...state,
303
+
304
+ // Account
305
+ account: {
306
+ ...state.account,
307
+ ...data,
308
+ plus: !data.plus ? state.account?.plus : {
309
+ ...state.account?.plus,
310
+ ...data.plus,
311
+ },
312
+ },
313
+ settings: {
314
+ ...DEFAULT_APP_CONTEXT.settings,
315
+ ...data.settings,
316
+ }
317
+ };
318
+ }
319
+ return state;
320
+ }
321
+ case 'APP_THEME': {
322
+ if (!data?.preview) {
323
+ // Active theme
324
+ return {
325
+ ...state,
326
+ previewTheme: null,
327
+ };
328
+ }
329
+
330
+ // Is preview theme
331
+ return {
332
+ ...state,
333
+ previewTheme: data.theme,
334
+ };
335
+ }
336
+ case 'APP_LIGHT_MODE': {
337
+ if (!data.lightMode && !data.preview) {
338
+ console.warn('Developer error in setLightMode(): You cannot set active lightMode to null.');
339
+ return state;
340
+ } else if (data.preview) {
341
+ return {
342
+ ...state,
343
+ previewLightMode: data.lightMode,
344
+ };
345
+ }
346
+
347
+ return {
348
+ ...state,
349
+ previewLightMode: null,
350
+ };
351
+ }
352
+ case 'APP_SYSTEM_LIGHT_MODE': {
353
+ return {
354
+ ...state,
355
+ systemLightMode: data.lightMode,
356
+ };
357
+ }
358
+ case 'APP_KEY_DOWN': {
359
+ if (typeof data.pressed !=='string' && data.pressed !== null) {
360
+ return state;
361
+ }
362
+
363
+ return {
364
+ ...state,
365
+ keyDown: {
366
+ ...state.keyDown,
367
+ ...data,
368
+ }
369
+ };
370
+ }
371
+ default:
372
+ throw new Error('App Reducer Error: [' + __type + ']');
373
+ }
374
+ };
375
+
376
+ export const AppContext = createContext({
377
+ appState: DEFAULT_APP_CONTEXT as AppContextData,
378
+ dispatchApp: (() => {
379
+ console.warn('AppContext has been re-initialized due to hot refresh.');
380
+ }) as AppContextDispatch
381
+ });
382
+
383
+ /**
384
+ * Use current account
385
+ */
386
+
387
+ export function useCurrentAccount() {
388
+ const { appState: { activated, hasPassword, version, account, settings, primaryOrganizationId } } = useContext(AppContext);
389
+ const hasName = !!account?.profile?.firstName || !!account?.profile?.lastName;
390
+ const fullName = buildSingleText([account?.profile?.firstName, account?.profile?.lastName], ' ');
391
+ const displayName = guessFirstName(fullName, 8);
392
+
393
+ return {
394
+ // App state
395
+ account,
396
+ settings,
397
+ activated,
398
+ hasPassword,
399
+ version,
400
+
401
+ // Computed
402
+ loggedIn: !!account?.id,
403
+ hasName,
404
+ fullName,
405
+ displayName,
406
+ labelName: displayName || account?.email?.address || '?',
407
+ primaryOrganizationId
408
+ };
409
+ }
410
+
411
+ /**
412
+ * Check if logged in
413
+ */
414
+
415
+ export function useIsLoggedIn() {
416
+ const { appState: { account } } = useContext(AppContext);
417
+ return !!account?.id;
418
+ }
package/states/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './apiData';
2
+ export * from './appContext';
2
3
  export * from './connected';
3
4
  export * from './modal';
4
5
  export * from './popOver';
package/states/modal.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import i18n from '@jsb188/app/i18n';
2
- import type { ServerErrorObj } from '@jsb188/app/types/app';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d';
3
3
  import { atom, useAtom, useSetAtom } from 'jotai';
4
4
  import { useCallback } from 'react';
5
5
 
@@ -143,7 +143,6 @@ class ModalPopUp extends ModalScreen {
143
143
  readonly name: string = 'modal_popup_state';
144
144
 
145
145
  open(data: ModalRequestParams | null, error?: ServerErrorObj): ModalProps | null {
146
-
147
146
  if (data) {
148
147
  const { preset, name, props } = data;
149
148
  const values = this.defaultValues?.[name ?? ''];
package/states/popOver.ts CHANGED
@@ -1,94 +1,22 @@
1
+ import {
2
+ ClosePopOverFn,
3
+ CloseTooltipFn,
4
+ OpenPopOverFn,
5
+ OpenTooltipFn,
6
+ PopOverGlobalStateObj,
7
+ PopOverGlobalStateParams,
8
+ PopOverHookProps,
9
+ PopOverProps,
10
+ SetPopOverStateFn,
11
+ TooltipHookProps,
12
+ TooltipProps,
13
+ UpdatePopOverFn,
14
+ UpdatePopOverParams,
15
+ UpdateTooltipFn
16
+ } from '@jsb188/react/types/PopOver.d';
1
17
  import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
2
18
  import { useCallback } from 'react';
3
19
 
4
- /**
5
- * Type; Pop overs
6
- */
7
-
8
- export enum PopOverNames {
9
- popover = 'popover',
10
- options = 'options',
11
- chat_options = 'chat_options',
12
- mini_profile = 'mini_profile',
13
- notification = 'notification',
14
- persona_picker = 'persona_picker',
15
- image_popover = 'image_popover'
16
- }
17
-
18
- export type POPosition = 'top' | 'left' | 'right' | 'bottom';
19
-
20
- export interface ClientRectValues {
21
- width: number;
22
- height: number;
23
- left: number;
24
- right: number;
25
- top: number;
26
- bottom: number;
27
- x: number;
28
- y: number;
29
- }
30
-
31
- interface FixedElementProps {
32
- id: string; // This ensures that the popover doesn't reset from within the same mouse pointer element
33
- className: string;
34
- position: POPosition;
35
- variables: Record<string, any>;
36
- popOverWidth: number;
37
- popOverHeight: number;
38
- rect?: ClientRectValues;
39
- offsetX: number;
40
- offsetY: number;
41
- leftEdgeThreshold: number;
42
- rightEdgeThreshold: number;
43
- leftEdgePosition: number;
44
- rightEdgePosition: number;
45
- hover: boolean;
46
- }
47
-
48
- interface UpdateStateParams {
49
- name: PopOverNames;
50
- variables: Record<string, any>;
51
- }
52
-
53
- export interface PopOverProps extends Partial<FixedElementProps> {
54
- name: PopOverNames; // Used to be "__type"
55
- doNotTrackHover?: boolean;
56
- children?: any; // ????????
57
- }
58
-
59
- export interface TooltipProps extends Partial<FixedElementProps> {
60
- title?: string;
61
- message?: string;
62
- }
63
-
64
- export type OpenPopOverFn = (data: PopOverProps) => void;
65
- export type ClosePopOverFn = (dismissIfName?: PopOverNames) => void;
66
- export type UpdatePopOverFn = (data: UpdateStateParams) => void;
67
-
68
- export interface PopOverHandlerProps {
69
- openPopOver: OpenPopOverFn;
70
- closePopOver: ClosePopOverFn;
71
- updatePopOver: UpdatePopOverFn;
72
- }
73
-
74
- export interface PopOverHookProps extends PopOverHandlerProps {
75
- popOver: PopOverProps | null;
76
- }
77
-
78
- export type OpenTooltipFn = (data: TooltipProps) => void;
79
- export type CloseTooltipFn = (removeId: string) => void;
80
- export type UpdateTooltipFn = (data: TooltipProps) => void;
81
-
82
- export interface TooltipHandlerProps {
83
- openTooltip: OpenTooltipFn;
84
- closeTooltip: CloseTooltipFn;
85
- updateTooltip: UpdateTooltipFn;
86
- }
87
-
88
- export interface TooltipHookProps extends TooltipHandlerProps {
89
- tooltip: TooltipProps | null;
90
- }
91
-
92
20
  /**
93
21
  * Pop over class
94
22
  */
@@ -104,7 +32,7 @@ class PopOver {
104
32
  return data;
105
33
  }
106
34
 
107
- update(data: UpdateStateParams, prev: PopOverProps | null): PopOverProps | null {
35
+ update(data: UpdatePopOverParams, prev: PopOverProps | null): PopOverProps | null {
108
36
  const { name, ...variables } = data;
109
37
  const nextName = name || prev?.name
110
38
  if (!nextName) {
@@ -117,8 +45,39 @@ class PopOver {
117
45
  };
118
46
  }
119
47
 
120
- close(): PopOverProps | null {
121
- return null;
48
+ close(prev: PopOverProps | null): PopOverProps | null {
49
+ if (!prev || !prev.animationClassName) {
50
+ return null;
51
+ }
52
+
53
+ let nextAnimClassName = prev.animationClassName;
54
+ if (/\bon_mount\b/.test(nextAnimClassName)) {
55
+ nextAnimClassName = nextAnimClassName.replace(/\bon_mount\b/, '').trim();
56
+ } else if (!/\breverse\b/.test(nextAnimClassName)) {
57
+ nextAnimClassName += ' reverse';
58
+ } else {
59
+ return null;
60
+ }
61
+
62
+ return {
63
+ ...prev,
64
+ closing: true,
65
+ animationClassName: nextAnimClassName,
66
+ };
67
+ }
68
+
69
+ setGlobalState(globalState: PopOverGlobalStateParams | null, prev: PopOverProps | null): PopOverProps | null {
70
+ if (!prev) {
71
+ return null;
72
+ }
73
+
74
+ return {
75
+ ...prev,
76
+ globalState: !globalState ? null : {
77
+ id: prev.id,
78
+ ...globalState
79
+ },
80
+ };
122
81
  }
123
82
  }
124
83
 
@@ -189,24 +148,36 @@ function composeClosePopOverFn(
189
148
  setPopOverIsHover: (update: boolean | ((prev: boolean) => boolean)) => void,
190
149
  popOver: PopOverProps | null
191
150
  ): ClosePopOverFn {
192
- return (dismissIfName?: PopOverNames) => {
151
+ return (dismissIfName?: string) => {
193
152
  if (!popOver || (typeof dismissIfName === 'string' && popOver.name !== dismissIfName)) {
194
153
  return;
195
154
  }
196
155
  setPopOverIsHover(false);
197
- setPopOver(popOverClass.close());
156
+ setPopOver(popOverClass.close(popOver));
198
157
  };
199
158
  }
200
159
 
201
160
  function composeUpdatePopOverFn( setPopOver: (value: PopOverProps | null) => void): UpdatePopOverFn {
202
- return (data: UpdateStateParams) => {
203
- // @ts-expect-error - I couldn't get rid of this type error
161
+ return (data: UpdatePopOverParams) => {
204
162
  setPopOver((prev: PopOverProps | null) => {
205
163
  const nextPopOverState = popOverClass.update(data, prev);
206
164
  if (nextPopOverState) {
207
165
  return nextPopOverState;
208
166
  }
209
- console.warn('Invalid {popOver} data for update():', data);
167
+ console.warn('{popOver} data should never be null when using update():', data);
168
+ return prev;
169
+ });
170
+ };
171
+ }
172
+
173
+ function composeSetPopOverState( setPopOver: (value: PopOverProps | null) => void): SetPopOverStateFn {
174
+ return (data: PopOverGlobalStateParams | null) => {
175
+ setPopOver((prev: PopOverProps | null) => {
176
+ const nextPopOverState = popOverClass.setGlobalState(data, prev);
177
+ if (nextPopOverState) {
178
+ return nextPopOverState;
179
+ }
180
+ console.warn('{popOver} data should never be null when using setGlobalState():', data);
210
181
  return prev;
211
182
  });
212
183
  };
@@ -222,15 +193,32 @@ export function usePopOver(): PopOverHookProps {
222
193
 
223
194
  const openPopOver = useCallback( composeOpenPopOverFn(setPopOver), []);
224
195
  const closePopOver = useCallback( composeClosePopOverFn(setPopOver, setPopOverIsHover, popOver), [popOver]);
225
-
226
- // Test to make sure updatePopOver updates previous state even with [] deps
227
196
  const updatePopOver = useCallback( composeUpdatePopOverFn(setPopOver), []);
197
+ const setPopOverState = useCallback( composeSetPopOverState(setPopOver), []);
228
198
 
229
199
  return {
230
200
  popOver,
231
201
  openPopOver,
232
202
  closePopOver,
233
203
  updatePopOver,
204
+ setPopOverState
205
+ };
206
+ }
207
+
208
+ /**
209
+ * Use pop over global state
210
+ */
211
+
212
+ export function usePopOverState() {
213
+ const [popOver, setPopOver] = useAtom<PopOverProps | null>(popOverClass.state);
214
+ const setPopOverIsHover = useSetAtom(popOverIsHoverState);
215
+ const updatePopOver = useCallback( composeUpdatePopOverFn(setPopOver), []);
216
+ const closePopOver = useCallback( composeClosePopOverFn(setPopOver, setPopOverIsHover, popOver), [popOver]);
217
+
218
+ return {
219
+ popOverState: popOver?.globalState,
220
+ closePopOver,
221
+ updatePopOver
234
222
  };
235
223
  }
236
224
 
@@ -260,7 +248,7 @@ function composeCloseTooltipFn( setTooltip: (value: TooltipProps | null) => void
260
248
  if (prev?.id !== removeId) {
261
249
  return prev;
262
250
  }
263
- return popOverClass.close();
251
+ return tooltipClass.close();
264
252
  });
265
253
  };
266
254
  }