@jsb188/react 1.0.4 → 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.
package/utils/hooks.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { areObjectsEqual } from '@jsb188/app/utils/object.ts';
2
+ import { releaseObjectUrl, retainObjectUrl } from '@jsb188/app/utils/url_client.ts';
1
3
  import { useEffect, useMemo, useRef, useState } from 'react';
2
- import { isAppHidden, setTimeoutPriority } from './priorityTimeout';
3
4
 
4
5
  /**
5
6
  * Check if database document needs an update, insert, or do nothing based on the user API arguments
@@ -7,57 +8,60 @@ import { isAppHidden, setTimeoutPriority } from './priorityTimeout';
7
8
  * NOTE: Do *NOT* export this function.
8
9
  */
9
10
 
10
- function getDatabaseAction(
11
- currentData: any,
12
- data: any,
13
- allowNull?: boolean,
14
- mergeCurrentData?: boolean,
15
- ): any {
16
- if (!currentData) {
17
- return {
18
- action: 'INSERT',
19
- documentData: data,
20
- };
21
- }
22
-
23
- const documentData: Record<string, any> = {};
24
-
25
- let hasChanges = false;
26
- for (const key in data) {
27
- if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== undefined) {
28
- // trim() on all string databse fields should be OK;
29
- // But if not, add an extra param.
30
- const value = typeof data[key] === 'string' ? data[key].trim() : data[key];
31
-
32
- const isNullValue = value !== null || allowNull;
33
- if (isNullValue) {
34
- documentData[key] = value;
35
- }
36
-
37
- if (
38
- // Doing loose != check instead of !== type check
39
- currentData[key] != value &&
40
- isNullValue
41
- ) {
42
- hasChanges = true;
43
- }
44
- }
45
- }
46
-
47
- if (mergeCurrentData) {
48
- for (const key in currentData) {
49
- if (Object.prototype.hasOwnProperty.call(currentData, key) && documentData[key] === undefined) {
50
- documentData[key] = currentData[key];
51
- }
52
- }
53
- }
54
-
55
- const action = hasChanges ? 'UPDATE' : 'NONE';
56
-
57
- return {
58
- action,
59
- documentData,
60
- };
11
+ function getDatabaseAction(currentData: any, data: any, allowNull?: boolean, mergeCurrentData?: boolean): any {
12
+ if (!currentData) {
13
+ return {
14
+ action: 'INSERT',
15
+ documentData: data,
16
+ };
17
+ }
18
+
19
+ const documentData: Record<string, any> = {};
20
+
21
+ let hasChanges = false;
22
+ for (const key in data) {
23
+ if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== undefined) {
24
+ // trim() on all string databse fields should be OK;
25
+ // But if not, add an extra param.
26
+ const value = typeof data[key] === 'string' ? data[key].trim() : data[key];
27
+
28
+ const isNotNull = value !== null || allowNull;
29
+ if (isNotNull) {
30
+ documentData[key] = value;
31
+ }
32
+
33
+ if (
34
+ // Doing loose != check instead of !== type check
35
+ currentData[key] != value &&
36
+ isNotNull
37
+ ) {
38
+ if (value && typeof value === 'object') {
39
+ hasChanges = !areObjectsEqual(currentData[key], value);
40
+ } else {
41
+ hasChanges = true;
42
+ }
43
+
44
+ if (hasChanges) {
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ if (mergeCurrentData) {
52
+ for (const key in currentData) {
53
+ if (Object.prototype.hasOwnProperty.call(currentData, key) && documentData[key] === undefined) {
54
+ documentData[key] = currentData[key];
55
+ }
56
+ }
57
+ }
58
+
59
+ const action = hasChanges ? 'UPDATE' : 'NONE';
60
+
61
+ return {
62
+ action,
63
+ documentData,
64
+ };
61
65
  }
62
66
 
63
67
  /**
@@ -65,28 +69,28 @@ function getDatabaseAction(
65
69
  */
66
70
 
67
71
  export function formValuesAreDiff(currentValues: any, formValues: any): boolean {
68
- if (!formValues && formValues !== 0) {
69
- // If formValues are null, it's not set yet
70
- return false;
71
- }
72
-
73
- if (typeof formValues === 'object') {
74
- // for (const key in currentValues) {
75
- // if (
76
- // currentValues[key] !== formValues[key] &&
77
- // // This would not work for values with number 0, but I don't think that's an issue for any mutations right now
78
- // (currentValues[key] !== null || formValues[key] !== undefined)
79
- // ) {
80
- // console.log('DIFF!:', key, currentValues[key], formValues[key]);
81
- // return true;
82
- // }
83
- // }
84
-
85
- const result = getDatabaseAction(currentValues, formValues);
86
- return result.action !== 'NONE';
87
- }
88
-
89
- return currentValues !== formValues;
72
+ if (!formValues && formValues !== 0) {
73
+ // If formValues are null, it's not set yet
74
+ return false;
75
+ }
76
+
77
+ if (typeof formValues === 'object') {
78
+ // for (const key in currentValues) {
79
+ // if (
80
+ // currentValues[key] !== formValues[key] &&
81
+ // // This would not work for values with number 0, but I don't think that's an issue for any mutations right now
82
+ // (currentValues[key] !== null || formValues[key] !== undefined)
83
+ // ) {
84
+ // console.log('DIFF!:', key, currentValues[key], formValues[key]);
85
+ // return true;
86
+ // }
87
+ // }
88
+
89
+ const result = getDatabaseAction(currentValues, formValues, true);
90
+ return result.action !== 'NONE';
91
+ }
92
+
93
+ return currentValues !== formValues;
90
94
  }
91
95
 
92
96
  /**
@@ -94,18 +98,35 @@ export function formValuesAreDiff(currentValues: any, formValues: any): boolean
94
98
  */
95
99
 
96
100
  export function useMounted() {
97
- const mounted = useRef(true);
98
-
99
- useEffect(() => {
100
- // This is necessary, I don't know why, this hook unmounteds itself and remounts even though the dependencies are empty
101
- // NOTE: This behavior was seen in [gqlClient.ts]
102
- mounted.current = true;
103
- return () => {
104
- mounted.current = false;
105
- };
106
- }, []);
107
-
108
- return mounted;
101
+ const mounted = useRef(true);
102
+
103
+ useEffect(() => {
104
+ // This is necessary, I don't know why, this hook unmounteds itself and remounts even though the dependencies are empty
105
+ // NOTE: This behavior was seen in [gqlClient.ts]
106
+ mounted.current = true;
107
+ return () => {
108
+ mounted.current = false;
109
+ };
110
+ }, []);
111
+
112
+ return mounted;
113
+ }
114
+
115
+ /**
116
+ * Return the computer timezone after client hydration.
117
+ */
118
+
119
+ let cachedComputerTimeZone: string | null = null;
120
+
121
+ export function useComputerTimeZone() {
122
+ const [timeZone, setTimeZone] = useState<string | null>(cachedComputerTimeZone);
123
+
124
+ useEffect(() => {
125
+ cachedComputerTimeZone ??= Intl.DateTimeFormat().resolvedOptions().timeZone;
126
+ setTimeZone(cachedComputerTimeZone);
127
+ }, []);
128
+
129
+ return timeZone;
109
130
  }
110
131
 
111
132
  /**
@@ -113,57 +134,54 @@ export function useMounted() {
113
134
  */
114
135
 
115
136
  export function useWatchChange(
116
- currentValues: any,
117
- formValues: any,
118
- saving: boolean,
119
- onChangeDiff: (hasChanges: boolean, saving: boolean) => void,
120
- onDataUpdated: () => void,
137
+ currentValues: any,
138
+ formValues: any,
139
+ saving: boolean,
140
+ onChangeDiff: (hasChanges: boolean, saving: boolean) => void,
141
+ onDataUpdated: () => void,
121
142
  ) {
122
- const isDiff = useMemo(() => {
123
- return formValuesAreDiff(currentValues, formValues);
124
- }, [currentValues, formValues]);
125
-
126
- useEffect(() => {
127
- onChangeDiff(isDiff, saving);
128
- }, [isDiff, saving]);
129
-
130
- useEffect(() => {
131
- if (!saving) {
132
- // Always update, because isDiff memo() only listens to formValues (and not currentValues)
133
- onDataUpdated();
134
- }
135
- }, [saving]);
143
+ const isDiff = useMemo(() => {
144
+ return formValuesAreDiff(currentValues, formValues);
145
+ }, [currentValues, formValues]);
146
+
147
+ useEffect(() => {
148
+ onChangeDiff(isDiff, saving);
149
+ }, [isDiff, saving]);
150
+
151
+ useEffect(() => {
152
+ if (!saving) {
153
+ // Always update, because isDiff memo() only listens to formValues (and not currentValues)
154
+ onDataUpdated();
155
+ }
156
+ }, [saving]);
136
157
  }
137
158
 
138
159
  /**
139
160
  * Check props diff (logging for dev)
140
161
  */
141
162
 
142
- export function checkPropsDiff(pp, np) {
143
- let isSame = true;
144
- for (const k in pp) {
145
- if (Object.prototype.hasOwnProperty.call(pp, k) && pp[k] !== np[k]) {
146
- console.log('Diff:', k);
147
- isSame = false;
148
- }
149
- }
150
-
151
- for (const k in np) {
152
- if (
153
- Object.prototype.hasOwnProperty.call(np, k) &&
154
- !Object.prototype.hasOwnProperty.call(pp, k) &&
155
- np[k] !== pp[k]
156
- ) {
157
- console.log('New Prop:', k);
158
- isSame = false;
159
- }
160
- }
161
-
162
- return isSame;
163
+ export function checkPropsDiff(pp: any, np: any) {
164
+ let isSame = true;
165
+ for (const k in pp) {
166
+ if (Object.prototype.hasOwnProperty.call(pp, k) && pp[k] !== np[k]) {
167
+ console.log('Diff:', k);
168
+ isSame = false;
169
+ }
170
+ }
171
+
172
+ for (const k in np) {
173
+ if (Object.prototype.hasOwnProperty.call(np, k) && !Object.prototype.hasOwnProperty.call(pp, k) && np[k] !== pp[k]) {
174
+ console.log('New Prop:', k);
175
+ isSame = false;
176
+ }
177
+ }
178
+
179
+ return isSame;
163
180
  }
164
181
 
165
182
  if (globalThis && globalThis.location?.origin?.indexOf('localhost') >= 0) {
166
- globalThis.checkPropsDiff = checkPropsDiff;
183
+ // @ts-ignore - Dev only shim
184
+ globalThis.checkPropsDiff = checkPropsDiff;
167
185
  }
168
186
 
169
187
  /**
@@ -171,147 +189,277 @@ if (globalThis && globalThis.location?.origin?.indexOf('localhost') >= 0) {
171
189
  */
172
190
 
173
191
  export function arePropsEqualExceptChildren(pp: any, np: any) {
174
- for (const k in np) {
175
- if (
176
- Object.prototype.hasOwnProperty.call(np, k) &&
177
- k !== 'children' &&
178
- (
179
- !Object.prototype.hasOwnProperty.call(pp, k) ||
180
- np[k] !== pp[k]
181
- )
182
- ) {
183
- // console.log('DIFF:', k, pp[k], np[k]);
184
- return false;
185
- }
186
- }
187
- return true;
192
+ for (const k in np) {
193
+ if (
194
+ Object.prototype.hasOwnProperty.call(np, k) &&
195
+ k !== 'children' &&
196
+ (!Object.prototype.hasOwnProperty.call(pp, k) || np[k] !== pp[k])
197
+ ) {
198
+ // console.log('DIFF:', k, pp[k], np[k]);
199
+ return false;
200
+ }
201
+ }
202
+ return true;
188
203
  }
189
204
 
190
205
  /**
191
206
  * Keep track of visibility state change and copy props;
192
- * To be used in animation components
207
+ * To be used in animation components.
208
+ *
209
+ * You can use this hook to animate an element to fade out before returning
210
+ * null. Pass a truthy value while the element should be visible, render while
211
+ * visibility is not 0, and apply fade classes from the visibility value.
212
+ *
213
+ * Example:
214
+ *
215
+ * const [, visibility] = useAnimationVisibility(visible);
216
+ * const active = visibility >= 2;
217
+ *
218
+ * if (!visibility) {
219
+ * return null;
220
+ * }
221
+ *
222
+ * return <div className={cn('trans_op spd_2', active ? 'op_100' : 'op_0')} />;
193
223
  */
194
224
 
195
- type VisibilityValue = 0 | .5 | 1 | 2;
196
-
197
- export function useAnimationVisibility(
198
- props: any,
199
- onHasProps?: (hasProps: boolean) => void,
200
- ): [
201
- any,
202
- VisibilityValue,
203
- (VisibilityValue: VisibilityValue) => void,
204
- ] {
205
- const [visible, setVisible] = useState(0 as VisibilityValue);
206
- const [persistedProps, setPersistedProps] = useState({});
207
- const hasData = !!props;
208
-
209
- useEffect(() => {
210
- if (props) {
211
- setPersistedProps({ ...props });
212
- }
213
- if (onHasProps) {
214
- onHasProps(hasData);
215
- }
216
- }, [props]);
217
-
218
- useEffect(() => {
219
- if (visible === 1) {
220
- if (hasData) {
221
- const timer = setTimeout(() => {
222
- setVisible(2);
223
- }, 100);
224
- return () => clearTimeout(timer);
225
- } else {
226
- const timer = setTimeout(() => {
227
- setVisible(0);
228
- }, 300);
229
- return () => clearTimeout(timer);
230
- }
231
- } else if (visible === .5) {
232
- // Use custom exit function if .5
233
- return;
234
- }
235
-
236
- const shouldBeValue = hasData ? 2 : 0;
237
- if (shouldBeValue !== visible) {
238
- setVisible(1);
239
- }
240
- }, [visible, hasData]);
241
-
242
- return [persistedProps, visible, setVisible];
225
+ type VisibilityValue = 0 | 0.5 | 1 | 2;
226
+
227
+ export function useAnimationVisibility<T>(
228
+ props: T,
229
+ onHasProps?: (hasProps: boolean) => void,
230
+ ): [any, VisibilityValue, (VisibilityValue: VisibilityValue) => void] {
231
+ const [visibility, setVisibility] = useState(0 as VisibilityValue);
232
+ const [persistedProps, setPersistedProps] = useState<T>(props as T);
233
+ const hasData = !!props;
234
+
235
+ useEffect(() => {
236
+ if (props) {
237
+ setPersistedProps(props);
238
+ }
239
+ onHasProps?.(hasData);
240
+ }, [props]);
241
+
242
+ useEffect(() => {
243
+ if (visibility === 1) {
244
+ if (hasData) {
245
+ const timer = setTimeout(() => {
246
+ setVisibility(2);
247
+ }, 100);
248
+ return () => clearTimeout(timer);
249
+ } else {
250
+ const timer = setTimeout(() => {
251
+ setVisibility(0);
252
+ }, 300);
253
+ return () => clearTimeout(timer);
254
+ }
255
+ } else if (visibility === 0.5) {
256
+ const timer = setTimeout(() => {
257
+ setVisibility(0);
258
+ }, 300);
259
+ return () => clearTimeout(timer);
260
+ }
261
+
262
+ const shouldBeValue = hasData ? 2 : 0;
263
+ if (shouldBeValue !== visibility) {
264
+ setVisibility(hasData ? 1 : 0.5);
265
+ }
266
+ }, [visibility, hasData]);
267
+
268
+ return [persistedProps, visibility, setVisibility];
243
269
  }
244
270
 
245
271
  /**
246
- * Use in-component visibility state (0 | 1 | 2)
272
+ * Check if image are loaded
273
+ * NOTE: This only checks on mount
247
274
  */
248
275
 
249
- export function useVisible(
250
- openOnMount: boolean = true,
251
- onVisible?: (val: number) => void
252
- ): [
253
- 0 | .5 | 1 | 2,
254
- (val: 0 | .5 | 1 | 2) => void
255
- ] {
256
-
257
- const [visible, setVisible] = useState(0 as 0 | .5 | 1 | 2);
258
- const allowOpen = useRef(openOnMount);
259
-
260
- useEffect(() => {
261
- if (onVisible) {
262
- onVisible(visible);
263
- }
264
-
265
- switch (visible) {
266
- case 0:
267
- if (!allowOpen.current) {
268
- allowOpen.current = true;
269
- return;
270
- }
271
-
272
- setVisible(1);
273
- break;
274
- case .5: {
275
- const timer = setTimeout(() => {
276
- allowOpen.current = false;
277
- setVisible(0);
278
- }, 100);
279
- return () => { clearTimeout(timer); };
280
- }
281
- case 1: {
282
- const timer = setTimeout(() => {
283
- setVisible(2);
284
- }, 100);
285
- return () => { clearTimeout(timer); };
286
- }
287
- case 2:
288
- break;
289
- }
290
- }, [visible]);
291
-
292
- return [visible, setVisible];
276
+ export function useImagesLoadStatus(
277
+ imageUrls: string[],
278
+ timeoutMS = 10000, // default timeout miliseconds
279
+ ): boolean {
280
+ const [loaded, setLoaded] = useState(false);
281
+
282
+ useEffect(() => {
283
+ if (!imageUrls || imageUrls.length === 0) {
284
+ setLoaded(true);
285
+ return;
286
+ }
287
+
288
+ let isCancelled = false;
289
+ let loadedCount = 0;
290
+ const timeout = setTimeout(() => {
291
+ if (!isCancelled) {
292
+ setLoaded(true);
293
+ }
294
+ }, timeoutMS);
295
+
296
+ const handleLoad = () => {
297
+ loadedCount += 1;
298
+ if (loadedCount === imageUrls.length && !isCancelled) {
299
+ clearTimeout(timeout);
300
+ setLoaded(true);
301
+ }
302
+ };
303
+
304
+ const handleError = () => {
305
+ loadedCount += 1; // count errors too, so they don’t block loading
306
+ if (loadedCount === imageUrls.length && !isCancelled) {
307
+ clearTimeout(timeout);
308
+ setLoaded(true);
309
+ }
310
+ };
311
+
312
+ const imageElements = imageUrls.map((url) => {
313
+ const img = new Image();
314
+ img.onload = handleLoad;
315
+ img.onerror = handleError;
316
+ img.src = url;
317
+ return img;
318
+ });
319
+
320
+ return () => {
321
+ isCancelled = true;
322
+ clearTimeout(timeout);
323
+ // Optional: clear handlers to prevent leaks
324
+ imageElements.forEach((img) => {
325
+ img.onload = null;
326
+ img.onerror = null;
327
+ });
328
+ };
329
+ }, []);
330
+
331
+ return loaded;
293
332
  }
294
333
 
295
- /**
296
- * Create an infinite loop timer
334
+ /*
335
+ * Hold local object URLs (e.g. image previews) while mounted, so they outlive the component that created them.
336
+ */
337
+
338
+ export function useRetainedObjectUrls(urls: (string | null | undefined)[]) {
339
+ const urlsKey = urls.filter(Boolean).join('\n');
340
+
341
+ useEffect(() => {
342
+ const retainedUrls = urlsKey ? urlsKey.split('\n') : [];
343
+ for (const url of retainedUrls) {
344
+ retainObjectUrl(url);
345
+ }
346
+
347
+ return () => {
348
+ for (const url of retainedUrls) {
349
+ releaseObjectUrl(url);
350
+ }
351
+ };
352
+ }, [urlsKey]);
353
+ }
354
+
355
+ /*
356
+ * Track whether a referenced div's scroll position has passed a pixel offset.
297
357
  */
298
358
 
299
- export function useTimer(
300
- refreshInterval: number = 60000
301
- ): null | number {
359
+ export function useScrollPastPosition(pixels: number) {
360
+ const divRef = useRef<HTMLDivElement>(null);
361
+ const [hasScrolledPast, setHasScrolledPast] = useState(false);
362
+
363
+ useEffect(() => {
364
+ const element = divRef.current;
365
+ if (!element) {
366
+ return;
367
+ }
302
368
 
303
- const [timestamp, setTimestamp] = useState<null | number>(null);
304
- const appIsHidden = isAppHidden();
369
+ const handleScroll = () => {
370
+ const nextValue = element.scrollTop > pixels;
305
371
 
306
- useEffect(() => {
307
- const timeout = setTimeoutPriority(() => {
308
- setTimestamp(Date.now());
309
- }, refreshInterval);
372
+ setHasScrolledPast((currentValue) => {
373
+ return currentValue === nextValue ? currentValue : nextValue;
374
+ });
375
+ };
310
376
 
311
- return () => {
312
- clearTimeout(timeout);
313
- };
314
- }, [appIsHidden, timestamp]);
377
+ element.addEventListener('scroll', handleScroll, { passive: true });
378
+ handleScroll();
379
+
380
+ return () => {
381
+ element.removeEventListener('scroll', handleScroll);
382
+ };
383
+ }, [pixels]);
384
+
385
+ return [divRef, hasScrolledPast] as const;
386
+ }
387
+
388
+ export type ScrollNavState = 'STATIC' | 'HIDDEN' | 'SHOWN';
389
+
390
+ interface ScrollNavValue {
391
+ navState: ScrollNavState;
392
+ // Whether the page is scrolled past `staticOffset` (independent of scroll direction)
393
+ pastOffset: boolean;
394
+ }
395
+
396
+ /*
397
+ * Track the state of a hide-on-scroll window nav.
398
+ * 'STATIC' from page load until the page scrolls down past `staticOffset` (the nav sits in the page flow),
399
+ * then 'HIDDEN' while scrolling down and 'SHOWN' as soon as the page scrolls back up. Once shown, the nav
400
+ * stays fixed all the way up and only returns to 'STATIC' at the very top, where the two line up.
401
+ * Scroll deltas smaller than `minDelta` are ignored so trackpad jitter does not flip the direction.
402
+ */
315
403
 
316
- return timestamp;
404
+ export function useScrollNavState(staticOffset = 0, minDelta = 4) {
405
+ const [value, setValue] = useState<ScrollNavValue>({ navState: 'STATIC', pastOffset: false });
406
+
407
+ useEffect(() => {
408
+ let lastScrollY = window.scrollY;
409
+ let frameRequested = false;
410
+
411
+ const update = () => {
412
+ frameRequested = false;
413
+ const scrollY = window.scrollY;
414
+ const delta = scrollY - lastScrollY;
415
+ const isDirectionChange = Math.abs(delta) >= minDelta;
416
+
417
+ if (isDirectionChange) {
418
+ lastScrollY = scrollY;
419
+ }
420
+
421
+ const pastOffset = scrollY > staticOffset;
422
+
423
+ const getNavState = (currentValue: ScrollNavState): ScrollNavState => {
424
+ // Negative scrollY happens during rubber-band overscroll; it counts as the top.
425
+ if (scrollY <= 0) {
426
+ return 'STATIC';
427
+ }
428
+ if (isDirectionChange) {
429
+ if (delta > 0) {
430
+ return pastOffset ? 'HIDDEN' : currentValue;
431
+ }
432
+ return currentValue === 'STATIC' ? 'STATIC' : 'SHOWN';
433
+ }
434
+ // Landed past the offset without a real scroll (e.g. restored scroll position on load)
435
+ return currentValue === 'STATIC' && pastOffset ? 'SHOWN' : currentValue;
436
+ };
437
+
438
+ setValue((currentValue) => {
439
+ const navState = getNavState(currentValue.navState);
440
+ // Keep the same object when nothing changed so scroll frames do not re-render the nav
441
+ if (navState === currentValue.navState && pastOffset === currentValue.pastOffset) {
442
+ return currentValue;
443
+ }
444
+ return { navState, pastOffset };
445
+ });
446
+ };
447
+
448
+ // Coalesce bursts of scroll events into one read per frame
449
+ const handleScroll = () => {
450
+ if (!frameRequested) {
451
+ frameRequested = true;
452
+ window.requestAnimationFrame(update);
453
+ }
454
+ };
455
+
456
+ window.addEventListener('scroll', handleScroll, { passive: true });
457
+ update();
458
+
459
+ return () => {
460
+ window.removeEventListener('scroll', handleScroll);
461
+ };
462
+ }, [staticOffset, minDelta]);
463
+
464
+ return value;
317
465
  }