Skip to content

Commit 5fb67cc

Browse files
authored
fix(scan): triage sweep across open issues (aidenybai#437)
1 parent 7a7ac59 commit 5fb67cc

15 files changed

Lines changed: 456 additions & 94 deletions
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest';
2+
3+
interface FakeRenderer {
4+
bundleType?: number;
5+
rendererPackageName?: string;
6+
}
7+
8+
interface FakeRDTHook {
9+
renderers: Map<number, FakeRenderer>;
10+
}
11+
12+
const sharedHook: FakeRDTHook = { renderers: new Map() };
13+
14+
vi.mock('bippy', () => {
15+
return {
16+
detectReactBuildType: (renderer: FakeRenderer) =>
17+
renderer.bundleType === 0 ? 'production' : 'development',
18+
getRDTHook: () => sharedHook,
19+
getType: () => null,
20+
isInstrumentationActive: () => false,
21+
};
22+
});
23+
24+
const importFreshGetIsProduction = async () => {
25+
vi.resetModules();
26+
const mod = (await import('~core/index')) as typeof import('~core/index');
27+
return mod.getIsProduction;
28+
};
29+
30+
beforeEach(() => {
31+
sharedHook.renderers.clear();
32+
});
33+
34+
describe('getIsProduction', () => {
35+
it('returns null when no React renderer has registered yet', async () => {
36+
const getIsProduction = await importFreshGetIsProduction();
37+
expect(getIsProduction()).toBeNull();
38+
});
39+
40+
it('returns true when every registered renderer is production', async () => {
41+
const getIsProduction = await importFreshGetIsProduction();
42+
sharedHook.renderers.set(1, { bundleType: 0 });
43+
expect(getIsProduction()).toBe(true);
44+
});
45+
46+
it('returns false when at least one renderer is non-production', async () => {
47+
const getIsProduction = await importFreshGetIsProduction();
48+
sharedHook.renderers.set(1, { bundleType: 0 });
49+
sharedHook.renderers.set(2, { bundleType: 1 });
50+
expect(getIsProduction()).toBe(false);
51+
});
52+
53+
it('does not cache `true` — a later dev renderer flips the result', async () => {
54+
// Regression guard for #402: the Next.js dev overlay registers a
55+
// production React build first, then the user's dev React arrives a
56+
// tick later. Caching `true` on the first call would lock us out.
57+
const getIsProduction = await importFreshGetIsProduction();
58+
sharedHook.renderers.set(1, { bundleType: 0 });
59+
expect(getIsProduction()).toBe(true);
60+
61+
sharedHook.renderers.set(2, { bundleType: 1 });
62+
expect(getIsProduction()).toBe(false);
63+
});
64+
65+
it('caches `false` permanently once a dev renderer has been seen', async () => {
66+
const getIsProduction = await importFreshGetIsProduction();
67+
sharedHook.renderers.set(1, { bundleType: 1 });
68+
expect(getIsProduction()).toBe(false);
69+
70+
sharedHook.renderers.clear();
71+
sharedHook.renderers.set(2, { bundleType: 0 });
72+
expect(getIsProduction()).toBe(false);
73+
});
74+
});

‎packages/scan/src/core/index.ts‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import styles from '~web/assets/css/styles.css';
1414
import { createToolbar } from '~web/toolbar';
1515
import { IS_CLIENT } from '~web/utils/constants';
1616
import { readLocalStorage, saveLocalStorage } from '~web/utils/helpers';
17+
import { parseSafeAreaOption } from '~web/utils/parse-safe-area-option';
1718
import type { States } from '~web/views/inspector/utils';
1819
import type {
1920
ChangeReason,
@@ -126,6 +127,33 @@ export interface Options {
126127
*/
127128
allowInIframe?: boolean;
128129

130+
/**
131+
* Distance (in pixels) the toolbar keeps from the viewport edges. Useful
132+
* when other dev overlays (e.g. the Next.js dev indicator) sit in the same
133+
* corner. Pass a single number to inset all edges, or an object to inset
134+
* edges individually.
135+
*
136+
* @default 24
137+
*/
138+
safeArea?:
139+
| number
140+
| {
141+
top?: number;
142+
right?: number;
143+
bottom?: number;
144+
left?: number;
145+
};
146+
147+
/**
148+
* Render outline overlays via an OffscreenCanvas + Web Worker. Disable when
149+
* a strict Content-Security-Policy without `worker-src blob:` would
150+
* otherwise reject the blob worker — React Scan automatically falls back
151+
* to main-thread rendering.
152+
*
153+
* @default true
154+
*/
155+
useOffscreenCanvasWorker?: boolean;
156+
129157
/**
130158
* Should react scan log internal errors to the console.
131159
*
@@ -277,6 +305,7 @@ const validateOptions = (options: Partial<Options>): Partial<Options> => {
277305
case 'dangerouslyForceRunInProduction':
278306
case 'showFPS':
279307
case 'allowInIframe':
308+
case 'useOffscreenCanvasWorker':
280309
if (typeof value !== 'boolean') {
281310
errors.push(`- ${key} must be a boolean. Got "${value}"`);
282311
} else {
@@ -292,6 +321,15 @@ const validateOptions = (options: Partial<Options>): Partial<Options> => {
292321
validOptions[key] = value as 'slow' | 'fast' | 'off';
293322
}
294323
break;
324+
case 'safeArea': {
325+
const parsed = parseSafeAreaOption(value);
326+
if (parsed.ok) {
327+
validOptions.safeArea = parsed.value;
328+
} else {
329+
errors.push(parsed.error);
330+
}
331+
break;
332+
}
295333
case 'onCommitStart':
296334
if (typeof value !== 'function') {
297335
errors.push(`- ${key} must be a function. Got "${value}"`);
@@ -411,21 +449,30 @@ export const setOptions = (userOptions: Partial<Options>) => {
411449

412450
export const getOptions = () => ReactScanInternals.options;
413451

414-
// we only need to run this check once and will read the value in hot path
415452
let isProduction: boolean | null = null;
416453
let rdtHook: ReturnType<typeof getRDTHook>;
417454
export const getIsProduction = () => {
418-
if (isProduction !== null) {
419-
return isProduction;
455+
// Once we've definitively seen a non-production renderer, the app is "dev"
456+
// forever — cache that and short-circuit. We deliberately do NOT cache the
457+
// `true` result: tools like the Next.js dev overlay register a production
458+
// React renderer alongside the user's dev React, and the dev renderer may
459+
// arrive on a later tick. Caching `true` would lock out that flip.
460+
if (isProduction === false) {
461+
return false;
420462
}
421463
rdtHook ??= getRDTHook();
422-
for (const renderer of rdtHook.renderers.values()) {
464+
const renderers = Array.from(rdtHook.renderers.values());
465+
if (renderers.length === 0) {
466+
return null;
467+
}
468+
for (const renderer of renderers) {
423469
const buildType = detectReactBuildType(renderer);
424-
if (buildType === 'production') {
425-
isProduction = true;
470+
if (buildType !== 'production') {
471+
isProduction = false;
472+
return false;
426473
}
427474
}
428-
return isProduction;
475+
return true;
429476
};
430477

431478
export const start = () => {

‎packages/scan/src/new-outlines/index.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -321,19 +321,24 @@ export const getCanvasEl = () => {
321321
canvasEl.width = width;
322322
canvasEl.height = height;
323323

324+
// Users on a strict CSP without `worker-src blob:` (see #372) can opt out;
325+
// we still render outlines on the main thread via `initCanvas` below.
326+
const workerOptOut =
327+
ReactScanInternals.options.value.useOffscreenCanvasWorker === false;
328+
324329
if (
325330
IS_OFFSCREEN_CANVAS_WORKER_SUPPORTED &&
326-
!window.__REACT_SCAN_EXTENSION__
331+
!window.__REACT_SCAN_EXTENSION__ &&
332+
!workerOptOut
327333
) {
328334
try {
329-
worker = new Worker(
330-
URL.createObjectURL(
331-
new Blob([workerCode], { type: 'application/javascript' }),
332-
),
335+
const blobUrl = URL.createObjectURL(
336+
new Blob([workerCode], { type: 'application/javascript' }),
333337
);
338+
worker = new Worker(blobUrl);
334339

335340
const offscreenCanvas = canvasEl.transferControlToOffscreen();
336-
worker?.postMessage(
341+
worker.postMessage(
337342
{
338343
type: 'init',
339344
canvas: offscreenCanvas,
@@ -343,10 +348,20 @@ export const getCanvasEl = () => {
343348
},
344349
[offscreenCanvas],
345350
);
346-
} catch (e) {
347-
// oxlint-disable-next-line no-console
348-
console.warn('Failed to initialize OffscreenCanvas worker:', e);
351+
} catch (error) {
352+
// The common failure here is a strict CSP rejecting `blob:` workers.
353+
// The fallback below renders fine on the main thread, so log only when
354+
// the user explicitly asked for verbose diagnostics.
355+
worker = null;
356+
if (ReactScanInternals.options.value._debug === 'verbose') {
357+
// oxlint-disable-next-line no-console
358+
console.warn('Failed to initialize OffscreenCanvas worker:', error);
359+
}
349360
}
361+
// The blob URL stays alive until the worker is GC'd. Revoking
362+
// synchronously after `new Worker(url)` has historically broken some
363+
// browser versions before the worker actually fetched the URL — leave
364+
// the (single, tiny) URL in place rather than risking that race.
350365
}
351366

352367
if (!worker) {

‎packages/scan/src/web/assets/css/styles.tailwind.css‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,17 @@ svg {
107107
backface-visibility: hidden;
108108
}
109109

110+
/* The toolbar uses select-none for drag UX, so re-enable text selection on
111+
* content elements (e.g. AI prompt <pre>, search inputs). See #415. */
112+
#react-scan-toolbar pre,
113+
#react-scan-toolbar textarea,
114+
#react-scan-toolbar input[type='text'],
115+
#react-scan-toolbar input[type='search'],
116+
#react-scan-toolbar [data-react-scan-selectable] {
117+
@apply select-text;
118+
cursor: text;
119+
}
120+
110121
.button {
111122
&:hover {
112123
background: rgba(255, 255, 255, 0.1);

‎packages/scan/src/web/constants.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,9 @@ export const MIN_CONTAINER_WIDTH = 240;
1010
export const LOCALSTORAGE_KEY = "react-scan-widget-settings-v2";
1111
export const LOCALSTORAGE_COLLAPSED_KEY = "react-scan-widget-collapsed-v1";
1212
export const LOCALSTORAGE_LAST_VIEW_KEY = "react-scan-widget-last-view-v1";
13+
14+
// CSS selector for elements inside #react-scan-toolbar that should NOT
15+
// trigger drag and SHOULD allow native text selection / focus (#415).
16+
// Keep in sync with the matching CSS rule in styles.tailwind.css.
17+
export const TOOLBAR_INTERACTIVE_SELECTOR =
18+
"button, a, input, textarea, select, pre, [contenteditable], [data-react-scan-selectable]";

‎packages/scan/src/web/state.ts‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "./constants";
99
import { IS_CLIENT } from "./utils/constants";
1010
import { readLocalStorage, saveLocalStorage } from "./utils/helpers";
11+
import { getSafeArea } from "./utils/safe-area";
1112
import type { Corner, WidgetConfig, WidgetSettings } from "./widget/types";
1213
import type { CollapsedPosition } from "./widget/types";
1314

@@ -16,8 +17,10 @@ export const signalRefWidget = /* @__PURE__ */ signal<HTMLDivElement | null>(
1617
null
1718
);
1819

19-
export const defaultWidgetConfig = {
20-
corner: "bottom-right" as Corner,
20+
// Use the raw SAFE_AREA constant (not getSafeArea()) here: this runs at
21+
// module-init time, before any user has called scan() with options.
22+
export const getDefaultWidgetConfig = (): WidgetConfig => ({
23+
corner: "bottom-right" satisfies Corner,
2124
dimensions: {
2225
isFullWidth: false,
2326
isFullHeight: false,
@@ -35,30 +38,36 @@ export const defaultWidgetConfig = {
3538
componentsTree: {
3639
width: MIN_CONTAINER_WIDTH,
3740
},
38-
} as WidgetConfig;
41+
});
42+
43+
// Deprecated alias kept for one minor version to avoid breaking downstream
44+
// imports of the pre-refactor `defaultWidgetConfig` const.
45+
/** @deprecated use {@link getDefaultWidgetConfig} */
46+
export const defaultWidgetConfig: WidgetConfig = getDefaultWidgetConfig();
3947

4048
export const getInitialWidgetConfig = (): WidgetConfig => {
49+
const defaults = getDefaultWidgetConfig();
4150
const stored = readLocalStorage<WidgetSettings>(LOCALSTORAGE_KEY);
4251
if (!stored) {
4352
saveLocalStorage(LOCALSTORAGE_KEY, {
44-
corner: defaultWidgetConfig.corner,
45-
dimensions: defaultWidgetConfig.dimensions,
46-
lastDimensions: defaultWidgetConfig.lastDimensions,
47-
componentsTree: defaultWidgetConfig.componentsTree,
53+
corner: defaults.corner,
54+
dimensions: defaults.dimensions,
55+
lastDimensions: defaults.lastDimensions,
56+
componentsTree: defaults.componentsTree,
4857
});
4958

50-
return defaultWidgetConfig;
59+
return defaults;
5160
}
5261

5362
return {
54-
corner: stored.corner ?? defaultWidgetConfig.corner,
55-
dimensions: stored.dimensions ?? defaultWidgetConfig.dimensions,
63+
corner: stored.corner ?? defaults.corner,
64+
dimensions: stored.dimensions ?? defaults.dimensions,
5665

5766
lastDimensions:
5867
stored.lastDimensions ??
5968
stored.dimensions ??
60-
defaultWidgetConfig.lastDimensions,
61-
componentsTree: stored.componentsTree ?? defaultWidgetConfig.componentsTree,
69+
defaults.lastDimensions,
70+
componentsTree: stored.componentsTree ?? defaults.componentsTree,
6271
};
6372
};
6473

@@ -69,12 +78,13 @@ export const updateDimensions = (): void => {
6978

7079
const { dimensions } = signalWidget.value;
7180
const { width, height, position } = dimensions;
81+
const safeArea = getSafeArea();
7282

7383
signalWidget.value = {
7484
...signalWidget.value,
7585
dimensions: {
76-
isFullWidth: width >= window.innerWidth - SAFE_AREA * 2,
77-
isFullHeight: height >= window.innerHeight - SAFE_AREA * 2,
86+
isFullWidth: width >= window.innerWidth - safeArea.left - safeArea.right,
87+
isFullHeight: height >= window.innerHeight - safeArea.top - safeArea.bottom,
7888
width,
7989
height,
8090
position,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const isFiniteNonNegative = (value: unknown): value is number =>
2+
typeof value === 'number' && Number.isFinite(value) && value >= 0;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export const isPlainObject = (
2+
value: unknown,
3+
): value is Record<string, unknown> =>
4+
Boolean(value) && typeof value === 'object' && !Array.isArray(value);

0 commit comments

Comments
 (0)