-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
594 lines (519 loc) · 16.1 KB
/
Copy pathindex.ts
File metadata and controls
594 lines (519 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { type Signal, signal } from "@preact/signals";
import {
type Fiber,
detectReactBuildType,
getRDTHook,
getType,
isInstrumentationActive,
} from "bippy";
import type { ComponentType } from "preact";
import type { ReactNode } from "preact/compat";
import type { RenderData } from "src/core/utils";
import { initReactScanInstrumentation } from "src/new-outlines";
import styles from "~web/assets/css/styles.css";
import { createToolbar } from "~web/toolbar";
import { IS_CLIENT } from "~web/utils/constants";
import { checkReactGrabVersion } from "~web/utils/check-react-grab-version";
import { readLocalStorage, saveLocalStorage } from "~web/utils/helpers";
import { parseSafeAreaOption } from "~web/utils/parse-safe-area-option";
import type { States } from "~web/views/inspector/utils";
import type { ChangeReason, Render, createInstrumentation } from "./instrumentation";
import { startTimingTracking } from "./notifications/event-tracking";
import { createHighlightCanvas } from "./notifications/outline-overlay";
import packageJson from "../../package.json";
let rootContainer: HTMLDivElement | null = null;
let shadowRoot: ShadowRoot | null = null;
interface RootContainer {
rootContainer: HTMLDivElement;
shadowRoot: ShadowRoot;
}
const initRootContainer = (): RootContainer => {
if (rootContainer && shadowRoot) {
return { rootContainer, shadowRoot };
}
rootContainer = document.createElement("div");
rootContainer.id = "react-scan-root";
shadowRoot = rootContainer.attachShadow({ mode: "open" });
const cssStyles = document.createElement("style");
cssStyles.textContent = styles;
shadowRoot.appendChild(cssStyles);
document.documentElement.appendChild(rootContainer);
return { rootContainer, shadowRoot };
};
export interface Options {
/**
* Enable/disable scanning
*
* Please use the recommended way:
* enabled: process.env.NODE_ENV === 'development',
*
* @default true
*/
enabled?: boolean;
/**
* Force React Scan to run in production (not recommended)
*
* @default false
*/
dangerouslyForceRunInProduction?: boolean;
/**
* Log renders to the console
*
* WARNING: This can add significant overhead when the app re-renders frequently
*
* @default false
*/
log?: boolean;
/**
* Show toolbar bar
*
* If you set this to true, and set {@link enabled} to false, the toolbar will still show, but scanning will be disabled.
*
* @default true
*/
showToolbar?: boolean;
/**
* Animation speed
*
* @default "fast"
*/
animationSpeed?: "slow" | "fast" | "off";
/**
* Track unnecessary renders, and mark their outlines gray when detected
*
* An unnecessary render is defined as the component re-rendering with no change to the component's
* corresponding dom subtree
*
* @default false
* @warning tracking unnecessary renders can add meaningful overhead to react-scan
*/
trackUnnecessaryRenders?: boolean;
/**
* Should the FPS meter show in the toolbar
*
* @default true
*/
showFPS?: boolean;
/**
* Should the number of slowdown notifications be shown in the toolbar
*
* @default true
*/
showNotificationCount?: boolean;
/**
* Allow React Scan to run inside iframes
*
* @default false
*/
allowInIframe?: boolean;
/**
* Distance (in pixels) the toolbar keeps from the viewport edges. Useful
* when other dev overlays (e.g. the Next.js dev indicator) sit in the same
* corner. Pass a single number to inset all edges, or an object to inset
* edges individually.
*
* @default 24
*/
safeArea?:
| number
| {
top?: number;
right?: number;
bottom?: number;
left?: number;
};
/**
* Render outline overlays via an OffscreenCanvas + Web Worker. Disable when
* a strict Content-Security-Policy without `worker-src blob:` would
* otherwise reject the blob worker — React Scan automatically falls back
* to main-thread rendering.
*
* @default true
*/
useOffscreenCanvasWorker?: boolean;
/**
* Should react scan log internal errors to the console.
*
* Useful if react scan is not behaving expected and you want to provide information to maintainers when submitting an issue https://github.com/aidenybai/react-scan/issues
*
* @default false
*/
_debug?: "verbose" | false;
onCommitStart?: () => void;
onRender?: (fiber: Fiber, renders: Array<Render>) => void;
onCommitFinish?: () => void;
}
export interface StoreType {
inspectState: Signal<States>;
wasDetailsOpen: Signal<boolean>;
lastReportTime: Signal<number>;
isInIframe: Signal<boolean>;
fiberRoots: WeakSet<Fiber>;
reportData: Map<number, RenderData>;
legacyReportData: Map<string, RenderData>;
changesListeners: Map<number, Array<ChangesListener>>;
interactionListeningForRenders: ((fiber: Fiber, renders: Array<Render>) => void) | null;
}
export type OutlineKey = `${string}-${string}`;
export interface Internals {
instrumentation: ReturnType<typeof createInstrumentation> | null;
componentAllowList: WeakMap<ComponentType<unknown>, Options> | null;
options: Signal<Options>;
onRender: ((fiber: Fiber, renders: Array<Render>) => void) | null;
Store: StoreType;
version: string;
runInAllEnvironments: boolean;
}
export type FunctionalComponentStateChange = {
type: ChangeReason.FunctionalState;
value: unknown;
prevValue?: unknown;
count?: number | undefined;
name: string;
};
export type ClassComponentStateChange = {
type: ChangeReason.ClassState;
value: unknown;
prevValue?: unknown;
count?: number | undefined;
name: "state";
};
export type StateChange = FunctionalComponentStateChange | ClassComponentStateChange;
export type PropsChange = {
type: ChangeReason.Props;
name: string;
value: unknown;
prevValue?: unknown;
count?: number | undefined;
};
export type ContextChange = {
type: ChangeReason.Context;
name: string;
value: unknown;
prevValue?: unknown;
count?: number | undefined;
contextType: number;
};
export type Change = StateChange | PropsChange | ContextChange;
export type ChangesPayload = {
propsChanges: Array<PropsChange>;
stateChanges: Array<FunctionalComponentStateChange | ClassComponentStateChange>;
contextChanges: Array<ContextChange>;
};
export type ChangesListener = (changes: ChangesPayload) => void;
export const Store: StoreType = {
wasDetailsOpen: signal(true),
isInIframe: signal(IS_CLIENT && window.self !== window.top),
inspectState: signal<States>({
kind: "uninitialized",
}),
fiberRoots: new Set<Fiber>(),
reportData: new Map<number, RenderData>(),
legacyReportData: new Map<string, RenderData>(),
lastReportTime: signal(0),
interactionListeningForRenders: null,
changesListeners: new Map(),
};
export const ReactScanInternals: Internals = {
instrumentation: null,
componentAllowList: null,
options: signal({
enabled: true,
log: false,
showToolbar: true,
animationSpeed: "fast",
dangerouslyForceRunInProduction: false,
showFPS: true,
showNotificationCount: true,
allowInIframe: false,
}),
runInAllEnvironments: false,
onRender: null,
Store,
version: packageJson.version,
};
if (IS_CLIENT && window.__REACT_SCAN_EXTENSION__) {
window.__REACT_SCAN_VERSION__ = ReactScanInternals.version;
}
export type LocalStorageOptions = Omit<Options, "onCommitStart" | "onRender" | "onCommitFinish">;
const applyLocalStorageOptions = (options: Options): LocalStorageOptions => {
const { onCommitStart, onRender, onCommitFinish, ...rest } = options;
return rest;
};
const validateOptions = (options: Partial<Options>): Partial<Options> => {
const errors: Array<string> = [];
const validOptions: Partial<Options> = {};
for (const key in options) {
const value = options[key as keyof Options];
switch (key) {
case "enabled":
case "log":
case "showToolbar":
case "showNotificationCount":
case "dangerouslyForceRunInProduction":
case "showFPS":
case "allowInIframe":
case "useOffscreenCanvasWorker":
if (typeof value !== "boolean") {
errors.push(`- ${key} must be a boolean. Got "${value}"`);
} else {
validOptions[key] = value;
}
break;
case "animationSpeed":
if (!["slow", "fast", "off"].includes(value as string)) {
errors.push(`- Invalid animation speed "${value}". Using default "fast"`);
} else {
validOptions[key] = value as "slow" | "fast" | "off";
}
break;
case "safeArea": {
const parsed = parseSafeAreaOption(value);
if (parsed.ok) {
validOptions.safeArea = parsed.value;
} else {
errors.push(parsed.error);
}
break;
}
case "onCommitStart":
if (typeof value !== "function") {
errors.push(`- ${key} must be a function. Got "${value}"`);
} else {
validOptions.onCommitStart = value as () => void;
}
break;
case "onCommitFinish":
if (typeof value !== "function") {
errors.push(`- ${key} must be a function. Got "${value}"`);
} else {
validOptions.onCommitFinish = value as () => void;
}
break;
case "onRender":
if (typeof value !== "function") {
errors.push(`- ${key} must be a function. Got "${value}"`);
} else {
validOptions.onRender = value as (fiber: Fiber, renders: Array<Render>) => void;
}
break;
default:
errors.push(`- Unknown option "${key}"`);
}
}
if (errors.length > 0) {
// oxlint-disable-next-line no-console
console.warn(`[React Scan] Invalid options:\n${errors.join("\n")}`);
}
return validOptions;
};
export const getReport = (type?: ComponentType<unknown>) => {
if (type) {
for (const reportData of Array.from(Store.legacyReportData.values())) {
if (reportData.type === type) {
return reportData;
}
}
return null;
}
return Store.legacyReportData;
};
export const setOptions = (userOptions: Partial<Options>) => {
try {
const validOptions = validateOptions(userOptions);
if (Object.keys(validOptions).length === 0) {
return;
}
const shouldInitToolbar =
"showToolbar" in validOptions && validOptions.showToolbar !== undefined;
const newOptions = {
...ReactScanInternals.options.value,
...validOptions,
};
const { instrumentation } = ReactScanInternals;
if (instrumentation && "enabled" in validOptions) {
instrumentation.isPaused.value = validOptions.enabled === false;
}
ReactScanInternals.options.value = newOptions;
// temp hack since defaults override stored local storage values
// we actually don't care about any other local storage option other than enabled, we should not be syncing those to local storage
try {
const existing = readLocalStorage<undefined | Record<string, unknown>>(
"react-scan-options",
)?.enabled;
if (typeof existing === "boolean") {
newOptions.enabled = existing;
}
} catch (e) {
if (ReactScanInternals.options.value._debug === "verbose") {
// oxlint-disable-next-line no-console
console.error(
"[React Scan Internal Error]",
"Failed to create notifications outline canvas",
e,
);
}
/** */
}
saveLocalStorage<LocalStorageOptions>(
"react-scan-options",
applyLocalStorageOptions(newOptions),
);
if (shouldInitToolbar) {
initToolbar(!!newOptions.showToolbar);
}
return newOptions;
} catch (e) {
if (ReactScanInternals.options.value._debug === "verbose") {
// oxlint-disable-next-line no-console
console.error(
"[React Scan Internal Error]",
"Failed to create notifications outline canvas",
e,
);
}
/** */
}
};
export const getOptions = () => ReactScanInternals.options;
let isProduction: boolean | null = null;
let rdtHook: ReturnType<typeof getRDTHook>;
export const getIsProduction = () => {
// Once we've definitively seen a non-production renderer, the app is "dev"
// forever — cache that and short-circuit. We deliberately do NOT cache the
// `true` result: tools like the Next.js dev overlay register a production
// React renderer alongside the user's dev React, and the dev renderer may
// arrive on a later tick. Caching `true` would lock out that flip.
if (isProduction === false) {
return false;
}
rdtHook ??= getRDTHook();
const renderers = Array.from(rdtHook.renderers.values());
if (renderers.length === 0) {
return null;
}
for (const renderer of renderers) {
const buildType = detectReactBuildType(renderer);
if (buildType !== "production") {
isProduction = false;
return false;
}
}
return true;
};
export const start = () => {
try {
if (!IS_CLIENT) {
return;
}
if (
!ReactScanInternals.runInAllEnvironments &&
getIsProduction() &&
!ReactScanInternals.options.value.dangerouslyForceRunInProduction
) {
return;
}
checkReactGrabVersion();
const localStorageOptions = readLocalStorage<LocalStorageOptions>("react-scan-options");
if (localStorageOptions) {
const validLocalOptions = validateOptions(localStorageOptions);
if (Object.keys(validLocalOptions).length > 0) {
ReactScanInternals.options.value = {
...ReactScanInternals.options.value,
...validLocalOptions,
};
}
}
const options = getOptions();
initReactScanInstrumentation(() => {
initToolbar(!!options.value.showToolbar);
});
if (IS_CLIENT) {
setTimeout(() => {
if (isInstrumentationActive()) return;
// oxlint-disable-next-line no-console
console.error("[React Scan] Failed to load. Must import React Scan before React runs.");
}, 5000);
}
} catch (e) {
if (ReactScanInternals.options.value._debug === "verbose") {
// oxlint-disable-next-line no-console
console.error(
"[React Scan Internal Error]",
"Failed to create notifications outline canvas",
e,
);
}
}
};
const initToolbar = (showToolbar: boolean) => {
window.reactScanCleanupListeners?.();
const cleanupTimingTracking = startTimingTracking();
const cleanupOutlineCanvas = createNotificationsOutlineCanvas();
window.reactScanCleanupListeners = () => {
cleanupTimingTracking();
cleanupOutlineCanvas?.();
};
const windowToolbarContainer = window.__REACT_SCAN_TOOLBAR_CONTAINER__;
if (!showToolbar) {
windowToolbarContainer?.remove();
return;
}
windowToolbarContainer?.remove();
const { shadowRoot } = initRootContainer();
createToolbar(shadowRoot);
};
const createNotificationsOutlineCanvas = () => {
try {
const highlightRoot = document.documentElement;
return createHighlightCanvas(highlightRoot);
} catch (e) {
if (ReactScanInternals.options.value._debug === "verbose") {
// oxlint-disable-next-line no-console
console.error(
"[React Scan Internal Error]",
"Failed to create notifications outline canvas",
e,
);
}
}
};
export const scan = (options: Options = {}) => {
setOptions(options);
const isInIframe = Store.isInIframe.value;
if (
isInIframe &&
!ReactScanInternals.options.value.allowInIframe &&
!ReactScanInternals.runInAllEnvironments
) {
return;
}
if (options.enabled === false && options.showToolbar !== true) {
return;
}
start();
};
export const useScan = (options: Options = {}) => {
setOptions(options);
start();
};
export const onRender = (
type: unknown,
_onRender: (fiber: Fiber, renders: Array<Render>) => void,
) => {
const prevOnRender = ReactScanInternals.onRender;
ReactScanInternals.onRender = (fiber, renders) => {
prevOnRender?.(fiber, renders);
if (getType(fiber.type) === type) {
_onRender(fiber, renders);
}
};
};
export const ignoredProps = new WeakSet<
Exclude<ReactNode, undefined | null | string | number | boolean | bigint>
>();
export const ignoreScan = (node: ReactNode) => {
if (node && typeof node === "object") {
ignoredProps.add(node);
}
};