diff --git a/packages/scan/src/core/get-is-production.test.ts b/packages/scan/src/core/get-is-production.test.ts new file mode 100644 index 00000000..d56971e0 --- /dev/null +++ b/packages/scan/src/core/get-is-production.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +interface FakeRenderer { + bundleType?: number; + rendererPackageName?: string; +} + +interface FakeRDTHook { + renderers: Map; +} + +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); + }); +}); diff --git a/packages/scan/src/core/index.ts b/packages/scan/src/core/index.ts index 1a07399e..d4b75b00 100644 --- a/packages/scan/src/core/index.ts +++ b/packages/scan/src/core/index.ts @@ -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, @@ -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. * @@ -277,6 +305,7 @@ const validateOptions = (options: Partial): Partial => { case 'dangerouslyForceRunInProduction': case 'showFPS': case 'allowInIframe': + case 'useOffscreenCanvasWorker': if (typeof value !== 'boolean') { errors.push(`- ${key} must be a boolean. Got "${value}"`); } else { @@ -292,6 +321,15 @@ const validateOptions = (options: Partial): Partial => { 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}"`); @@ -411,21 +449,30 @@ export const setOptions = (userOptions: Partial) => { 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; 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 = () => { diff --git a/packages/scan/src/new-outlines/index.ts b/packages/scan/src/new-outlines/index.ts index d4facd29..6d1e1630 100644 --- a/packages/scan/src/new-outlines/index.ts +++ b/packages/scan/src/new-outlines/index.ts @@ -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, @@ -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) { diff --git a/packages/scan/src/web/assets/css/styles.tailwind.css b/packages/scan/src/web/assets/css/styles.tailwind.css index 992e5491..e21830e4 100644 --- a/packages/scan/src/web/assets/css/styles.tailwind.css +++ b/packages/scan/src/web/assets/css/styles.tailwind.css @@ -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
, 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);
diff --git a/packages/scan/src/web/constants.ts b/packages/scan/src/web/constants.ts
index 3b7b8bcc..580e3819 100644
--- a/packages/scan/src/web/constants.ts
+++ b/packages/scan/src/web/constants.ts
@@ -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]";
diff --git a/packages/scan/src/web/state.ts b/packages/scan/src/web/state.ts
index 4d1a197c..c7feb5ea 100644
--- a/packages/scan/src/web/state.ts
+++ b/packages/scan/src/web/state.ts
@@ -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";
 
@@ -16,8 +17,10 @@ export const signalRefWidget = /* @__PURE__ */ signal(
   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,
@@ -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(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,
   };
 };
 
@@ -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,
diff --git a/packages/scan/src/web/utils/is-finite-non-negative.ts b/packages/scan/src/web/utils/is-finite-non-negative.ts
new file mode 100644
index 00000000..17fbd8f2
--- /dev/null
+++ b/packages/scan/src/web/utils/is-finite-non-negative.ts
@@ -0,0 +1,2 @@
+export const isFiniteNonNegative = (value: unknown): value is number =>
+  typeof value === 'number' && Number.isFinite(value) && value >= 0;
diff --git a/packages/scan/src/web/utils/is-plain-object.ts b/packages/scan/src/web/utils/is-plain-object.ts
new file mode 100644
index 00000000..2558f466
--- /dev/null
+++ b/packages/scan/src/web/utils/is-plain-object.ts
@@ -0,0 +1,4 @@
+export const isPlainObject = (
+  value: unknown,
+): value is Record =>
+  Boolean(value) && typeof value === 'object' && !Array.isArray(value);
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.test.ts b/packages/scan/src/web/utils/parse-safe-area-option.test.ts
new file mode 100644
index 00000000..0fa1d9e4
--- /dev/null
+++ b/packages/scan/src/web/utils/parse-safe-area-option.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+import { parseSafeAreaOption } from '~web/utils/parse-safe-area-option';
+
+describe('parseSafeAreaOption', () => {
+  it('accepts a non-negative finite number', () => {
+    expect(parseSafeAreaOption(0)).toEqual({ ok: true, value: 0 });
+    expect(parseSafeAreaOption(24)).toEqual({ ok: true, value: 24 });
+    expect(parseSafeAreaOption(96)).toEqual({ ok: true, value: 96 });
+  });
+
+  it('rejects negative numbers', () => {
+    const result = parseSafeAreaOption(-1);
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects NaN and Infinity', () => {
+    expect(parseSafeAreaOption(Number.NaN).ok).toBe(false);
+    expect(parseSafeAreaOption(Number.POSITIVE_INFINITY).ok).toBe(false);
+    expect(parseSafeAreaOption(Number.NEGATIVE_INFINITY).ok).toBe(false);
+  });
+
+  it('accepts a partial per-edge object', () => {
+    expect(parseSafeAreaOption({ right: 96 })).toEqual({
+      ok: true,
+      value: { right: 96 },
+    });
+    expect(parseSafeAreaOption({ top: 0, bottom: 40 })).toEqual({
+      ok: true,
+      value: { top: 0, bottom: 40 },
+    });
+  });
+
+  it('accepts a full per-edge object', () => {
+    expect(
+      parseSafeAreaOption({ top: 1, right: 2, bottom: 3, left: 4 }),
+    ).toEqual({
+      ok: true,
+      value: { top: 1, right: 2, bottom: 3, left: 4 },
+    });
+  });
+
+  it('rejects per-edge object with a negative value', () => {
+    const result = parseSafeAreaOption({ right: -10 });
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects per-edge object with a non-number value', () => {
+    const result = parseSafeAreaOption({ top: '24' });
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects arrays (not plain objects)', () => {
+    const result = parseSafeAreaOption([10, 20, 30, 40]);
+    expect(result.ok).toBe(false);
+  });
+
+  it('rejects null and undefined', () => {
+    expect(parseSafeAreaOption(null).ok).toBe(false);
+    expect(parseSafeAreaOption(undefined).ok).toBe(false);
+  });
+
+  it('rejects strings', () => {
+    expect(parseSafeAreaOption('24').ok).toBe(false);
+    expect(parseSafeAreaOption('').ok).toBe(false);
+  });
+
+  it('ignores undefined edges in a per-edge object', () => {
+    expect(
+      parseSafeAreaOption({ top: 5, right: undefined }),
+    ).toEqual({ ok: true, value: { top: 5 } });
+  });
+});
diff --git a/packages/scan/src/web/utils/parse-safe-area-option.ts b/packages/scan/src/web/utils/parse-safe-area-option.ts
new file mode 100644
index 00000000..7c70810f
--- /dev/null
+++ b/packages/scan/src/web/utils/parse-safe-area-option.ts
@@ -0,0 +1,38 @@
+import type { Options } from '~core/index';
+import { isFiniteNonNegative } from '~web/utils/is-finite-non-negative';
+import { isPlainObject } from '~web/utils/is-plain-object';
+
+type SafeAreaOption = NonNullable;
+
+export type ParsedSafeAreaOption =
+  | { ok: true; value: SafeAreaOption }
+  | { ok: false; error: string };
+
+const SAFE_AREA_EDGES = ['top', 'right', 'bottom', 'left'] as const;
+
+export const parseSafeAreaOption = (value: unknown): ParsedSafeAreaOption => {
+  if (isFiniteNonNegative(value)) {
+    return { ok: true, value };
+  }
+
+  if (!isPlainObject(value)) {
+    return {
+      ok: false,
+      error: `- safeArea must be a non-negative number or { top?, right?, bottom?, left? }. Got "${JSON.stringify(value)}"`,
+    };
+  }
+
+  const inset: Partial> = {};
+  for (const edge of SAFE_AREA_EDGES) {
+    const edgeValue = value[edge];
+    if (edgeValue === undefined) continue;
+    if (!isFiniteNonNegative(edgeValue)) {
+      return {
+        ok: false,
+        error: `- safeArea.${edge} must be a non-negative number. Got "${JSON.stringify(edgeValue)}"`,
+      };
+    }
+    inset[edge] = edgeValue;
+  }
+  return { ok: true, value: inset };
+};
diff --git a/packages/scan/src/web/utils/safe-area.ts b/packages/scan/src/web/utils/safe-area.ts
new file mode 100644
index 00000000..7a33ae9f
--- /dev/null
+++ b/packages/scan/src/web/utils/safe-area.ts
@@ -0,0 +1,39 @@
+import { ReactScanInternals } from '~core/index';
+import { SAFE_AREA } from '~web/constants';
+import { isFiniteNonNegative } from '~web/utils/is-finite-non-negative';
+import { isPlainObject } from '~web/utils/is-plain-object';
+
+export interface SafeAreaInsets {
+  top: number;
+  right: number;
+  bottom: number;
+  left: number;
+}
+
+export const getSafeArea = (): SafeAreaInsets => {
+  const value = ReactScanInternals.options.value.safeArea;
+
+  if (isFiniteNonNegative(value)) {
+    return { top: value, right: value, bottom: value, left: value };
+  }
+
+  if (isPlainObject(value)) {
+    const top = value.top;
+    const right = value.right;
+    const bottom = value.bottom;
+    const left = value.left;
+    return {
+      top: isFiniteNonNegative(top) ? top : SAFE_AREA,
+      right: isFiniteNonNegative(right) ? right : SAFE_AREA,
+      bottom: isFiniteNonNegative(bottom) ? bottom : SAFE_AREA,
+      left: isFiniteNonNegative(left) ? left : SAFE_AREA,
+    };
+  }
+
+  return {
+    top: SAFE_AREA,
+    right: SAFE_AREA,
+    bottom: SAFE_AREA,
+    left: SAFE_AREA,
+  };
+};
diff --git a/packages/scan/src/web/views/notifications/optimize.tsx b/packages/scan/src/web/views/notifications/optimize.tsx
index 7b26c0bf..8be7131a 100644
--- a/packages/scan/src/web/views/notifications/optimize.tsx
+++ b/packages/scan/src/web/views/notifications/optimize.tsx
@@ -147,7 +147,7 @@ We also have lower level information about react components, such as their rende
 
 ${formattedReactData}
 
-You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation
+You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation
 
 It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So the flow should be:
 - find the most expensive components
@@ -197,7 +197,7 @@ We also have lower level information about react components, such as their rende
 
 ${formattedReactData}
 
-You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation
+You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation
 
 It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So the flow should be:
 - find the most expensive components
@@ -235,7 +235,7 @@ We also have lower level information about react components, such as their rende
 
 ${formattedReactData}
 
-You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation
+You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation
 
 It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So a flow we can go through is:
 - find the most expensive components
@@ -312,7 +312,7 @@ We also have lower level information about react components, such as their rende
 ${formattedReactData}
 
 
-You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could of been memoized to avoid computation
+You may notice components have many renders, but much fewer props/state/context changes. This normally implies most of the components could have been memoized to avoid computation
 
 It's also important to remember if a component had no props/state/context change, and it was memoized, it would not render. So a flow we can go through is:
 - find the most expensive components
diff --git a/packages/scan/src/web/widget/helpers.ts b/packages/scan/src/web/widget/helpers.ts
index e3b6589d..f0984adb 100644
--- a/packages/scan/src/web/widget/helpers.ts
+++ b/packages/scan/src/web/widget/helpers.ts
@@ -1,4 +1,5 @@
-import { MIN_SIZE, SAFE_AREA } from '../constants';
+import { MIN_SIZE } from '../constants';
+import { getSafeArea, type SafeAreaInsets } from '../utils/safe-area';
 import type { Corner, Position, ResizeHandleProps, Size } from './types';
 
 class WindowDimensions {
@@ -8,17 +9,18 @@ class WindowDimensions {
   constructor(
     public width: number,
     public height: number,
+    public safeArea: SafeAreaInsets,
   ) {
-    this.maxWidth = width - SAFE_AREA * 2;
-    this.maxHeight = height - SAFE_AREA * 2;
+    this.maxWidth = width - safeArea.left - safeArea.right;
+    this.maxHeight = height - safeArea.top - safeArea.bottom;
   }
 
   rightEdge(width: number): number {
-    return this.width - width - SAFE_AREA;
+    return this.width - width - this.safeArea.right;
   }
 
   bottomEdge(height: number): number {
-    return this.height - height - SAFE_AREA;
+    return this.height - height - this.safeArea.bottom;
   }
 
   isFullWidth(width: number): boolean {
@@ -32,19 +34,31 @@ class WindowDimensions {
 
 let cachedWindowDimensions: WindowDimensions | undefined;
 
+const safeAreaMatches = (a: SafeAreaInsets, b: SafeAreaInsets): boolean =>
+  a.top === b.top &&
+  a.right === b.right &&
+  a.bottom === b.bottom &&
+  a.left === b.left;
+
 export const getWindowDimensions = () => {
   const currentWidth = window.innerWidth;
   const currentHeight = window.innerHeight;
+  const currentSafeArea = getSafeArea();
 
   if (
     cachedWindowDimensions &&
     cachedWindowDimensions.width === currentWidth &&
-    cachedWindowDimensions.height === currentHeight
+    cachedWindowDimensions.height === currentHeight &&
+    safeAreaMatches(cachedWindowDimensions.safeArea, currentSafeArea)
   ) {
     return cachedWindowDimensions;
   }
 
-  cachedWindowDimensions = new WindowDimensions(currentWidth, currentHeight);
+  cachedWindowDimensions = new WindowDimensions(
+    currentWidth,
+    currentHeight,
+    currentSafeArea,
+  );
 
   return cachedWindowDimensions;
 };
@@ -98,6 +112,7 @@ export const calculatePosition = (
 
   const windowWidth = window.innerWidth;
   const windowHeight = window.innerHeight;
+  const safeArea = getSafeArea();
 
   // Check if widget is minimized
   const isMinimized = width === MIN_SIZE.width;
@@ -105,35 +120,46 @@ export const calculatePosition = (
   // Only bound dimensions if minimized
   const effectiveWidth = isMinimized
     ? width
-    : Math.min(width, windowWidth - SAFE_AREA * 2);
+    : Math.min(width, windowWidth - safeArea.left - safeArea.right);
   const effectiveHeight = isMinimized
     ? height
-    : Math.min(height, windowHeight - SAFE_AREA * 2);
+    : Math.min(height, windowHeight - safeArea.top - safeArea.bottom);
 
   // Calculate base positions
   let x: number;
   let y: number;
 
-  let leftBound = SAFE_AREA;
-  let rightBound =  windowWidth - effectiveWidth - SAFE_AREA;
-  let topBound = SAFE_AREA;
-  let bottomBound = windowHeight - effectiveHeight - SAFE_AREA;
+  let leftBound = safeArea.left;
+  let rightBound =  windowWidth - effectiveWidth - safeArea.right;
+  let topBound = safeArea.top;
+  let bottomBound = windowHeight - effectiveHeight - safeArea.bottom;
+
+  // In RTL the toolbar's containing block resolves to the right viewport
+  // edge (position: fixed with both left:0 and right:0 plus an explicit
+  // width pins to inline-end). translateX(negative) moves it leftward
+  // from that right anchor, so the *physical* right inset is `-safeArea.right`
+  // and the physical left inset is `-(windowWidth - width - safeArea.left)`.
+  // With symmetric SAFE_AREA these collapse to the original `-leftBound` /
+  // `-rightBound` values; asymmetric `safeArea` would otherwise apply the
+  // wrong edge to the wrong physical side.
+  const rtlRightCornerX = -safeArea.right;
+  const rtlLeftCornerX = -(windowWidth - effectiveWidth - safeArea.left);
 
   switch (corner) {
     case 'top-right':
-      x = isRTL ? -leftBound : rightBound;
+      x = isRTL ? rtlRightCornerX : rightBound;
       y = topBound;
       break;
     case 'bottom-right':
-      x = isRTL ? -leftBound : rightBound;
+      x = isRTL ? rtlRightCornerX : rightBound;
       y = bottomBound;
       break;
     case 'bottom-left':
-      x = isRTL ? -rightBound : leftBound;
+      x = isRTL ? rtlLeftCornerX : leftBound;
       y = bottomBound;
       break;
     case 'top-left':
-      x = isRTL ? -rightBound : leftBound;
+      x = isRTL ? rtlLeftCornerX : leftBound;
       y = topBound;
       break;
     default:
@@ -145,13 +171,11 @@ export const calculatePosition = (
   // Only ensure positions are within bounds if minimized
   if (isMinimized) {
     if (isRTL) {
-      // For RTL
       x = Math.min(
-        -leftBound,
-        Math.max(x, -rightBound)
+        rtlRightCornerX,
+        Math.max(x, rtlLeftCornerX),
       );
     } else {
-      // For LTR
       x = Math.max(
         leftBound,
         Math.min(x, rightBound),
@@ -224,9 +248,10 @@ export const calculateNewSizeAndPosition = (
   deltaY: number,
 ): { newSize: Size; newPosition: Position } => {
   const isRTL = getComputedStyle(document.body).direction === 'rtl';
+  const safeArea = getSafeArea();
 
-  const maxWidth = window.innerWidth - SAFE_AREA * 2;
-  const maxHeight = window.innerHeight - SAFE_AREA * 2;
+  const maxWidth = window.innerWidth - safeArea.left - safeArea.right;
+  const maxHeight = window.innerHeight - safeArea.top - safeArea.bottom;
 
   let newWidth = initialSize.width;
   let newHeight = initialSize.height;
@@ -236,27 +261,27 @@ export const calculateNewSizeAndPosition = (
   // horizontal resize for RTL
   if (isRTL && position.includes('right')) {
     // Check if we have enough space on the right
-    const availableWidth = -initialPosition.x + initialSize.width - SAFE_AREA;
+    const availableWidth = -initialPosition.x + initialSize.width - safeArea.right;
     const proposedWidth = Math.min(initialSize.width + deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
     newX = initialPosition.x + (newWidth - initialSize.width);
   }
   if (isRTL && position.includes('left')) {
     // Check if we have enough space on the left
-    const availableWidth = window.innerWidth - initialPosition.x - SAFE_AREA;
+    const availableWidth = window.innerWidth - initialPosition.x - safeArea.left;
     const proposedWidth = Math.min(initialSize.width - deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
   }
   // horizontal resize for LTR
   if (!isRTL && position.includes('right')) {
     // Check if we have enough space on the right
-    const availableWidth = window.innerWidth - initialPosition.x - SAFE_AREA;
+    const availableWidth = window.innerWidth - initialPosition.x - safeArea.right;
     const proposedWidth = Math.min(initialSize.width + deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
   }
   if (!isRTL && position.includes('left')) {
     // Check if we have enough space on the left
-    const availableWidth = initialPosition.x + initialSize.width - SAFE_AREA;
+    const availableWidth = initialPosition.x + initialSize.width - safeArea.left;
     const proposedWidth = Math.min(initialSize.width - deltaX, availableWidth);
     newWidth = Math.min(maxWidth, Math.max(MIN_SIZE.width, proposedWidth));
     newX = initialPosition.x - (newWidth - initialSize.width);
@@ -265,7 +290,7 @@ export const calculateNewSizeAndPosition = (
   // vertical resize
   if (position.includes('bottom')) {
     // Check if we have enough space at the bottom
-    const availableHeight = window.innerHeight - initialPosition.y - SAFE_AREA;
+    const availableHeight = window.innerHeight - initialPosition.y - safeArea.bottom;
     const proposedHeight = Math.min(
       initialSize.height + deltaY,
       availableHeight,
@@ -277,7 +302,7 @@ export const calculateNewSizeAndPosition = (
   }
   if (position.includes('top')) {
     // Check if we have enough space at the top
-    const availableHeight = initialPosition.y + initialSize.height - SAFE_AREA;
+    const availableHeight = initialPosition.y + initialSize.height - safeArea.top;
     const proposedHeight = Math.min(
       initialSize.height - deltaY,
       availableHeight,
@@ -289,20 +314,24 @@ export const calculateNewSizeAndPosition = (
     newY = initialPosition.y - (newHeight - initialSize.height);
   }
 
-  let leftBound = SAFE_AREA;
-  let rightBound = window.innerWidth - SAFE_AREA - newWidth;
-  let topBound = SAFE_AREA;
-  let bottomBound = window.innerHeight - SAFE_AREA - newHeight;
+  let leftBound = safeArea.left;
+  let rightBound = window.innerWidth - safeArea.right - newWidth;
+  let topBound = safeArea.top;
+  let bottomBound = window.innerHeight - safeArea.bottom - newHeight;
+
+  // See `calculatePosition` for why RTL uses these values: the toolbar is
+  // right-anchored in RTL, so physical-edge insets need different bounds
+  // than the LTR `[leftBound, rightBound]` clamp.
+  const rtlRightCornerX = -safeArea.right;
+  const rtlLeftCornerX = -(window.innerWidth - newWidth - safeArea.left);
 
   // Ensure position stays within bounds
   if (isRTL) {
-    // for RTL
     newX = Math.min(
-      -leftBound,
-      Math.max(newX, -rightBound)
+      rtlRightCornerX,
+      Math.max(newX, rtlLeftCornerX),
     );
   } else {
-    // for LTR
     newX = Math.max(
       leftBound,
       Math.min(newX, rightBound),
diff --git a/packages/scan/src/web/widget/index.tsx b/packages/scan/src/web/widget/index.tsx
index b7223a79..7025eb03 100644
--- a/packages/scan/src/web/widget/index.tsx
+++ b/packages/scan/src/web/widget/index.tsx
@@ -13,17 +13,18 @@ import {
   LOCALSTORAGE_KEY,
   LOCALSTORAGE_COLLAPSED_KEY,
   MIN_SIZE,
-  SAFE_AREA,
   LOCALSTORAGE_LAST_VIEW_KEY,
+  TOOLBAR_INTERACTIVE_SELECTOR,
 } from "../constants";
 import {
-  defaultWidgetConfig,
+  getDefaultWidgetConfig,
   signalRefWidget,
   signalWidget,
   signalWidgetViews,
   updateDimensions,
   type WidgetStates,
 } from "../state";
+import { getSafeArea } from "../utils/safe-area";
 import {
   calculateBoundedSize,
   calculatePosition,
@@ -82,25 +83,26 @@ export const Widget = () => {
       const { corner: collapsedCorner, orientation = "horizontal" } =
         signalWidgetCollapsed.value;
       const size = COLLAPSED_SIZE[orientation];
+      const safeArea = getSafeArea();
 
       switch (collapsedCorner) {
         case "top-left":
           finalPosition =
             orientation === "horizontal"
-              ? { x: -1, y: SAFE_AREA }
-              : { x: SAFE_AREA, y: -1 };
+              ? { x: -1, y: safeArea.top }
+              : { x: safeArea.left, y: -1 };
           break;
         case "bottom-left":
           finalPosition =
             orientation === "horizontal"
-              ? { x: -1, y: window.innerHeight - size.height - SAFE_AREA }
-              : { x: SAFE_AREA, y: window.innerHeight - size.height + 1 };
+              ? { x: -1, y: window.innerHeight - size.height - safeArea.bottom }
+              : { x: safeArea.left, y: window.innerHeight - size.height + 1 };
           break;
         case "top-right":
           finalPosition =
             orientation === "horizontal"
-              ? { x: window.innerWidth - size.width + 1, y: SAFE_AREA }
-              : { x: window.innerWidth - size.width - SAFE_AREA, y: -1 };
+              ? { x: window.innerWidth - size.width + 1, y: safeArea.top }
+              : { x: window.innerWidth - size.width - safeArea.right, y: -1 };
           break;
         case "bottom-right":
         default:
@@ -108,10 +110,10 @@ export const Widget = () => {
             orientation === "horizontal"
               ? {
                   x: window.innerWidth - size.width + 1,
-                  y: window.innerHeight - size.height - SAFE_AREA,
+                  y: window.innerHeight - size.height - safeArea.bottom,
                 }
               : {
-                  x: window.innerWidth - size.width - SAFE_AREA,
+                  x: window.innerWidth - size.width - safeArea.right,
                   y: window.innerHeight - size.height + 1,
                 };
           break;
@@ -145,9 +147,10 @@ export const Widget = () => {
       rafId = null;
     });
 
+    const safeArea = getSafeArea();
     const newDimensions = {
-      isFullWidth: newWidth >= window.innerWidth - SAFE_AREA * 2,
-      isFullHeight: newHeight >= window.innerHeight - SAFE_AREA * 2,
+      isFullWidth: newWidth >= window.innerWidth - safeArea.left - safeArea.right,
+      isFullHeight: newHeight >= window.innerHeight - safeArea.top - safeArea.bottom,
       width: newWidth,
       height: newHeight,
       position: finalPosition,
@@ -178,10 +181,17 @@ export const Widget = () => {
 
   const handleDrag = useCallback(
     (e: JSX.TargetedPointerEvent) => {
-      e.preventDefault();
+      const target = e.target as HTMLElement;
 
-      if (!refWidget.current || (e.target as HTMLElement).closest("button"))
+      // Skip drag on interactive/text-selectable surfaces so users can select
+      // prompt text, focus inputs, and click buttons normally.
+      if (target.closest(TOOLBAR_INTERACTIVE_SELECTOR)) {
         return;
+      }
+
+      e.preventDefault();
+
+      if (!refWidget.current) return;
 
       const container = refWidget.current;
       const containerStyle = container.style;
@@ -478,13 +488,14 @@ export const Widget = () => {
                 let newX = e.clientX - targetWidth / 2;
                 let newY = e.clientY - targetHeight / 2;
 
+                const safeArea = getSafeArea();
                 newX = Math.max(
-                  SAFE_AREA,
-                  Math.min(newX, window.innerWidth - targetWidth - SAFE_AREA)
+                  safeArea.left,
+                  Math.min(newX, window.innerWidth - targetWidth - safeArea.right)
                 );
                 newY = Math.max(
-                  SAFE_AREA,
-                  Math.min(newY, window.innerHeight - targetHeight - SAFE_AREA)
+                  safeArea.top,
+                  Math.min(newY, window.innerHeight - targetHeight - safeArea.bottom)
                 );
 
                 signalWidget.value = {
@@ -558,8 +569,9 @@ export const Widget = () => {
       refInitialMinimizedWidth.current = 0;
     }
 
-    refWidget.current.style.maxWidth = `calc(100vw - ${SAFE_AREA * 2}px)`;
-    refWidget.current.style.maxHeight = `calc(100vh - ${SAFE_AREA * 2}px)`;
+    const safeArea = getSafeArea();
+    refWidget.current.style.maxWidth = `calc(100vw - ${safeArea.left + safeArea.right}px)`;
+    refWidget.current.style.maxHeight = `calc(100vh - ${safeArea.top + safeArea.bottom}px)`;
 
     updateWidgetPosition();
 
@@ -631,7 +643,7 @@ export const Widget = () => {
       unsubscribeSignalWidget();
 
       saveLocalStorage(LOCALSTORAGE_KEY, {
-        ...defaultWidgetConfig,
+        ...getDefaultWidgetConfig(),
         corner: signalWidget.value.corner,
       });
     };
diff --git a/packages/scan/tsup.config.ts b/packages/scan/tsup.config.ts
index 09bde403..113c591b 100644
--- a/packages/scan/tsup.config.ts
+++ b/packages/scan/tsup.config.ts
@@ -92,7 +92,10 @@ export default defineConfig([
     clean: false,
     sourcemap: false,
     format: ['iife'],
-    target: 'esnext',
+    // Target ES2019 (no `?.`, no `??`) so older babel-loader configs without
+    // `@babel/preset-env` for optional chaining can still parse the bundle
+    // (#287, #336).
+    target: 'es2019',
     platform: 'browser',
     treeshake: true,
     dts: true,
@@ -130,7 +133,7 @@ export default defineConfig([
     clean: false,
     sourcemap: false,
     format: ['cjs', 'esm'],
-    target: 'esnext',
+    target: 'es2019',
     platform: 'browser',
     // FIXME: tree shaking removes use client directive
     // Info: vercel analytics does the same thing- https://github.com/vercel/analytics/blob/main/packages/web/tsup.config.js