@jsb188/react 1.1.1 → 1.1.2

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.
@@ -1,2 +1,424 @@
1
+ import { clearAppCache, fetchLightModeSetting, isSystemDarkMode, saveAuthTokenToPlatform } from '@jsb188/app/platform.ts';
2
+ import type { AccountData, AccountSettings, AuthenticationData, LightModeEnum } from '@jsb188/app/types/auth.d.ts';
3
+ import { setAuthToken } from '@jsb188/app/utils/api.ts';
4
+ import { getDisplayName } from '@jsb188/app/utils/string.ts';
5
+ import { createContext, useContext } from 'react';
1
6
 
2
- export const appReducer = {};
7
+ /**
8
+ * Type; Reducer action for App Context
9
+ */
10
+
11
+ type AppContextAction = {
12
+ __type: // App initialization
13
+ | 'APP_INIT'
14
+ // Auth setup
15
+ | 'APP_LOGIN'
16
+ | 'APP_GUEST'
17
+ | 'APP_REFRESH_AUTH'
18
+ | 'APP_EDIT_AUTH'
19
+ | 'APP_EDIT_ACCOUNT'
20
+ | 'APP_SWITCH_PRIMARY_ORGANIZATION'
21
+ // Account theme
22
+ | 'APP_THEME'
23
+ | 'APP_SYSTEM_LIGHT_MODE'
24
+ | 'APP_LIGHT_MODE';
25
+ data?: any;
26
+ };
27
+
28
+ export type AppContextDispatch = (action: AppContextAction) => void;
29
+
30
+ export type CurrentAccountObj = ReturnType<typeof useCurrentAccount>;
31
+
32
+ /**
33
+ * Types
34
+ */
35
+
36
+ export type AppAppearanceType = {
37
+ realLightMode: LightModeEnum;
38
+ lightMode: LightModeEnum;
39
+ previewLightMode: LightModeEnum;
40
+ previewTheme: Record<string, any> | 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
+ cacheAuthorizationEpoch: string | null;
53
+
54
+ // Account settings & state
55
+ settings: AccountSettings;
56
+ activated: boolean;
57
+ hasPassword: boolean;
58
+ webVersion: string | null;
59
+ alertUpdatesOnMount: boolean;
60
+
61
+ // Preview theme overrides active theme
62
+ systemLightMode: 'LIGHT' | 'DARK';
63
+ previewLightMode: LightModeEnum | null;
64
+ previewTheme: Record<string, any> | null;
65
+ };
66
+
67
+ /**
68
+ * Context default values
69
+ */
70
+
71
+ export const DEFAULT_APP_CONTEXT = {
72
+ init: 0,
73
+ authorization: '',
74
+ networkError: false,
75
+
76
+ account: null,
77
+ primaryOrganizationId: null,
78
+ cacheAuthorizationEpoch: null,
79
+
80
+ settings: {
81
+ theme: null,
82
+ lightMode: 'LIGHT',
83
+ timeZone: null,
84
+ },
85
+ activated: false,
86
+ hasPassword: false,
87
+ webVersion: null,
88
+ alertUpdatesOnMount: false,
89
+
90
+ systemLightMode: 'LIGHT',
91
+ previewLightMode: null,
92
+ previewTheme: null,
93
+ } as AppContextData;
94
+
95
+ /**
96
+ * Helper for light mode
97
+ */
98
+
99
+ function ensureLightModeSetting(lightMode?: LightModeEnum): LightModeEnum {
100
+ return lightMode && ['LIGHT', 'DARK', 'SYSTEM'].includes(lightMode || '') ? lightMode : 'LIGHT';
101
+ }
102
+
103
+ /**
104
+ * App log in with Promise
105
+ */
106
+
107
+ export function onAccountLogin(auth: any, dispatchApp: AppContextDispatch, otherCB?: (auth: any) => void) {
108
+ if (auth && auth?.token && auth.activated && auth.account) {
109
+ console.log('.. 🥝 logged into account ..');
110
+
111
+ saveAuthTokenToPlatform(auth.token, () => {
112
+ clearAppCache();
113
+ dispatchApp({
114
+ __type: 'APP_LOGIN',
115
+ data: auth,
116
+ });
117
+
118
+ if (otherCB) {
119
+ otherCB(auth);
120
+ }
121
+ });
122
+ } else {
123
+ console.log(auth);
124
+ console.warn('Developer error in onAccountLogin()');
125
+ }
126
+ }
127
+
128
+ /**
129
+ * App guest init
130
+ */
131
+
132
+ export function onGuestInit(error: any, dispatchApp: AppContextDispatch) {
133
+ fetchLightModeSetting(null, (lightMode) => {
134
+ dispatchApp({
135
+ __type: 'APP_GUEST',
136
+ data: {
137
+ error,
138
+ lightMode,
139
+ },
140
+ });
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Get active/current or preview theme
146
+ */
147
+
148
+ export function getTheme(appState: AppContextData, priority: 'PREVIEW' | 'ACCOUNT' | 'ACTIVE') {
149
+ let lightMode = appState.previewLightMode || appState.settings.lightMode;
150
+ if (lightMode === 'SYSTEM') {
151
+ lightMode = appState.systemLightMode;
152
+ }
153
+
154
+ const theme = (priority === 'PREVIEW' && appState.previewTheme) || appState.settings.theme || '';
155
+
156
+ return {
157
+ lightMode: lightMode || 'LIGHT',
158
+ theme,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Get theme; but prioritize preview theme
164
+ */
165
+
166
+ export function getPreviewAppearance(appState: AppContextData) {
167
+ let realLightMode = appState.previewLightMode || appState.settings.lightMode;
168
+ if (realLightMode === 'SYSTEM') {
169
+ realLightMode = appState.systemLightMode;
170
+ }
171
+
172
+ return {
173
+ realLightMode,
174
+ lightMode: appState.settings.lightMode,
175
+ previewLightMode: appState.previewLightMode,
176
+ previewTheme: appState.previewTheme,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Merge sign in mutation auth values to context
182
+ */
183
+
184
+ export function mergeAuthToDefaultValues(auth?: AuthenticationData | null, authToken?: string | null) {
185
+ if (auth?.token && auth?.account?.id) {
186
+ let systemLightMode = 'LIGHT';
187
+ if (isSystemDarkMode()) {
188
+ systemLightMode = 'DARK';
189
+ }
190
+
191
+ setAuthToken(auth.token);
192
+
193
+ const authSettings = {
194
+ ...DEFAULT_APP_CONTEXT.settings,
195
+ ...auth.account.settings,
196
+ };
197
+
198
+ authSettings.lightMode = ensureLightModeSetting(authSettings.lightMode);
199
+
200
+ return {
201
+ ...DEFAULT_APP_CONTEXT,
202
+ init: 1, // Always 1 because we're always using SSR for authentication
203
+ authorization: auth.token,
204
+ account: auth.account,
205
+ primaryOrganizationId: auth.primaryOrganizationId || null,
206
+ cacheAuthorizationEpoch: auth.cacheAuthorizationEpoch || null,
207
+ settings: authSettings,
208
+
209
+ alertUpdatesOnMount: auth.alertUpdatesOnMount,
210
+ hasPassword: auth.hasPassword,
211
+ webVersion: auth.webVersion,
212
+
213
+ // Theme
214
+ systemLightMode,
215
+ previewLightMode: null,
216
+ previewTheme: null,
217
+ };
218
+ } else if (authToken) {
219
+ setAuthToken(authToken);
220
+ return {
221
+ ...DEFAULT_APP_CONTEXT,
222
+ authorization: authToken || '',
223
+ };
224
+ }
225
+
226
+ setAuthToken(null);
227
+ return DEFAULT_APP_CONTEXT;
228
+ }
229
+
230
+ /**
231
+ * App reducer
232
+ */
233
+
234
+ export const appReducer = (state: AppContextData, action: AppContextAction) => {
235
+ const { __type, data } = action;
236
+
237
+ switch (__type) {
238
+ case 'APP_INIT': {
239
+ return {
240
+ ...state,
241
+ init: state.init === 1 ? 2 : 1,
242
+ };
243
+ }
244
+ case 'APP_LOGIN': {
245
+ const nextState = mergeAuthToDefaultValues(data);
246
+ // Inline sign-in keeps the mounted app's completed initialization.
247
+ return { ...nextState, init: state.init === 2 ? 2 : nextState.init };
248
+ }
249
+ case 'APP_REFRESH_AUTH': {
250
+ const authorization = data?.authorization || '';
251
+ if (!authorization) {
252
+ return state;
253
+ }
254
+
255
+ setAuthToken(authorization);
256
+ return {
257
+ ...state,
258
+ authorization,
259
+ };
260
+ }
261
+ case 'APP_GUEST': {
262
+ const networkError = data.error?.errorCode === 'network_error';
263
+ if (networkError) {
264
+ console.log('.. ❌ network error ..');
265
+ } else {
266
+ console.log('.. 🥝 guest entered ..');
267
+ }
268
+
269
+ clearAppCache();
270
+ setAuthToken(null);
271
+
272
+ return {
273
+ ...DEFAULT_APP_CONTEXT,
274
+ init: 2,
275
+ authorization: '',
276
+ networkError,
277
+
278
+ // Theme
279
+ previewLightMode: null,
280
+ previewTheme: null,
281
+ };
282
+ }
283
+ case 'APP_EDIT_AUTH': {
284
+ if (data.id === state.account?.id) {
285
+ return {
286
+ ...state,
287
+ hasPassword: typeof data.hasPassword === 'boolean' ? data.hasPassword : state.hasPassword,
288
+ account: !data.email
289
+ ? state.account
290
+ : {
291
+ ...state.account,
292
+ email: data.email,
293
+ },
294
+ };
295
+ }
296
+ return state;
297
+ }
298
+ case 'APP_EDIT_ACCOUNT': {
299
+ if (data.id === state.account?.id) {
300
+ return {
301
+ ...state,
302
+
303
+ // Account
304
+ account: {
305
+ ...state.account,
306
+ ...data,
307
+ plus: !data.plus
308
+ ? state.account?.plus
309
+ : {
310
+ ...state.account?.plus,
311
+ ...data.plus,
312
+ },
313
+ },
314
+ settings: !data.settings
315
+ ? state.settings
316
+ : {
317
+ ...DEFAULT_APP_CONTEXT.settings,
318
+ ...data.settings,
319
+ },
320
+ };
321
+ }
322
+ return state;
323
+ }
324
+ case 'APP_SWITCH_PRIMARY_ORGANIZATION': {
325
+ return {
326
+ ...state,
327
+ primaryOrganizationId: data.primaryOrganizationId,
328
+ };
329
+ }
330
+ case 'APP_THEME': {
331
+ if (!data?.preview) {
332
+ // Active theme
333
+ return {
334
+ ...state,
335
+ previewTheme: null,
336
+ };
337
+ }
338
+
339
+ // Is preview theme
340
+ return {
341
+ ...state,
342
+ previewTheme: data.theme,
343
+ };
344
+ }
345
+ case 'APP_LIGHT_MODE': {
346
+ if (!data.lightMode && !data.preview) {
347
+ console.warn('Developer error in setLightMode(): You cannot set active lightMode to null.');
348
+ return state;
349
+ } else if (data.preview) {
350
+ return {
351
+ ...state,
352
+ previewLightMode: data.lightMode,
353
+ };
354
+ }
355
+
356
+ return {
357
+ ...state,
358
+ previewLightMode: null,
359
+ };
360
+ }
361
+ case 'APP_SYSTEM_LIGHT_MODE': {
362
+ return {
363
+ ...state,
364
+ systemLightMode: data.lightMode,
365
+ };
366
+ }
367
+ default:
368
+ console.dev('Unknown app reducer action type:', __type);
369
+ return state;
370
+ }
371
+ };
372
+
373
+ export const AppContext = createContext({
374
+ appState: DEFAULT_APP_CONTEXT as AppContextData,
375
+ dispatchApp: (() => {
376
+ console.warn('AppContext has been re-initialized due to hot refresh.');
377
+ }) as AppContextDispatch,
378
+ });
379
+
380
+ /**
381
+ * Use current account
382
+ */
383
+
384
+ export function useCurrentAccount() {
385
+ const {
386
+ appState: { init, activated, hasPassword, webVersion, alertUpdatesOnMount, account, settings, primaryOrganizationId },
387
+ dispatchApp,
388
+ } = useContext(AppContext);
389
+ const hasName = !!account?.profile?.firstName || !!account?.profile?.lastName;
390
+ const { fullName, displayName } = getDisplayName(account?.profile?.firstName, account?.profile?.lastName);
391
+
392
+ return {
393
+ // Dispatch
394
+ dispatchApp,
395
+
396
+ // App state
397
+ init,
398
+ account,
399
+ settings,
400
+ activated,
401
+ hasPassword,
402
+ webVersion,
403
+ alertUpdatesOnMount,
404
+
405
+ // Computed
406
+ isLoggedIn: !!account?.id,
407
+ hasName,
408
+ fullName,
409
+ displayName,
410
+ labelName: displayName || account?.email?.address || '?',
411
+ primaryOrganizationId,
412
+ };
413
+ }
414
+
415
+ /**
416
+ * Check if logged in
417
+ */
418
+
419
+ export function useIsLoggedIn() {
420
+ const {
421
+ appState: { account },
422
+ } = useContext(AppContext);
423
+ return !!account?.id;
424
+ }
@@ -1,12 +1,88 @@
1
- import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'
1
+ import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
2
+ import type { SetStateAction } from 'react';
3
+
4
+ export type RealtimeConnectionStatus =
5
+ | 'CONNECTED'
6
+ | 'DISCONNECTED'
7
+ | 'REAUTHENTICATING'
8
+ | 'REVOKED';
9
+
10
+ /*
11
+ * Preserve terminal revocation when a recoverable transport path disconnects.
12
+ */
13
+ export function getRealtimeConnectionStatusAfterDisconnect(
14
+ status: RealtimeConnectionStatus,
15
+ ): RealtimeConnectionStatus {
16
+ return status === 'REVOKED' ? status : 'DISCONNECTED';
17
+ }
18
+
19
+ /*
20
+ * Enter optimistic reauthentication only from an authenticated-ready lifecycle.
21
+ */
22
+ export function getRealtimeConnectionStatusAfterAuthReset(
23
+ status: RealtimeConnectionStatus,
24
+ ): RealtimeConnectionStatus {
25
+ return status === 'CONNECTED' || status === 'REAUTHENTICATING'
26
+ ? 'REAUTHENTICATING'
27
+ : status;
28
+ }
29
+
30
+ /*
31
+ * Return whether the app should surface its reconnecting recovery message.
32
+ */
33
+ export function shouldShowRealtimeReconnectingMessage(
34
+ status: RealtimeConnectionStatus,
35
+ ) {
36
+ return status === 'DISCONNECTED';
37
+ }
38
+
39
+ /**
40
+ * realtimeConnectionStatusState; Track transport and authenticated readiness.
41
+ */
42
+
43
+ const realtimeConnectionStatusState =
44
+ atom<RealtimeConnectionStatus>('DISCONNECTED');
2
45
 
3
46
  /**
4
- * connectedToState; Track network connection state;
5
- * Developer should use either WebSockets, or SSE to track this,
6
- * or just keep the value set to {true} on app mount.
47
+ * connectedToServerState; Preserve the strict authenticated-ready boolean API.
7
48
  */
8
49
 
9
- const connectedToServerState = atom(false);
50
+ const connectedToServerState = atom(
51
+ (get) => get(realtimeConnectionStatusState) === 'CONNECTED',
52
+ (get, set, nextValue: SetStateAction<boolean>) => {
53
+ const connected = get(realtimeConnectionStatusState) === 'CONNECTED';
54
+ const nextConnected =
55
+ typeof nextValue === 'function' ? nextValue(connected) : nextValue;
56
+ set(
57
+ realtimeConnectionStatusState,
58
+ nextConnected ? 'CONNECTED' : 'DISCONNECTED',
59
+ );
60
+ },
61
+ );
62
+
63
+ /**
64
+ * optimisticConnectedToServerState; Keep presentation connected during auth rotation.
65
+ */
66
+
67
+ const optimisticConnectedToServerState = atom((get) => {
68
+ const status = get(realtimeConnectionStatusState);
69
+ return status === 'CONNECTED' || status === 'REAUTHENTICATING';
70
+ });
71
+
72
+ /**
73
+ * realtimeReconnectingMessageState; Narrowly observe visible recovery status.
74
+ */
75
+
76
+ const realtimeReconnectingMessageState = atom((get) =>
77
+ shouldShowRealtimeReconnectingMessage(get(realtimeConnectionStatusState)),
78
+ );
79
+
80
+ /**
81
+ * realtimeConnectionGenerationState; Monotonic identity for replacement
82
+ * realtime connections, including reconnects whose false state is batched.
83
+ */
84
+
85
+ const realtimeConnectionGenerationState = atom(0);
10
86
 
11
87
  /**
12
88
  * screenIsFocused; whether or not app is open & focused
@@ -19,7 +95,7 @@ const screenIsFocusedState = atom(true);
19
95
  */
20
96
 
21
97
  export function useSetConnectedToServer() {
22
- return useSetAtom(connectedToServerState);
98
+ return useSetAtom(connectedToServerState);
23
99
  }
24
100
 
25
101
  /**
@@ -27,7 +103,7 @@ export function useSetConnectedToServer() {
27
103
  */
28
104
 
29
105
  export function useConnectedToServerValue() {
30
- return useAtomValue(connectedToServerState);
106
+ return useAtomValue(connectedToServerState);
31
107
  }
32
108
 
33
109
  /**
@@ -35,7 +111,55 @@ export function useConnectedToServerValue() {
35
111
  */
36
112
 
37
113
  export function useConnectedToServer() {
38
- return useAtom(connectedToServerState);
114
+ return useAtom(connectedToServerState);
115
+ }
116
+
117
+ /**
118
+ * Export; get the complete realtime connection lifecycle status.
119
+ */
120
+
121
+ export function useRealtimeConnectionStatusValue() {
122
+ return useAtomValue(realtimeConnectionStatusState);
123
+ }
124
+
125
+ /**
126
+ * Export; set the complete realtime connection lifecycle status.
127
+ */
128
+
129
+ export function useSetRealtimeConnectionStatus() {
130
+ return useSetAtom(realtimeConnectionStatusState);
131
+ }
132
+
133
+ /**
134
+ * Export; get whether realtime should appear connected to the user.
135
+ */
136
+
137
+ export function useOptimisticConnectedToServerValue() {
138
+ return useAtomValue(optimisticConnectedToServerState);
139
+ }
140
+
141
+ /**
142
+ * Export; get whether the app should surface its reconnecting message.
143
+ */
144
+
145
+ export function useShowRealtimeReconnectingMessageValue() {
146
+ return useAtomValue(realtimeReconnectingMessageState);
147
+ }
148
+
149
+ /**
150
+ * Export; advance realtimeConnectionGenerationState
151
+ */
152
+
153
+ export function useSetRealtimeConnectionGeneration() {
154
+ return useSetAtom(realtimeConnectionGenerationState);
155
+ }
156
+
157
+ /**
158
+ * Export; get realtimeConnectionGenerationState value
159
+ */
160
+
161
+ export function useRealtimeConnectionGenerationValue() {
162
+ return useAtomValue(realtimeConnectionGenerationState);
39
163
  }
40
164
 
41
165
  /**
@@ -43,7 +167,7 @@ export function useConnectedToServer() {
43
167
  */
44
168
 
45
169
  export function useSetScreenIsFocused() {
46
- return useSetAtom(screenIsFocusedState);
170
+ return useSetAtom(screenIsFocusedState);
47
171
  }
48
172
 
49
173
  /**
@@ -51,7 +175,7 @@ export function useSetScreenIsFocused() {
51
175
  */
52
176
 
53
177
  export function useScreenIsFocusedValue() {
54
- return useAtomValue(screenIsFocusedState);
178
+ return useAtomValue(screenIsFocusedState);
55
179
  }
56
180
 
57
181
  /**
@@ -59,5 +183,5 @@ export function useScreenIsFocusedValue() {
59
183
  */
60
184
 
61
185
  export function useScreenIsFocused() {
62
- return useAtom(screenIsFocusedState);
186
+ return useAtom(screenIsFocusedState);
63
187
  }
package/states/index.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export * from './apiData';
2
2
  export * from './appContext';
3
3
  export * from './connected';
4
+ export * from './keyDown';
5
+ export * from './keyboardLayer';
4
6
  export * from './modal';
5
7
  export * from './popOver';
8
+ export * from './reactiveEvents';
9
+ export * from './uploads';