@jsb188/react 1.0.0

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 ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@jsb188/react",
3
+ "version": "1.0.0",
4
+ "description": "Contains react (and DOM) related utils and hooks.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "exports": {
9
+ "./dom": "./utils/dom.ts",
10
+ "./hooks": "./utils/hooks.ts",
11
+ "./icons": "./icons/Icon.tsx",
12
+ "./priorityTimeout": "./utils/priorityTimeout.ts",
13
+ "./types/dom": "./types/dom.d.ts"
14
+ },
15
+ "dependencies": {
16
+ "react": "^18.2.0"
17
+ },
18
+ "devDependencies": {
19
+ "@types/react": "^18.2.20"
20
+ },
21
+ "scripts": {
22
+ "test": "echo \"Error: no test specified\" && exit 1"
23
+ }
24
+ }
package/types/dom.d.ts ADDED
@@ -0,0 +1,7 @@
1
+
2
+ // Common react types
3
+
4
+ export type ReactSpanElement = React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>;
5
+ export type ReactDivElement = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
6
+ export type ReactButtonElement = React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
7
+ export type ReactLabelElement = React.DetailedHTMLProps<React.LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>;
package/utils/dom.ts ADDED
@@ -0,0 +1,303 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ /**
4
+ * Check if parent has class name
5
+ */
6
+
7
+ export function parentHasClassName(el: HTMLElement | null, cnRegex: RegExp, count = 0): boolean {
8
+ if (!el || (!el.className && !el.parentNode)) {
9
+ return false;
10
+ } else if (
11
+ typeof el.className === 'string' && cnRegex && cnRegex.test(el.className)
12
+ ) {
13
+ // console.log('!!!!!!!!!!', el && el.className, '::::', cnRegex);
14
+ // NOTE: FontAwesome elements may return an SVG as className
15
+ // So a "string" check is required
16
+ return true;
17
+ }
18
+
19
+ // if (el) {
20
+ // console.log(':::>', el.className, cnRegex, cnRegex.test(el.className));
21
+ // }
22
+
23
+ return (
24
+ !!el.parentNode &&
25
+ count < 10 &&
26
+ parentHasClassName(el.parentNode as HTMLElement, cnRegex, count + 1)
27
+ );
28
+ }
29
+
30
+ /**
31
+ * Detect click outside
32
+ */
33
+
34
+ export function useOnClickOutside(
35
+ ref: React.RefObject<HTMLElement | undefined>,
36
+ listening: boolean,
37
+ listenToResize: boolean,
38
+ ignoreClassName: string | null,
39
+ onClickOutside?: (e: MouseEvent | Event, isResize: boolean) => void,
40
+ ) {
41
+ const isListening = listening && typeof onClickOutside === 'function';
42
+
43
+ useEffect(() => {
44
+ if (isListening) {
45
+ const handleClickOutside = (e: MouseEvent) => {
46
+ if (ref.current && !ref.current.contains(e.target as Node)) {
47
+ // console.log('(1) in');
48
+ const overlayEl = document.getElementById('root-overlay');
49
+ // const check = !overlayEl || !overlayEl.contains(e.target);
50
+
51
+ // Bring this back if you want to allow from outside the ref
52
+ const check1 = !overlayEl || !overlayEl.contains(e.target as Node);
53
+ const check2 = !ignoreClassName ||
54
+ !parentHasClassName(
55
+ e.target as HTMLElement,
56
+ new RegExp('\\b' + ignoreClassName + '\\b'),
57
+ );
58
+ // const check3 = !selfContainerClassName || !parentHasClassName(e.target, new RegExp('\\b' + selfContainerClassName + '\\b'));
59
+ // if (check1 && check2 && check3) {
60
+
61
+ if (check1 && check2) {
62
+ onClickOutside(e, false);
63
+ }
64
+ }
65
+ };
66
+
67
+ let handleResize: (e: Event) => void;
68
+ if (listenToResize) {
69
+ handleResize = (e: Event) => onClickOutside(e, true);
70
+ globalThis.addEventListener('resize', handleResize);
71
+ }
72
+
73
+ document.addEventListener('mousedown', handleClickOutside);
74
+
75
+ return () => {
76
+ document.removeEventListener('mousedown', handleClickOutside);
77
+
78
+ if (handleResize) {
79
+ globalThis.removeEventListener('resize', handleResize);
80
+ }
81
+ };
82
+ }
83
+ }, [isListening]);
84
+ }
85
+
86
+ /**
87
+ * Focus element if it exists
88
+ */
89
+
90
+ export function focusElement(elemId: string) {
91
+ const el = document.getElementById(elemId);
92
+ if (el) {
93
+ el.focus();
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Get platform shortcut
99
+ */
100
+
101
+ export function platformShortcut(key: string) {
102
+ const isMac = /Mac|iPhone|iPod|iPad/i.test(globalThis.navigator?.platform);
103
+ return (isMac ? '⌘' : '^') + key;
104
+ }
105
+
106
+ /**
107
+ * Quick helper for copying a text to clipboard
108
+ */
109
+
110
+ export function useCopyToClipboard(textToCopy: string, resetTimeMS: number = 2250): [boolean, () => void] {
111
+ const [copied, setCopied] = useState(false);
112
+
113
+ useEffect(() => {
114
+ if (copied) {
115
+ const timer = setTimeout(() => {
116
+ setCopied(false);
117
+ }, resetTimeMS);
118
+ return () => clearTimeout(timer);
119
+ }
120
+ }, [copied]);
121
+
122
+ const onClickCopy = () => {
123
+ const el = document.createElement('textarea');
124
+ el.value = textToCopy;
125
+ document.body.appendChild(el);
126
+ el.select();
127
+ document.execCommand('copy');
128
+ document.body.removeChild(el);
129
+ setCopied(true);
130
+ };
131
+
132
+ return [copied, onClickCopy];
133
+ }
134
+
135
+ /**
136
+ * Remove HTML from text when pasting to conten editable
137
+ */
138
+
139
+ export async function removeHTMLfromPaste(e: React.ClipboardEvent) {
140
+ if (typeof navigator?.clipboard?.readText === 'function') {
141
+ // This is not available on older browsers
142
+ const clipboardText = await navigator.clipboard.readText();
143
+ return clipboardText;
144
+ }
145
+
146
+ // @ts-expect-error - Older browser deprecation support
147
+ const html = (e.originalEvent || e).clipboardData.getData('text/html');
148
+ const result = document.createElement('div');
149
+ result.innerHTML = html;
150
+
151
+ result.querySelectorAll('style').forEach((el) => el.remove());
152
+ result.querySelectorAll('meta').forEach((el) => el.remove());
153
+ result.querySelectorAll('link').forEach((el) => el.remove());
154
+
155
+ result.querySelectorAll('img').forEach(img => {
156
+ const altText = img.alt || '';
157
+ const textNode = document.createTextNode(altText);
158
+ img.replaceWith(textNode);
159
+ });
160
+
161
+ result.querySelectorAll('br').forEach(br => {
162
+ const textNode = document.createTextNode('\n');
163
+ br.replaceWith(textNode);
164
+ });
165
+
166
+ // result.querySelectorAll('p').forEach(p => {
167
+ // const textNode = document.createTextNode('\n');
168
+ // p.replaceWith(textNode);
169
+ // });
170
+
171
+ // result.querySelectorAll('div').forEach(div => {
172
+ // const textNode = document.createTextNode('\n');
173
+ // div.replaceWith(textNode);
174
+ // });
175
+
176
+ const text = result.innerHTML
177
+ .replace(/<\/?[^`]+?\/?>/gmi, '\n')
178
+ .replace(/\n[\s]*\n/gmi, '\n')
179
+ .trim();
180
+
181
+ // NOTE: If copied from inside the content editable, "double line breaks" will become single.
182
+ // So result.innerText would be correct in this case.
183
+ // But if html is copied from outside, then reuslt.innerText would remove all line breaks,
184
+ // Making text.replace(..) correct.
185
+ // There's no way to tell where the text was copied, so use text as the output.
186
+ // This is a small issue becasue all modern browsers will have access to navigator.clipboard.readText()
187
+
188
+ return text;
189
+ }
190
+
191
+ /**
192
+ * Get text from the entire DOM element;
193
+ * including text form of all child elements.
194
+ */
195
+
196
+ export function getTextFromDOMElement(el: HTMLElement): string {
197
+ const clone = el.cloneNode(true) as HTMLElement;
198
+
199
+ // Replace all <img> elements with their alt text
200
+ clone.querySelectorAll('img').forEach(img => {
201
+ const altText = img.alt || '';
202
+ const textNode = document.createTextNode(altText);
203
+ img.replaceWith(textNode);
204
+ });
205
+
206
+ clone.querySelectorAll('br').forEach(br => {
207
+ const textNode = document.createTextNode('\n');
208
+ br.replaceWith(textNode);
209
+ });
210
+
211
+ return clone.textContent || '';
212
+ }
213
+
214
+ /**
215
+ * Remove HTML and paste text at caret position
216
+ */
217
+
218
+ export async function pasteTextAtCaret(e: React.ClipboardEvent, cb: (text: string) => void) {
219
+ e.preventDefault();
220
+ const text = await removeHTMLfromPaste(e);
221
+
222
+ if (globalThis.getSelection) {
223
+ // IE9 and non-IE
224
+ const sel = globalThis.getSelection();
225
+ if (sel?.getRangeAt && sel.rangeCount) {
226
+ let range = sel.getRangeAt(0);
227
+ range.deleteContents();
228
+
229
+ // Range.createContextualFragment() would be useful here but is
230
+ // non-standard and not supported in all browsers (IE9, for one)
231
+ const el = document.createElement('div');
232
+ el.innerHTML = text;
233
+
234
+ let node;
235
+ let lastNode;
236
+ const frag = document.createDocumentFragment();
237
+
238
+ while ((node = el.firstChild)) {
239
+ lastNode = frag.appendChild(node);
240
+ }
241
+
242
+ range.insertNode(frag);
243
+
244
+ // Preserve the selection
245
+ if (lastNode) {
246
+ range = range.cloneRange();
247
+ range.setStartAfter(lastNode);
248
+ range.collapse(true);
249
+ sel.removeAllRanges();
250
+ sel.addRange(range);
251
+ }
252
+ }
253
+ } else if (
254
+ // @ts-expect-error - Deprecation support
255
+ document.selection && document.selection.type != 'Control'
256
+ ) {
257
+ // @ts-expect-error - IE < 9
258
+ document.selection.createRange().pasteHTML(text);
259
+ }
260
+
261
+ const activeEl = document.activeElement;
262
+ if (activeEl) {
263
+ cb((activeEl as HTMLElement).innerText || '');
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Take the current position of caret in content editable;
269
+ * then update the innerHTML and then set the caret back to the same position.
270
+ */
271
+
272
+ export function updateInnerHTMLRepositionCaret(
273
+ el: HTMLElement,
274
+ nextHTMLText: string,
275
+ ) {
276
+ const sel = globalThis.getSelection();
277
+ if (sel) {
278
+ const lenDiff = nextHTMLText.length - el.innerText.length;
279
+ const range = sel.getRangeAt(0);
280
+ const start = range.startOffset + lenDiff;
281
+ const end = range.endOffset + lenDiff;
282
+
283
+ el.innerHTML = nextHTMLText;
284
+
285
+ const newMaxLen = el.innerText.length;
286
+ if (newMaxLen > start && newMaxLen > end) {
287
+ const newRange = new Range();
288
+ newRange.setStart(el.childNodes[0], Math.min(start, newMaxLen));
289
+ newRange.setEnd(el.childNodes[0], Math.min(end, newMaxLen));
290
+ } else {
291
+ // This means start/end position exceeds the new length;
292
+ // this would happen when you try to replace text with a DOM element (such as <img />)
293
+ // For this situation, set the caret at end of the text.
294
+
295
+ el.focus();
296
+ const range = document.createRange();
297
+ range.selectNodeContents(el);
298
+ range.collapse(false);
299
+ sel.removeAllRanges();
300
+ sel.addRange(range);
301
+ }
302
+ }
303
+ }
package/utils/hooks.ts ADDED
@@ -0,0 +1,317 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { isAppHidden, setTimeoutPriority } from './priorityTimeout';
3
+
4
+ /**
5
+ * Check if database document needs an update, insert, or do nothing based on the user API arguments
6
+ * NOTE: There is a copy paste of this function in @jsb188/app/utils/logic.ts
7
+ * NOTE: Do *NOT* export this function.
8
+ */
9
+
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
+ };
61
+ }
62
+
63
+ /**
64
+ * Basic diff check
65
+ */
66
+
67
+ 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;
90
+ }
91
+
92
+ /**
93
+ * Use mounted state
94
+ */
95
+
96
+ 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;
109
+ }
110
+
111
+ /**
112
+ * Watch form value change and run action when the ouput is different
113
+ */
114
+
115
+ export function useWatchChange(
116
+ currentValues: any,
117
+ formValues: any,
118
+ saving: boolean,
119
+ onChangeDiff: (hasChanges: boolean, saving: boolean) => void,
120
+ onDataUpdated: () => void,
121
+ ) {
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]);
136
+ }
137
+
138
+ /**
139
+ * Check props diff (logging for dev)
140
+ */
141
+
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
+ }
164
+
165
+ if (globalThis && globalThis.location?.origin?.indexOf('localhost') >= 0) {
166
+ globalThis.checkPropsDiff = checkPropsDiff;
167
+ }
168
+
169
+ /**
170
+ * Check if props are same; except for children
171
+ */
172
+
173
+ 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;
188
+ }
189
+
190
+ /**
191
+ * Keep track of visibility state change and copy props;
192
+ * To be used in animation components
193
+ */
194
+
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];
243
+ }
244
+
245
+ /**
246
+ * Use in-component visibility state (0 | 1 | 2)
247
+ */
248
+
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];
293
+ }
294
+
295
+ /**
296
+ * Create an infinite loop timer
297
+ */
298
+
299
+ export function useTimer(
300
+ refreshInterval: number = 60000
301
+ ): null | number {
302
+
303
+ const [timestamp, setTimestamp] = useState<null | number>(null);
304
+ const appIsHidden = isAppHidden();
305
+
306
+ useEffect(() => {
307
+ const timeout = setTimeoutPriority(() => {
308
+ setTimestamp(Date.now());
309
+ }, refreshInterval);
310
+
311
+ return () => {
312
+ clearTimeout(timeout);
313
+ };
314
+ }, [appIsHidden, timestamp]);
315
+
316
+ return timestamp;
317
+ }
@@ -0,0 +1,57 @@
1
+
2
+ let BROWSER_HIDDEN_TIME = 0;
3
+
4
+ /**
5
+ * Check if browser (or app) is hidden
6
+ * NOTE: Change this function for Mobile
7
+ */
8
+
9
+ export function isAppHidden() {
10
+ return globalThis.document?.hidden;
11
+ }
12
+
13
+ /**
14
+ * Keep track of browser hidden time
15
+ */
16
+
17
+ export function setAppVisibilityTime() {
18
+ BROWSER_HIDDEN_TIME = globalThis.document?.hidden ? Date.now() : 0;
19
+ }
20
+
21
+ /**
22
+ * When browser is un-focused for a while, all timeouts/intervals are paused.
23
+ * When the user resumes focus on the browser, all the paused timeouts/intervals are executed at once.
24
+ * This will cause a huge spike in CPU, causing the browser to freeze for a few seconds.
25
+ * To avoid this, we can use the Page Visibility API to detect when the browser is not visible.
26
+ */
27
+
28
+ export function setTimeoutPriority(fn: () => void, ms: number, ignoreIfLowPriority: boolean = false) {
29
+
30
+ // NOTE: You can check if browser is visible or hidden with:
31
+ // document.visibilityState === 'visible' or document.hidden === false
32
+ // document.hidden has more browser support than document.visibilityState
33
+
34
+ if (!globalThis.document?.hidden || !requestIdleCallback) {
35
+ // Browser is not tabbed out, so continue with normal timer
36
+ return setTimeout(fn, ms);
37
+ }
38
+
39
+ // Browser is tabbed out, so there *might* be a reason for low priority execution mode check
40
+
41
+ const now = Date.now();
42
+ const isLowPriorityMode = (now - BROWSER_HIDDEN_TIME) > 900000; // 15 minutes
43
+
44
+ // console.log('isLowPriorityMode', isLowPriorityMode, (now - BROWSER_HIDDEN_TIME));
45
+
46
+ if (isLowPriorityMode && ignoreIfLowPriority) {
47
+ // Exit without executing the function
48
+ return 0;
49
+ }
50
+
51
+ // During low priority mode, use requestIdleCallback() instead,
52
+ // which will execute the function in order when it's possible.
53
+ return requestIdleCallback(fn, { timeout: ms });
54
+ }
55
+
56
+ // More tips:
57
+ // Use requestIdleCallback() for heavy compute scripts that may get in the way of user experience or create JS lag