Skip to content
74 changes: 74 additions & 0 deletions packages/scan/src/core/get-is-production.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

interface FakeRenderer {
bundleType?: number;
rendererPackageName?: string;
}

interface FakeRDTHook {
renderers: Map<number, FakeRenderer>;
}

const sharedHook: FakeRDTHook = { renderers: new Map() };

vi.mock('bippy', () => {
return {
detectReactBuildType: (renderer: FakeRenderer) =>
renderer.bundleType === 0 ? 'production' : 'development',
getRDTHook: () => sharedHook,
getType: () => null,
isInstrumentationActive: () => false,
};
});

const importFreshGetIsProduction = async () => {
vi.resetModules();
const mod = (await import('~core/index')) as typeof import('~core/index');
return mod.getIsProduction;
};

beforeEach(() => {
sharedHook.renderers.clear();
});

describe('getIsProduction', () => {
it('returns null when no React renderer has registered yet', async () => {
const getIsProduction = await importFreshGetIsProduction();
expect(getIsProduction()).toBeNull();
});

it('returns true when every registered renderer is production', async () => {
const getIsProduction = await importFreshGetIsProduction();
sharedHook.renderers.set(1, { bundleType: 0 });
expect(getIsProduction()).toBe(true);
});

it('returns false when at least one renderer is non-production', async () => {
const getIsProduction = await importFreshGetIsProduction();
sharedHook.renderers.set(1, { bundleType: 0 });
sharedHook.renderers.set(2, { bundleType: 1 });
expect(getIsProduction()).toBe(false);
});

it('does not cache `true` — a later dev renderer flips the result', async () => {
// Regression guard for #402: the Next.js dev overlay registers a
// production React build first, then the user's dev React arrives a
// tick later. Caching `true` on the first call would lock us out.
const getIsProduction = await importFreshGetIsProduction();
sharedHook.renderers.set(1, { bundleType: 0 });
expect(getIsProduction()).toBe(true);

sharedHook.renderers.set(2, { bundleType: 1 });
expect(getIsProduction()).toBe(false);
});

it('caches `false` permanently once a dev renderer has been seen', async () => {
const getIsProduction = await importFreshGetIsProduction();
sharedHook.renderers.set(1, { bundleType: 1 });
expect(getIsProduction()).toBe(false);

sharedHook.renderers.clear();
sharedHook.renderers.set(2, { bundleType: 0 });
expect(getIsProduction()).toBe(false);
});
});
61 changes: 54 additions & 7 deletions packages/scan/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import styles from '~web/assets/css/styles.css';
import { createToolbar } from '~web/toolbar';
import { IS_CLIENT } from '~web/utils/constants';
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,
Expand Down Expand Up @@ -126,6 +127,33 @@ export interface Options {
*/
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.
*
Expand Down Expand Up @@ -277,6 +305,7 @@ const validateOptions = (options: Partial<Options>): Partial<Options> => {
case 'dangerouslyForceRunInProduction':
case 'showFPS':
case 'allowInIframe':
case 'useOffscreenCanvasWorker':
if (typeof value !== 'boolean') {
errors.push(`- ${key} must be a boolean. Got "${value}"`);
} else {
Expand All @@ -292,6 +321,15 @@ const validateOptions = (options: Partial<Options>): Partial<Options> => {
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}"`);
Expand Down Expand Up @@ -411,21 +449,30 @@ export const setOptions = (userOptions: Partial<Options>) => {

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

// we only need to run this check once and will read the value in hot path
let isProduction: boolean | null = null;
let rdtHook: ReturnType<typeof getRDTHook>;
export const getIsProduction = () => {
if (isProduction !== null) {
return isProduction;
// 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();
for (const renderer of rdtHook.renderers.values()) {
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 = true;
if (buildType !== 'production') {
isProduction = false;
return false;
}
}
return isProduction;
return true;
};

export const start = () => {
Expand Down
33 changes: 24 additions & 9 deletions packages/scan/src/new-outlines/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,19 +321,24 @@ export const getCanvasEl = () => {
canvasEl.width = width;
canvasEl.height = height;

// Users on a strict CSP without `worker-src blob:` (see #372) can opt out;
// we still render outlines on the main thread via `initCanvas` below.
const workerOptOut =
ReactScanInternals.options.value.useOffscreenCanvasWorker === false;

if (
IS_OFFSCREEN_CANVAS_WORKER_SUPPORTED &&
!window.__REACT_SCAN_EXTENSION__
!window.__REACT_SCAN_EXTENSION__ &&
!workerOptOut
) {
try {
worker = new Worker(
URL.createObjectURL(
new Blob([workerCode], { type: 'application/javascript' }),
),
const blobUrl = URL.createObjectURL(
new Blob([workerCode], { type: 'application/javascript' }),
);
worker = new Worker(blobUrl);

const offscreenCanvas = canvasEl.transferControlToOffscreen();
worker?.postMessage(
worker.postMessage(
{
type: 'init',
canvas: offscreenCanvas,
Expand All @@ -343,10 +348,20 @@ export const getCanvasEl = () => {
},
[offscreenCanvas],
);
} catch (e) {
// oxlint-disable-next-line no-console
console.warn('Failed to initialize OffscreenCanvas worker:', e);
} catch (error) {
// The common failure here is a strict CSP rejecting `blob:` workers.
// The fallback below renders fine on the main thread, so log only when
// the user explicitly asked for verbose diagnostics.
worker = null;
if (ReactScanInternals.options.value._debug === 'verbose') {
// oxlint-disable-next-line no-console
console.warn('Failed to initialize OffscreenCanvas worker:', error);
}
}
// The blob URL stays alive until the worker is GC'd. Revoking
// synchronously after `new Worker(url)` has historically broken some
// browser versions before the worker actually fetched the URL — leave
// the (single, tiny) URL in place rather than risking that race.
}

if (!worker) {
Expand Down
11 changes: 11 additions & 0 deletions packages/scan/src/web/assets/css/styles.tailwind.css
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ svg {
backface-visibility: hidden;
}

/* The toolbar uses select-none for drag UX, so re-enable text selection on
* content elements (e.g. AI prompt <pre>, search inputs). See #415. */
#react-scan-toolbar pre,
#react-scan-toolbar textarea,
#react-scan-toolbar input[type='text'],
#react-scan-toolbar input[type='search'],
#react-scan-toolbar [data-react-scan-selectable] {
@apply select-text;
cursor: text;
}

.button {
&:hover {
background: rgba(255, 255, 255, 0.1);
Expand Down
6 changes: 6 additions & 0 deletions packages/scan/src/web/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@ export const MIN_CONTAINER_WIDTH = 240;
export const LOCALSTORAGE_KEY = "react-scan-widget-settings-v2";
export const LOCALSTORAGE_COLLAPSED_KEY = "react-scan-widget-collapsed-v1";
export const LOCALSTORAGE_LAST_VIEW_KEY = "react-scan-widget-last-view-v1";

// CSS selector for elements inside #react-scan-toolbar that should NOT
// trigger drag and SHOULD allow native text selection / focus (#415).
// Keep in sync with the matching CSS rule in styles.tailwind.css.
export const TOOLBAR_INTERACTIVE_SELECTOR =
"button, a, input, textarea, select, pre, [contenteditable], [data-react-scan-selectable]";
38 changes: 24 additions & 14 deletions packages/scan/src/web/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "./constants";
import { IS_CLIENT } from "./utils/constants";
import { readLocalStorage, saveLocalStorage } from "./utils/helpers";
import { getSafeArea } from "./utils/safe-area";
import type { Corner, WidgetConfig, WidgetSettings } from "./widget/types";
import type { CollapsedPosition } from "./widget/types";

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

export const defaultWidgetConfig = {
corner: "bottom-right" as Corner,
// Use the raw SAFE_AREA constant (not getSafeArea()) here: this runs at
// module-init time, before any user has called scan() with options.
export const getDefaultWidgetConfig = (): WidgetConfig => ({
corner: "bottom-right" satisfies Corner,
dimensions: {
isFullWidth: false,
isFullHeight: false,
Expand All @@ -35,30 +38,36 @@ export const defaultWidgetConfig = {
componentsTree: {
width: MIN_CONTAINER_WIDTH,
},
} as WidgetConfig;
});

// Deprecated alias kept for one minor version to avoid breaking downstream
// imports of the pre-refactor `defaultWidgetConfig` const.
/** @deprecated use {@link getDefaultWidgetConfig} */
export const defaultWidgetConfig: WidgetConfig = getDefaultWidgetConfig();

export const getInitialWidgetConfig = (): WidgetConfig => {
const defaults = getDefaultWidgetConfig();
const stored = readLocalStorage<WidgetSettings>(LOCALSTORAGE_KEY);
if (!stored) {
saveLocalStorage(LOCALSTORAGE_KEY, {
corner: defaultWidgetConfig.corner,
dimensions: defaultWidgetConfig.dimensions,
lastDimensions: defaultWidgetConfig.lastDimensions,
componentsTree: defaultWidgetConfig.componentsTree,
corner: defaults.corner,
dimensions: defaults.dimensions,
lastDimensions: defaults.lastDimensions,
componentsTree: defaults.componentsTree,
});

return defaultWidgetConfig;
return defaults;
}

return {
corner: stored.corner ?? defaultWidgetConfig.corner,
dimensions: stored.dimensions ?? defaultWidgetConfig.dimensions,
corner: stored.corner ?? defaults.corner,
dimensions: stored.dimensions ?? defaults.dimensions,

lastDimensions:
stored.lastDimensions ??
stored.dimensions ??
defaultWidgetConfig.lastDimensions,
componentsTree: stored.componentsTree ?? defaultWidgetConfig.componentsTree,
defaults.lastDimensions,
componentsTree: stored.componentsTree ?? defaults.componentsTree,
};
};

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

const { dimensions } = signalWidget.value;
const { width, height, position } = dimensions;
const safeArea = getSafeArea();

signalWidget.value = {
...signalWidget.value,
dimensions: {
isFullWidth: width >= window.innerWidth - SAFE_AREA * 2,
isFullHeight: height >= window.innerHeight - SAFE_AREA * 2,
isFullWidth: width >= window.innerWidth - safeArea.left - safeArea.right,
isFullHeight: height >= window.innerHeight - safeArea.top - safeArea.bottom,
width,
height,
position,
Expand Down
2 changes: 2 additions & 0 deletions packages/scan/src/web/utils/is-finite-positive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const isFinitePositive = (value: unknown): value is number =>
typeof value === 'number' && Number.isFinite(value) && value >= 0;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
4 changes: 4 additions & 0 deletions packages/scan/src/web/utils/is-plain-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const isPlainObject = (
value: unknown,
): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value);
Loading
Loading