@jsb188/react 1.1.10 → 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/utils/lazy.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { Component, type ComponentType, createElement, type ErrorInfo, type ReactNode, use } from 'react';
2
+
3
+ export interface ComponentModule<P> {
4
+ default: ComponentType<P>;
5
+ }
6
+
7
+ export interface PreloadableComponent<P> {
8
+ // Render inside <Suspense>; suspends only while the code is still downloading
9
+ Component: ComponentType<P>;
10
+ // Start (or reuse) the download; resolves null on failure and never rejects
11
+ preload: () => Promise<ComponentModule<P> | null>;
12
+ }
13
+
14
+ // A promise carrying the settled-state fields React's use() reads to skip suspending
15
+ type TrackedPromise<T> = Promise<T> & {
16
+ status?: 'pending' | 'fulfilled' | 'rejected';
17
+ value?: T;
18
+ reason?: unknown;
19
+ };
20
+
21
+ interface LazyWithPreloadOptions<P> {
22
+ // Rendered instead of the component when its code fails to download (defaults to rendering nothing)
23
+ fallback?: ComponentType<P>;
24
+ // Called when a render needed the code and it failed to download
25
+ onError?: (error: unknown) => void;
26
+ }
27
+
28
+ /*
29
+ * Error thrown when a lazy component's code failed to download.
30
+ */
31
+ export class LazyLoadError extends Error {
32
+ constructor(cause: unknown) {
33
+ super('Failed to load lazy component code', { cause });
34
+ this.name = 'LazyLoadError';
35
+ }
36
+ }
37
+
38
+ /*
39
+ * Catch only code download failures (LazyLoadError) and render a fallback;
40
+ * every other error is rethrown to the next error boundary as before.
41
+ */
42
+ class LazyLoadErrorBoundary extends Component<
43
+ {
44
+ children: ReactNode;
45
+ renderFallback: () => ReactNode;
46
+ onLoadError: (error: LazyLoadError) => void;
47
+ },
48
+ { error: unknown }
49
+ > {
50
+ state = { error: null as unknown };
51
+
52
+ static getDerivedStateFromError(error: unknown) {
53
+ return { error };
54
+ }
55
+
56
+ componentDidCatch(error: unknown, _errorInfo: ErrorInfo) {
57
+ if (error instanceof LazyLoadError) {
58
+ this.props.onLoadError(error);
59
+ }
60
+ }
61
+
62
+ render() {
63
+ const { error } = this.state;
64
+ if (!error) {
65
+ return this.props.children;
66
+ }
67
+
68
+ if (error instanceof LazyLoadError) {
69
+ return this.props.renderFallback();
70
+ }
71
+
72
+ // Not a download failure; let the app's error handling deal with it
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ /*
78
+ * Create a component whose code downloads on first render, or earlier through
79
+ * preload() (idle or hover prefetch). Unlike React.lazy, a component whose code
80
+ * was already preloaded renders synchronously without suspending, so prefetched
81
+ * content never flashes a Suspense fallback. The download is shared by
82
+ * preload() and every render. A failed download renders `fallback` instead of
83
+ * throwing to the app's error boundary. A later render or preload() starts a new
84
+ * download, though some browsers (Chromium) keep failing a dynamic import that
85
+ * failed once until the page reloads, so `fallback` should offer a reload.
86
+ */
87
+ export function lazyWithPreload<P>(
88
+ load: () => Promise<ComponentModule<P>>,
89
+ options: LazyWithPreloadOptions<P> = {},
90
+ ): PreloadableComponent<P> {
91
+ let modulePromise: TrackedPromise<ComponentModule<P>> | null = null;
92
+
93
+ const loadOnce = () => {
94
+ if (!modulePromise) {
95
+ const promise: TrackedPromise<ComponentModule<P>> = load().catch((error) => {
96
+ throw new LazyLoadError(error);
97
+ });
98
+
99
+ // Record the settled state in the fields React's use() reads, so a loaded module
100
+ // is returned synchronously (no suspending) on every later render
101
+ promise.status = 'pending';
102
+ promise.then(
103
+ (module) => {
104
+ promise.status = 'fulfilled';
105
+ promise.value = module;
106
+ },
107
+ (error) => {
108
+ promise.status = 'rejected';
109
+ promise.reason = error;
110
+ },
111
+ );
112
+ modulePromise = promise;
113
+ }
114
+ return modulePromise;
115
+ };
116
+
117
+ // Forget a failed download so the next attempt fetches again (the same promise is kept
118
+ // while a render is still retrying, so React's use() sees one stable promise)
119
+ const forgetFailedLoad = () => {
120
+ if (modulePromise?.status === 'rejected') {
121
+ modulePromise = null;
122
+ }
123
+ };
124
+
125
+ function LoadedComponent(props: P) {
126
+ const Loaded = use(loadOnce() as Promise<ComponentModule<P>>).default;
127
+ return createElement(Loaded as ComponentType<any>, props as any);
128
+ }
129
+
130
+ function PreloadableComponent(props: P) {
131
+ return createElement(LazyLoadErrorBoundary, {
132
+ onLoadError: (error: LazyLoadError) => {
133
+ forgetFailedLoad();
134
+ options.onError?.(error.cause);
135
+ },
136
+ renderFallback: () => (options.fallback ? createElement(options.fallback as ComponentType<any>, props as any) : null),
137
+ children: createElement(LoadedComponent as ComponentType<any>, props as any),
138
+ });
139
+ }
140
+
141
+ return {
142
+ Component: PreloadableComponent,
143
+ preload: () =>
144
+ loadOnce().catch(() => {
145
+ forgetFailedLoad();
146
+ return null;
147
+ }),
148
+ };
149
+ }
150
+
151
+ /*
152
+ * Wrap an already imported component in the same shape as lazyWithPreload(),
153
+ * for registries that mix lazy and static entries (e.g. prompts that must open instantly).
154
+ */
155
+ export function preloadedComponent<P>(Loaded: ComponentType<P>): PreloadableComponent<P> {
156
+ const module = { default: Loaded };
157
+ return {
158
+ Component: Loaded,
159
+ preload: () => Promise.resolve(module),
160
+ };
161
+ }
162
+
163
+ /*
164
+ * Reload the page after a code chunk failed to load (e.g. a tab still running
165
+ * an old deploy), at most once per `windowMs` so a persistent failure can't
166
+ * cause a reload loop. Returns true when a reload was started.
167
+ */
168
+ export function reloadOnceAfterChunkError(storageKey: string, windowMs = 60000) {
169
+ try {
170
+ const lastReloadAt = Number(sessionStorage.getItem(storageKey) || 0);
171
+ if (Date.now() - lastReloadAt < windowMs) {
172
+ return false;
173
+ }
174
+
175
+ sessionStorage.setItem(storageKey, String(Date.now()));
176
+ } catch {
177
+ // Without sessionStorage there's no loop guard; don't reload
178
+ return false;
179
+ }
180
+
181
+ globalThis.location.reload();
182
+ return true;
183
+ }
package/states/toasts.ts DELETED
@@ -1,30 +0,0 @@
1
- import type { WSDataUpdateObj } from '@jsb188/app/types/app.d.ts';
2
- import { atom, useAtomValue, useSetAtom } from 'jotai';
3
-
4
- /**
5
- * Types; Fragment/observer hooks
6
- */
7
-
8
- export type ToastObj = Omit<WSDataUpdateObj, 'resetQueryKeys' | 'resetQueryRule' | 'fragment'>;
9
-
10
- /**
11
- * Toast; state
12
- */
13
-
14
- const toastState = atom<ToastObj | null>(null);
15
-
16
- /**
17
- * Export; get toast value
18
- */
19
-
20
- export function useToastValue() {
21
- return useAtomValue(toastState);
22
- }
23
-
24
- /**
25
- * Export; set toast state
26
- */
27
-
28
- export function useSetToast() {
29
- return useSetAtom(toastState);
30
- }
package/utils/schema.ts DELETED
@@ -1,158 +0,0 @@
1
- import { useState } from 'react';
2
- import i18n from '@jsb188/app/i18n/index.ts';
3
- import type { FormItemSchemaObj, FormSchemaObj } from '@jsb188/app/types/form.d.ts';
4
- import { getObject, setObject } from '@jsb188/app/utils/object.ts';
5
-
6
- /**
7
- * Types
8
- */
9
-
10
- interface ComputedSchema {
11
- formValues: any;
12
- setFormValues: (formValues: any) => void;
13
- listData: (FormItemSchemaObj & { name: string })[];
14
- validate?: () => any;
15
- isButtonDisabled?: (formValues: any) => boolean;
16
- }
17
-
18
- /**
19
- * Make form values from current form values, current data, and schema
20
- */
21
-
22
- export function makeFormValues(
23
- schema: any,
24
- dataForSchema?: any,
25
- currentData?: any,
26
- ) {
27
- const newFormValues: Record<string, any> = {};
28
- const { listData } = schema;
29
-
30
- for (const obj of listData) {
31
- const item = obj?.item || {};
32
- const { name, setter, items } = item;
33
-
34
- if (!name && !Array.isArray(items)) {
35
- continue;
36
- }
37
-
38
- if (currentData || dataForSchema) {
39
- if (Array.isArray(items)) {
40
- items.forEach(({ item: subItem }: any) => {
41
- if (typeof subItem.setter === 'function') {
42
- setObject(newFormValues, subItem.name, subItem.setter(
43
- currentData,
44
- dataForSchema,
45
- ));
46
- } else if (currentData) {
47
- setObject(newFormValues, subItem.name, getObject(currentData, subItem.name));
48
- }
49
- });
50
- } else if (typeof setter === 'function') {
51
- setObject(newFormValues, name, setter(currentData, dataForSchema));
52
- } else if (currentData) {
53
- setObject(newFormValues, name, getObject(currentData, name));
54
- }
55
- }
56
- }
57
-
58
- return newFormValues;
59
- }
60
-
61
- /**
62
- * Resolve schema using data
63
- */
64
-
65
- export function useSchema(
66
- schema: FormSchemaObj,
67
- dataForSchema: any,
68
- currentData?: any,
69
- ): ComputedSchema {
70
- const { listData, rules, isButtonDisabled } = schema;
71
- const [formValues, setFormValues] = useState(makeFormValues(schema, dataForSchema, currentData));
72
-
73
- // Make listData from schema
74
-
75
- const computedListData: any[] = listData.map((schemaItem: FormItemSchemaObj) => {
76
- const { __type, hidden, locked, item } = schemaItem;
77
- if (
78
- hidden === true ||
79
- (typeof hidden === 'function' && hidden(dataForSchema))
80
- ) {
81
- return null;
82
- }
83
-
84
- let lockedValue;
85
- if (typeof locked === 'function') {
86
- lockedValue = locked(dataForSchema);
87
- } else if (typeof locked === 'boolean') {
88
- lockedValue = locked;
89
- }
90
-
91
- const computedItem: Record<string, any> = { ...item };
92
- if (computedItem) {
93
- for (const key in computedItem) {
94
- if (
95
- typeof computedItem[key] === 'function' &&
96
- !key.startsWith('onClick') &&
97
- !['getter', 'setter'].includes(key)
98
- ) {
99
- computedItem[key] = computedItem[key](dataForSchema);
100
- }
101
- }
102
- }
103
-
104
- return {
105
- __type,
106
- locked: lockedValue,
107
- item: computedItem,
108
- };
109
- }).filter(Boolean);
110
-
111
- // Create validation function
112
-
113
- const validate = (): any => {
114
- if (rules) {
115
- const __errorFields: string[] = [];
116
-
117
- let firstError: any = null;
118
- for (const ruleObj of rules) {
119
- const { for: key, rule, error } = ruleObj;
120
- const value = formValues[key];
121
- const isValid = rule(value, formValues);
122
-
123
- if (!isValid) {
124
- if (!__errorFields.includes(key)) {
125
- __errorFields.push(key);
126
- }
127
-
128
- if (!firstError) {
129
- if (error) {
130
- firstError = typeof error === 'function' ? error(value) : error;
131
- } else {
132
- firstError = {
133
- message: i18n.t('error.unknown_error_msg'),
134
- };
135
- }
136
- }
137
- }
138
- }
139
-
140
- setFormValues({
141
- ...formValues,
142
- __errorFields,
143
- });
144
-
145
- return firstError;
146
- }
147
-
148
- return null;
149
- };
150
-
151
- return {
152
- formValues,
153
- setFormValues,
154
- listData: computedListData,
155
- validate,
156
- isButtonDisabled,
157
- };
158
- }