Compare commits

..
17 changed files with 701 additions and 44 deletions

No files matched your search

+38 -14
View File
@@ -1,33 +1,57 @@
import { posix } from "node:path";
import ts from "typescript";
/** The `@/*` import alias a tsconfig maps to one project directory, such as `src/` or the root. */
/** The import aliases a tsconfig maps to project directories, such as `@/*` to `src/` and `@/assets/*` to `assets/`. */
export type TsconfigAlias = {
/** Directory prefix that replaces `@/`, with a trailing slash or empty for the project root. */
target: string;
/** Each alias prefix (`@/`, `@/assets/`) and the directory prefix that replaces it, longest prefix first. */
prefixes: readonly { prefix: string; target: string }[];
/** `baseUrl` is the project root: a bare specifier no alias matches is looked up there before it is taken for a package. */
baseUrl?: true;
/** Set when the tsconfig asks for module resolution the static analysis cannot follow. */
unsupported?: string;
};
const SINGLE_DIRECTORY_TARGET = /^(?:\.\/)?((?:[\w.-]+\/)*)\*$/;
// A relative-looking key (`./*`, `/*`) is never applied: TypeScript and Metro resolve relative specifiers directly.
const PREFIX_KEY = /^([^*./][^*]*\/)\*$/;
const DEFAULT: TsconfigAlias = { prefixes: [{ prefix: "@/", target: "src/" }] };
/**
* Static analysis follows one alias, `@/*`, pointing at a single directory (`./*`, `src/*`, `./src/*`),
* which is what create-expo-app and the Expo docs set up. Anything else is reported, not guessed.
* Static analysis follows `paths` entries of the form `prefix/*` that each point at a single directory (`./*`, `src/*`,
* `./assets/*`), which covers create-expo-app's `@/*` and the extra entries apps add beside it. Anything else is
* reported, not guessed.
*/
export function readTsconfigAlias(configText: string | undefined): TsconfigAlias {
if (configText === undefined) return { target: "src/" };
if (configText === undefined) return DEFAULT;
const parsed = ts.parseConfigFileTextToJson("tsconfig.json", configText);
const options = parsed.config?.compilerOptions ?? {};
const unsupported = { target: "src/", unsupported: "custom module resolution is not statically supported" };
const unsupported = { ...DEFAULT, unsupported: "custom module resolution is not statically supported" };
if (parsed.error) return unsupported;
if (options.baseUrl && ![".", "./"].includes(options.baseUrl)) return unsupported;
if (parsed.config?.extends && parsed.config.extends !== "expo/tsconfig.base") return unsupported;
const baseUrl = options.baseUrl ? { baseUrl: true as const } : {};
const entries = Object.entries(options.paths ?? {}) as [string, unknown][];
if (entries.length === 0) return { target: "src/" };
if (entries.length > 1 || entries[0]![0] !== "@/*") return unsupported;
const targets = entries[0]![1];
if (!Array.isArray(targets) || targets.length !== 1 || typeof targets[0] !== "string") return unsupported;
const match = SINGLE_DIRECTORY_TARGET.exec(targets[0]);
if (!match || match[1]!.split("/").includes("..")) return unsupported;
return { target: match[1]! };
if (entries.length === 0) return { ...DEFAULT, ...baseUrl };
const prefixes: { prefix: string; target: string }[] = [];
for (const [key, targets] of entries) {
const prefix = PREFIX_KEY.exec(key)?.[1];
if (!prefix || !Array.isArray(targets) || targets.length !== 1 || typeof targets[0] !== "string") return unsupported;
const match = SINGLE_DIRECTORY_TARGET.exec(targets[0]);
if (!match || match[1]!.split("/").some(segment => segment === "." || segment === "..")) return unsupported;
prefixes.push({ prefix, target: match[1]! });
}
// TypeScript picks the pattern with the longest prefix, so `@/assets/x` goes to `assets/`, not `src/assets/`.
return { prefixes: prefixes.sort((a, b) => b.prefix.length - a.prefix.length), ...baseUrl };
}
/** The project path an aliased specifier names, before extensions, or undefined when no alias matches it. */
export function resolveTsconfigAlias(alias: TsconfigAlias, specifier: string): string | undefined {
const entry = alias.prefixes.find(({ prefix }) => specifier.startsWith(prefix));
// Normalized as Metro joins it: `@app/a/../b` is `src/b`, and a trailing slash still finds `index`.
return entry ? posix.normalize(`${entry.target}${specifier.slice(entry.prefix.length)}`).replace(/\/$/, "") : undefined;
}
/** The project path a bare specifier names under a root `baseUrl`, or undefined; a miss there is a package, not a gap. */
export function resolveTsconfigBaseUrl(alias: TsconfigAlias, specifier: string): string | undefined {
return alias.baseUrl && !/^[./]/.test(specifier) ? specifier : undefined;
}
+9 -7
View File
@@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process";
import ts from "typescript";
import type { SourceChange } from "./git-diff.js";
import { validateSourceRoutes, type SourceRoute } from "../contracts/source-route.js";
import { readTsconfigAlias } from "../shared/tsconfig-alias.js";
import { readTsconfigAlias, resolveTsconfigAlias, resolveTsconfigBaseUrl } from "../shared/tsconfig-alias.js";
/** Repository path → file text at one exact commit. Non-source files carry an empty string. */
export type SourceSnapshot = ReadonlyMap<string, string>;
@@ -50,11 +50,12 @@ export function surfaceDependencies(routes: readonly SourceRoute[], files: Sourc
if (alias.unsupported) unresolved.add("Custom TypeScript module resolution requires conservative capture");
const cache = new Map<string, string[]>();
const resolveModule = (importer: string, specifier: string): string | undefined => {
const base = specifier.startsWith("@/") ? `${alias.target}${specifier.slice(2)}`
: specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer), specifier))
: undefined;
const base = resolveTsconfigAlias(alias, specifier)
?? (specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer), specifier))
: resolveTsconfigBaseUrl(alias, specifier));
if (!base) return undefined;
const extensions = ["tsx", "ts", "jsx", "js"].flatMap(ext => [`.${platform}.${ext}`, ...(platform === "web" ? [] : [`.native.${ext}`]), `.${ext}`]).concat([".mjs", ".cjs", ".json"]);
// Metro tries a platform suffix with every extension before the next suffix, so `Foo.ios.ts` beats `Foo.tsx`.
const extensions = [`.${platform}`, ...(platform === "web" ? [] : [".native"]), ""].flatMap(suffix => ["tsx", "ts", "jsx", "js"].map(ext => `${suffix}.${ext}`)).concat([".mjs", ".cjs", ".json"]);
return [...extensions.map((ext) => base + ext), base,
...extensions.map((ext) => `${base}/index${ext}`)].find((candidate) => !/(?:^|\/)surfaces?\.json$/.test(candidate) && files.has(candidate));
};
@@ -78,7 +79,8 @@ export function surfaceDependencies(routes: readonly SourceRoute[], files: Sourc
const specifier = node.text;
const resolved = resolveModule(path, specifier);
if (resolved) dependencies.push(resolved);
else if (specifier.startsWith(".") || specifier.startsWith("@/") || specifier.startsWith("~")) {
// An alias that matches but finds no file (an .svg, a scale variant) is local code this analysis cannot follow, not a package.
else if (specifier.startsWith(".") || resolveTsconfigAlias(alias, specifier) !== undefined || specifier.startsWith("@/") || specifier.startsWith("~")) {
unresolved.add(`Unresolved runtime import: ${path} -> ${specifier}`);
}
// Bare npm packages are covered by lockfile/package changes.
@@ -103,7 +105,7 @@ export function surfaceDependencies(routes: readonly SourceRoute[], files: Sourc
const pending = [surface.routeFile, ...surface.sourceFiles];
let directory = posix.dirname(surface.routeFile);
while (directory !== "." && directory !== "/") {
const suffixes = ["tsx", "ts", "jsx", "js"].flatMap(extension => [`.${platform}.${extension}`, ...(platform === "web" ? [] : [`.native.${extension}`]), `.${extension}`]);
const suffixes = [`.${platform}`, ...(platform === "web" ? [] : [".native"]), ""].flatMap(suffix => ["tsx", "ts", "jsx", "js"].map(ext => `${suffix}.${ext}`));
const layout = suffixes.map(suffix => `${directory}/_layout${suffix}`).find(path => files.has(path));
if (layout) pending.push(layout);
directory = posix.dirname(directory);
+5 -5
View File
@@ -1,7 +1,7 @@
import { posix } from "node:path";
import ts from "typescript";
import type { SourceSnapshot } from "./dependency-graph.js";
import { readTsconfigAlias } from "../shared/tsconfig-alias.js";
import { readTsconfigAlias, resolveTsconfigAlias, resolveTsconfigBaseUrl } from "../shared/tsconfig-alias.js";
import { detectAppDir, routeGroupOf } from "./route-providers/expo-router.js";
import { validateSourceRoutes, type SourceRoute } from "../contracts/source-route.js";
import { validateNavigationGraph, type NavigationEdge, type NavigationGraph } from "../contracts/navigation-graph.js";
@@ -54,7 +54,7 @@ export function extractSourceNavigation(routes: readonly SourceRoute[], files: S
if (routes.length > 5_000 || files.size > 50_000) throw new Error("Source navigation inventory exceeds its analysis limit");
const appDir = detectAppDir(files, analysis.entry);
const platform = analysis.platform ?? "ios";
const extensions = ["tsx", "ts", "jsx", "js"].flatMap(extension => [`.${platform}.${extension}`, ...(platform === "web" ? [] : [`.native.${extension}`]), `.${extension}`]).concat([".mjs", ".cjs"]);
const extensions = [`.${platform}`, ...(platform === "web" ? [] : [".native"]), ""].flatMap(suffix => ["tsx", "ts", "jsx", "js"].map(ext => `${suffix}.${ext}`)).concat([".mjs", ".cjs"]);
const unresolved = new Set<string>();
const edges = new Map<string, NavigationEdge>();
const modalSurfaceIds = new Set<string>();
@@ -65,8 +65,8 @@ export function extractSourceNavigation(routes: readonly SourceRoute[], files: S
const alias = readTsconfigAlias(files.get("tsconfig.json"));
if (alias.unsupported) unresolved.add(`Unresolved navigation: tsconfig.json: ${alias.unsupported}`);
const resolveModule = (specifier: string, importer: string): string | undefined => {
const base = specifier.startsWith("@/") ? `${alias.target}${specifier.slice(2)}`
: specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer.replace(/^\//, "")), specifier)) : undefined;
const base = resolveTsconfigAlias(alias, specifier)
?? (specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer.replace(/^\//, "")), specifier)) : resolveTsconfigBaseUrl(alias, specifier));
if (!base || base.startsWith("../")) return undefined;
const withoutJs = /\.[cm]?jsx?$/.test(base) ? base.replace(/\.[cm]?jsx?$/, "") : base;
return [...extensions.map((ext) => base + ext), base,
@@ -542,7 +542,7 @@ export function extractSourceNavigation(routes: readonly SourceRoute[], files: S
let parent: ts.Node = declaration;
while (!ts.isImportDeclaration(parent) && !ts.isSourceFile(parent)) parent = parent.parent;
if (ts.isImportDeclaration(parent) && ts.isStringLiteral(parent.moduleSpecifier)
&& /^(?:\.|@\/|~)/.test(parent.moduleSpecifier.text)
&& (/^(?:\.|@\/|~)/.test(parent.moduleSpecifier.text) || resolveTsconfigAlias(alias, parent.moduleSpecifier.text) !== undefined)
&& !assetFile.test(parent.moduleSpecifier.text)
&& !resolveModule(parent.moduleSpecifier.text, parent.getSourceFile().fileName)) issue(parent, "local imported code could not be resolved");
}
+4 -4
View File
@@ -1,6 +1,6 @@
import { posix } from "node:path";
import ts from "typescript";
import { readTsconfigAlias } from "../../shared/tsconfig-alias.js";
import { readTsconfigAlias, resolveTsconfigAlias, resolveTsconfigBaseUrl } from "../../shared/tsconfig-alias.js";
const UNKNOWN = "\u0000";
const MAX_VALUES = 64;
@@ -15,7 +15,7 @@ function unwrap(node: ts.Node): ts.Node {
/** Prove that every render path forwards elsewhere; unknown behavior remains capturable. */
export function expoRedirectTargets(files: ReadonlyMap<string, string>, routeFiles: readonly string[], platform = "ios"): Map<string, string[]> {
const extensions = ["tsx", "ts", "jsx", "js"].flatMap(ext => [`.${platform}.${ext}`, ...(platform === "web" ? [] : [`.native.${ext}`]), `.${ext}`]).concat([".mjs", ".cjs"]);
const extensions = [`.${platform}`, ...(platform === "web" ? [] : [".native"]), ""].flatMap(suffix => ["tsx", "ts", "jsx", "js"].map(ext => `${suffix}.${ext}`)).concat([".mjs", ".cjs"]);
const sources = new Map<string, ts.SourceFile | undefined>();
let sourceBytes = 0;
const sourceFile = (name: string): ts.SourceFile | undefined => {
@@ -34,8 +34,8 @@ export function expoRedirectTargets(files: ReadonlyMap<string, string>, routeFil
};
const alias = readTsconfigAlias(files.get("tsconfig.json"));
const resolveModule = (specifier: string, importer: string): string | undefined => {
const base = specifier.startsWith("@/") && !alias.unsupported ? `${alias.target}${specifier.slice(2)}`
: specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer.replace(/^\//, "")), specifier)) : undefined;
const base = (alias.unsupported ? undefined : resolveTsconfigAlias(alias, specifier))
?? (specifier.startsWith(".") ? posix.normalize(posix.join(posix.dirname(importer.replace(/^\//, "")), specifier)) : alias.unsupported ? undefined : resolveTsconfigBaseUrl(alias, specifier));
if (!base || base.startsWith("../")) return undefined;
const withoutJs = base.replace(/\.[cm]?jsx?$/, "");
return [...extensions.map(ext => base + ext), base, ...extensions.map(ext => `${base}/index${ext}`),
@@ -45,6 +45,8 @@ export function discoverReactNavigation(files: Record<string, string>, options:
}
}
}
// TypeScript uses the pattern with the longest prefix and no other, so `@/assets/x` never falls back to `@/*`.
aliases.sort((a, b) => b.pattern.split("*")[0]!.length - a.pattern.split("*")[0]!.length);
const resolveModule = (file: string, specifier: string): string | undefined => {
const bases: string[] = [];
if (specifier.startsWith(".")) bases.push(posix.normalize(posix.join(posix.dirname(file), specifier)));
@@ -54,6 +56,7 @@ export function discoverReactNavigation(files: Record<string, string>, options:
if (suffix === undefined ? specifier === prefix : specifier.startsWith(prefix!) && specifier.endsWith(suffix)) {
const replacement = suffix === undefined ? "" : specifier.slice(prefix!.length, specifier.length - suffix.length);
bases.push(...alias.targets.map((target) => posix.normalize(posix.join(alias.base, target.replace("*", replacement)))));
break;
}
}
}
+235
View File
@@ -0,0 +1,235 @@
import { expect, test, type Page } from "@playwright/test";
const STORAGE_KEY = "expo-explore:inspector-width";
const panel = (page: Page) => page.getByRole("complementary", { name: "Inspector panel" });
const handle = (page: Page) => page.getByRole("separator", { name: "Resize inspector" });
const panelWidth = async (page: Page) => (await panel(page).boundingBox())!.width;
const storedWidth = (page: Page) => page.evaluate((key) => localStorage.getItem(key), STORAGE_KEY);
/** Drags the panel's edge `dx` pixels (negative is left, which widens the panel). */
async function dragEdge(page: Page, dx: number) {
const box = (await handle(page).boundingBox())!;
const x = box.x + box.width / 2;
const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + dx / 2, y);
await page.mouse.move(x + dx, y);
await page.mouse.up();
}
test.describe("Inspector resize", () => {
test("dragging the edge resizes the Inspector, and the width is kept for the next visit", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
// The 1280px test window takes the wide default.
expect(await panelWidth(page)).toBe(400);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "400");
await dragEdge(page, -150);
await expect.poll(() => panelWidth(page)).toBe(550);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "550");
expect(await storedWidth(page)).toBe("550");
await page.reload();
await expect(panel(page)).toBeVisible();
await expect.poll(() => panelWidth(page)).toBe(550);
// Dragging back right narrows it, never below the minimum.
await dragEdge(page, 400);
await expect.poll(() => panelWidth(page)).toBe(320);
expect(await storedWidth(page)).toBe("320");
});
test("the width stops at half the window, and a double-click restores the default", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
await dragEdge(page, -600);
await expect.poll(() => panelWidth(page)).toBe(640);
await expect(handle(page)).toHaveAttribute("aria-valuemax", "640");
await expect(handle(page)).toHaveAttribute("aria-valuenow", "640");
// The canvas toolbar moves left, out from under the wide panel, instead of being covered.
const toolbar = page.getByRole("toolbar", { name: "Canvas tools" });
await expect(toolbar).toBeVisible();
await expect.poll(async () => {
const toolbarBox = (await toolbar.boundingBox())!;
const panelBox = (await panel(page).boundingBox())!;
return panelBox.x - (toolbarBox.x + toolbarBox.width);
}).toBeGreaterThanOrEqual(8);
await handle(page).dblclick();
await expect.poll(() => panelWidth(page)).toBe(400);
expect(await storedWidth(page)).toBeNull();
});
test("arrow keys move the edge a step; Home and End take it to its limits", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
await handle(page).focus();
await page.keyboard.press("ArrowLeft");
await expect.poll(() => panelWidth(page)).toBe(416);
await page.keyboard.press("ArrowLeft");
await expect.poll(() => panelWidth(page)).toBe(432);
await page.keyboard.press("ArrowRight");
await expect.poll(() => panelWidth(page)).toBe(416);
await page.keyboard.press("End");
await expect.poll(() => panelWidth(page)).toBe(640);
await page.keyboard.press("Home");
await expect.poll(() => panelWidth(page)).toBe(320);
// The arrows resized the panel; they did not step the selected screen.
expect(new URL(page.url()).searchParams.get("screen")).toBe("area-0-screen-1");
});
test("a saved width wider than half of a smaller window is held to half of it", async ({ page }) => {
await page.addInitScript((key) => localStorage.setItem(key, "760"), STORAGE_KEY);
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
expect(await panelWidth(page)).toBe(640);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "640");
});
test("a drag that ends where it started leaves the default width in place", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
const box = (await handle(page).boundingBox())!;
const x = box.x + box.width / 2;
const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x - 100, y);
await expect.poll(() => panelWidth(page)).toBe(500);
await page.mouse.move(x, y);
await page.mouse.up();
await expect.poll(() => panelWidth(page)).toBe(400);
expect(await storedWidth(page)).toBeNull();
// Still the default: a narrower window takes the narrow default, not the 400 the drag passed through.
await page.setViewportSize({ width: 1100, height: 820 });
await expect.poll(() => panelWidth(page)).toBe(320);
});
test("a saved width below the minimum is held to it", async ({ page }) => {
await page.addInitScript((key) => localStorage.setItem(key, "40"), STORAGE_KEY);
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
expect(await panelWidth(page)).toBe(320);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "320");
});
test.describe("in a window wider than two maximum panels", () => {
test.use({ viewport: { width: 1700, height: 900 } });
test("a saved width above the maximum is held to it", async ({ page }) => {
await page.addInitScript((key) => localStorage.setItem(key, "5000"), STORAGE_KEY);
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
// Half of this window is 850.
expect(await panelWidth(page)).toBe(800);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "800");
});
});
test("a key that cannot move the edge keeps the saved width", async ({ page }) => {
await page.addInitScript((key) => localStorage.setItem(key, "760"), STORAGE_KEY);
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
expect(await panelWidth(page)).toBe(640);
await handle(page).focus();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
expect(await storedWidth(page)).toBe("760");
await page.keyboard.press("ArrowRight");
await expect.poll(() => panelWidth(page)).toBe(624);
expect(await storedWidth(page)).toBe("624");
});
test("the separator's values follow the window", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
await handle(page).focus();
await page.keyboard.press("End");
await expect(handle(page)).toHaveAttribute("aria-valuenow", "640");
await page.setViewportSize({ width: 1000, height: 820 });
await expect.poll(() => panelWidth(page)).toBe(500);
await expect(handle(page)).toHaveAttribute("aria-valuemax", "500");
await expect(handle(page)).toHaveAttribute("aria-valuenow", "500");
// Back in the wide window the saved width returns.
await page.setViewportSize({ width: 1280, height: 820 });
await expect.poll(() => panelWidth(page)).toBe(640);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "640");
});
test("closing the Inspector mid-drag ends the drag", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
const box = (await handle(page).boundingBox())!;
const x = box.x + box.width / 2;
const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x - 100, y);
await expect(page.locator("html")).toHaveClass(/inspector-resizing/);
await page.keyboard.press("i");
await expect(panel(page)).toHaveCount(0);
await page.mouse.up();
await expect(page.locator("html")).not.toHaveClass(/inspector-resizing/);
// The width the drag reached is kept.
await page.keyboard.press("i");
await expect.poll(() => panelWidth(page)).toBe(500);
});
test.describe("in a window too narrow for the toolbar beside a wide Inspector", () => {
test.use({ viewport: { width: 820, height: 800 } });
test("the toolbar never moves past the canvas' left edge", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
const toolbar = page.getByRole("toolbar", { name: "Canvas tools" });
await expect(toolbar).toBeVisible();
await handle(page).focus();
await page.keyboard.press("End");
await expect.poll(() => panelWidth(page)).toBe(410);
// Either it fits between the window's edge and the panel, or it gives way, as it does when
// the panels leave the canvas too little room.
await expect.poll(async () => {
if (await toolbar.count() === 0) return true;
const toolbarBox = (await toolbar.boundingBox())!;
const panelBox = (await panel(page).boundingBox())!;
return toolbarBox.x >= 0 && toolbarBox.x + toolbarBox.width <= panelBox.x;
}).toBe(true);
// Narrowed again, the toolbar returns.
await page.keyboard.press("Home");
await expect(toolbar).toBeVisible();
const toolbarBox = (await toolbar.boundingBox())!;
const panelBox = (await panel(page).boundingBox())!;
expect(toolbarBox.x).toBeGreaterThanOrEqual(0);
expect(toolbarBox.x + toolbarBox.width + 12).toBeCloseTo(panelBox.x, 0);
});
});
test.describe("in a narrow window", () => {
test.use({ viewport: { width: 1180, height: 820 } });
test("the Inspector starts at its narrow default, and a saved width is held to half the window", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
expect(await panelWidth(page)).toBe(320);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "320");
await page.evaluate((key) => localStorage.setItem(key, "760"), STORAGE_KEY);
await page.reload();
await expect(panel(page)).toBeVisible();
expect(await panelWidth(page)).toBe(590);
await expect(handle(page)).toHaveAttribute("aria-valuenow", "590");
});
});
test.describe("on a phone", () => {
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true });
test("the Inspector sheet has no resize edge", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
await expect(handle(page)).toHaveCount(0);
});
});
});
+22 -3
View File
@@ -2360,9 +2360,9 @@ test("keeps minimap and canvas chrome inside the responsive visible frame", asyn
for (const box of [minimapBox!, cameraBox!]) {
expect(box.x + box.width).toBeLessThanOrEqual(inspectorBox!.x + 1);
}
expect(Math.abs(
toolbarBox!.x + toolbarBox!.width / 2 - page.viewportSize()!.width / 2,
)).toBeLessThanOrEqual(1);
// The toolbar keeps the window's centre unless the Inspector would cover it; this 320px overlay
// would, so it clears the panel's edge by 12px instead.
expect(toolbarBox!.x + toolbarBox!.width + 12).toBeCloseTo(inspectorBox!.x, 0);
expect(minimapBox!.y + minimapBox!.height + 11).toBeLessThanOrEqual(toolbarBox!.y);
expect(minimapBox!.width).toBeCloseTo(168, 0);
expect(minimapBox!.height).toBeCloseTo(112, 0);
@@ -5449,3 +5449,22 @@ test("a find left on when the window narrows to the phone layout does not filter
await page.setViewportSize({ width: 390, height: 844 });
await expect(cells).toHaveCount(all);
});
test.describe("a wide Inspector in a short window", () => {
test.use({ viewport: { width: 1180, height: 600 } });
test("holds the review's Split pair to most of the window's height", async ({ page }) => {
await page.addInitScript(() => localStorage.setItem("expo-explore:inspector-width", "590"));
await serveWorkspace(page);
await page.goto("/map?screen=current-profile");
const review = page.locator(".right-panel").getByRole("region", { name: "Changes in /current-profile" });
await expect(review).toBeVisible();
await review.getByRole("button", { name: /^Split/ }).click();
const frame = review.locator(".compare-frame").first();
await expect(frame).toBeVisible();
// Two frames of a 590px panel would be over 600px tall unbounded; the cap is 70% of the window,
// the same as Swipe's and Flip's one frame.
await expect.poll(async () => (await frame.boundingBox())!.height).toBeLessThanOrEqual(421);
await expect.poll(async () => (await frame.boundingBox())!.height).toBeGreaterThan(300);
});
});
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import test from "node:test";
const { tsImport } = await import("tsx/esm/api");
const { clampInspectorWidth, inspectorWidthBounds, INSPECTOR_WIDTH_MAX, INSPECTOR_WIDTH_MIN } =
await tsImport("../../viewer/src/utils/inspector-width.ts", import.meta.url);
test("the Inspector may take at most half the window, within its fixed range", () => {
assert.deepEqual(inspectorWidthBounds(1440), { min: INSPECTOR_WIDTH_MIN, max: 720 });
assert.deepEqual(inspectorWidthBounds(2560), { min: INSPECTOR_WIDTH_MIN, max: INSPECTOR_WIDTH_MAX });
// A window narrower than two minimum panels still allows the minimum.
assert.deepEqual(inspectorWidthBounds(500), { min: INSPECTOR_WIDTH_MIN, max: INSPECTOR_WIDTH_MIN });
});
test("the bounds are in the panel's own pixels when the chrome is zoomed", () => {
assert.deepEqual(inspectorWidthBounds(1600, 1.25), { min: INSPECTOR_WIDTH_MIN, max: 640 });
assert.deepEqual(inspectorWidthBounds(1600, 0), inspectorWidthBounds(1600, 1));
});
test("a width is clamped to the bounds and rounded to whole pixels", () => {
const bounds = { min: 320, max: 720 };
assert.equal(clampInspectorWidth(100, bounds), 320);
assert.equal(clampInspectorWidth(1000, bounds), 720);
assert.equal(clampInspectorWidth(455.6, bounds), 456);
});
+54
View File
@@ -21,6 +21,60 @@ test("import closure attributes component and platform-source changes to depende
assert.deepEqual(selectedPaths(plan({base:files,platform:"android",changes:[{status:"modified",path:"src/theme.ios.ts"}]})), []);
});
test("tsconfig paths with several single-directory aliases resolve by their longest prefix, as TypeScript does", () => {
const tsconfig = JSON.stringify({ extends: "expo/tsconfig.base", compilerOptions: { paths: { "@/*": ["./src/*"], "@/assets/*": ["./assets/*"] } } });
const files = [["tsconfig.json", tsconfig], ["src/app/one.tsx", 'import { tint } from "@/theme"; import icon from "@/assets/icon"; export default () => [tint, icon];'],
["src/app/two.tsx", page], ["src/theme.ts", "export const tint = 'blue';"], ["assets/icon.ts", "export default 'icon';"], ["src/assets/icon.ts", "export default 'other';"]];
const result = plan({ base: files, changes: [{ status: "modified", path: "assets/icon.ts" }] });
assert.deepEqual(selectedPaths(result), ["/one"]);
assert.equal(result.surfaces.flatMap(row => row.reasons ?? []).some(reason => /module resolution/.test(reason)), false);
// `@/assets/icon` is `assets/icon.ts`, not `src/assets/icon.ts`, so an edit to the latter changes nothing.
assert.deepEqual(selectedPaths(plan({ base: files, changes: [{ status: "modified", path: "src/assets/icon.ts" }] })), []);
assert.deepEqual(selectedPaths(plan({ base: files, changes: [{ status: "modified", path: "src/theme.ts" }] })), ["/one"]);
});
test("an alias import that finds no file is local code the plan cannot follow, not a package", () => {
const tsconfig = JSON.stringify({ compilerOptions: { paths: { "@/*": ["./src/*"], "@icons/*": ["./src/icons/*"] } } });
const files = [["tsconfig.json", tsconfig], ["src/app/one.tsx", 'import Logo from "@icons/logo"; export default () => Logo;'], ["src/app/two.tsx", page], ["src/icons/logo.svg", "<svg/>"]];
const result = plan({ base: files, changes: [{ status: "modified", path: "src/icons/logo.svg" }] });
assert.ok(result.unresolved.some(message => message.includes("@icons/logo")), JSON.stringify(result.unresolved));
assert.ok(selectedPaths(result).includes("/one"));
});
test("tsconfig aliases: single-directory prefix keys are followed; anything TypeScript would read differently is not", async () => {
const { readTsconfigAlias, resolveTsconfigAlias } = await tsImport("../../src/shared/tsconfig-alias.ts", import.meta.url);
const read = paths => readTsconfigAlias(JSON.stringify({ compilerOptions: { paths } }));
for (const paths of [{ "*": ["src/*"] }, { "@*": ["src/*"] }, { "@/x": ["src/x"] }, { "@/*/x": ["src/*"] }, { "./*": ["src/*"] }, { "/*": ["src/*"] },
{ "@/*": ["src/*", "lib/*"] }, { "@/*": ["../src/*"] }, { "@/*": ["./src/./lib/*"] }, { "@/*": ["src/*.ts"] }]) {
assert.ok(read(paths).unsupported, JSON.stringify(paths));
}
const alias = read({ "@/*": ["./src/*"], "@/assets/*": ["./assets/*"], "~/*": ["./*"] });
assert.equal(alias.unsupported, undefined);
assert.equal(resolveTsconfigAlias(alias, "@/assets/icon"), "assets/icon");
assert.equal(resolveTsconfigAlias(alias, "@/assets"), "src/assets");
assert.equal(resolveTsconfigAlias(alias, "~/theme"), "theme");
assert.equal(resolveTsconfigAlias(alias, "react"), undefined);
assert.equal(resolveTsconfigAlias(alias, "@/a/../b"), "src/b");
assert.equal(resolveTsconfigAlias(alias, "@/components/"), "src/components");
});
test("a platform file wins over a plain file of another extension, as Metro resolves it", () => {
const files = [["app/one.tsx", 'import Card from "../src/card"; export default () => Card;'], ["app/two.tsx", page],
["src/card.tsx", "export default 1;"], ["src/card.ios.ts", "export default 2;"]];
assert.deepEqual(selectedPaths(plan({ base: files, changes: [{ status: "modified", path: "src/card.ios.ts" }] })), ["/one"]);
assert.deepEqual(selectedPaths(plan({ base: files, changes: [{ status: "modified", path: "src/card.tsx" }] })), []);
assert.deepEqual(selectedPaths(plan({ base: files, platform: "android", changes: [{ status: "modified", path: "src/card.tsx" }] })), ["/one"]);
});
test("with a root baseUrl, a bare specifier that names a project file is a dependency; one that does not is a package", () => {
const tsconfig = JSON.stringify({ compilerOptions: { baseUrl: ".", paths: { "components/*": ["./src/components/*"] } } });
const files = [["tsconfig.json", tsconfig], ["app/one.tsx", 'import theme from "theme"; import { View } from "react-native"; export default () => [theme, View];'],
["app/two.tsx", page], ["theme.ts", "export default 1;"]];
const result = plan({ base: files, changes: [{ status: "modified", path: "theme.ts" }] });
assert.deepEqual(selectedPaths(result), ["/one"]);
assert.deepEqual(result.unresolved, []);
});
test("route additions and removals are independently inventoried at each commit", () => {
const result = plan({base:[["app/removed.tsx",page]],head:[["app/added.tsx",page]]});
assert.deepEqual(selectedPaths(result,"base"), ["/removed"]);
+1 -1
View File
@@ -168,7 +168,7 @@ test("follows the create-expo-app alias @/* -> ./* without a diagnostic", () =>
test("unresolved object hrefs and unsupported custom aliases remain explicit diagnostics", () => {
const result = graph([surface("one"),surface("two")], {
"tsconfig.json": JSON.stringify({compilerOptions:{paths:{"~/*":["src/*"]}}}),
"tsconfig.json": JSON.stringify({compilerOptions:{paths:{"~/*":["src/*","lib/*"]}}}),
"src/app/one.tsx": "import {router} from 'expo-router';import {Screen} from '~/screen';export default function One(){router.push({pathname:getPath()});return <Screen/>;}",
});
assert.deepEqual(result.edges, []);
+31 -3
View File
@@ -1,5 +1,5 @@
import { GitCompareArrows, Keyboard, LayoutGrid, Map, Search } from "lucide-react";
import { type CSSProperties } from "react";
import { type CSSProperties, useLayoutEffect, useState } from "react";
import { Tooltip } from "../shared/tooltip";
import { useCanvasVisibleFrame } from "./visible-frame-provider";
import { CANVAS_NUMBER_KEYS, formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
@@ -29,20 +29,48 @@ type CanvasToolbarProps = {
onOpenShortcuts: () => void;
};
/** Room kept between the toolbar and an Inspector wide enough to reach it. */
const TOOLBAR_PANEL_GAP = 12;
export function CanvasToolbar(props: CanvasToolbarProps) {
const { visibleFrame } = useCanvasVisibleFrame();
// The bar as mounted now: it unmounts while hidden, and its last width is kept for deciding when
// it fits again.
const [element, setElement] = useState<HTMLDivElement | null>(null);
const [ownWidth, setOwnWidth] = useState(0);
useLayoutEffect(() => {
if (!element) return;
const measure = () => setOwnWidth(element.getBoundingClientRect().width);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [element]);
// When responsive panels leave less room than the toolbar itself, hiding it is the only
// collision-free layout. It returns as soon as either panel is collapsed.
if (visibleFrame && visibleFrame.width < TOOLBAR_MINIMUM_FRAME_WIDTH) return null;
// The toolbar is the canvas' persistent mode switcher. Panel geometry may raise it to avoid
// bottom chrome, but must not pull it away from the window's stable horizontal centre.
// bottom chrome, but must not pull it away from the window's stable horizontal centre. Only an
// Inspector that would cover it (widened by the reader, or a narrow window's overlay) pushes it
// left, and by just that much, never past the canvas' left edge: with no room left between the
// two, it hides as it does above.
let shift = 0;
if (visibleFrame && typeof window !== "undefined") {
const centredLeft = window.innerWidth / 2 - ownWidth / 2;
const needed = centredLeft + ownWidth + TOOLBAR_PANEL_GAP - (visibleFrame.x + visibleFrame.width);
const room = centredLeft - (visibleFrame.x + TOOLBAR_PANEL_GAP);
if (needed > 0 && needed > room) return null;
shift = Math.max(0, needed);
}
const style = visibleFrame ? ({
"--canvas-visible-bottom-inset": `calc(100% - ${visibleFrame.y + visibleFrame.height}px)`,
"--canvas-toolbar-shift": `${shift}px`,
} as CSSProperties) : undefined;
const views = CANVAS_VIEW_ORDER;
return (
<div className="canvas-toolbar" role="toolbar" aria-label="Canvas tools" style={style}>
<div ref={setElement} className="canvas-toolbar" role="toolbar" aria-label="Canvas tools" style={style}>
{/* The contents grow with --ui-scale; the bar itself keeps its exact place. */}
<div className="canvas-toolbar-inner">
<div className="toolbar-group" role="group" aria-label="Canvas actions">
@@ -490,9 +490,9 @@
the size a changed screen's is. */
.sidebar-review-off .variant-preview.has-image-ratio { width: min(100%, calc(70dvh * var(--preview-aspect))); }
.sidebar-review-stage {
/* Two frames and a 12px gap share the panel's width. One frame takes the whole width, up to
most of the window's height. */
--compare-frame-height: calc((100cqw - 12px) / 2 / var(--compare-aspect));
/* Two frames and a 12px gap share the panel's width, up to most of the window's height (a wide
panel would otherwise push What changed below the fold). One frame takes the whole width. */
--compare-frame-height: min(calc((100cqw - 12px) / 2 / var(--compare-aspect)), 70dvh);
gap: 12px;
}
.sidebar-review-stage.mode-swipe,
@@ -0,0 +1,169 @@
import {
useCallback, useRef, useSyncExternalStore, type CSSProperties, type KeyboardEvent, type PointerEvent, type RefObject,
} from "react";
import {
clampInspectorWidth, inspectorWidthBounds, INSPECTOR_WIDTH_MAX, INSPECTOR_WIDTH_MIN, INSPECTOR_WIDTH_STEP,
setInspectorWidth, useInspectorWidth,
type InspectorWidthBounds,
} from "../../utils/inspector-width";
/** On the root while the edge is dragged, so the whole page keeps the resize cursor and selects nothing. */
const RESIZING_CLASS = "inspector-resizing";
/** The chrome's zoom (`--ui-scale`): pointer distances are in window pixels, the panel's width in its own. */
function uiScale(): number {
const raw = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--ui-scale"));
return Number.isFinite(raw) && raw > 0 ? raw : 1;
}
/** The panel's width in its own pixels: the reader's, else the stylesheet's default for this window. */
function panelWidth(panel: HTMLElement): number {
return parseFloat(getComputedStyle(panel).width) || 0;
}
function defaultWidth(): number {
return window.matchMedia("(max-width: 1180px)").matches ? 320 : 400;
}
/** The panel's widest and default widths follow the window (and `--ui-scale`, which follows it too). */
function subscribeToWindow(onChange: () => void): () => void {
window.addEventListener("resize", onChange);
return () => window.removeEventListener("resize", onChange);
}
function widestWidth(): number {
return inspectorWidthBounds(window.innerWidth, uiScale()).max;
}
type Drag = {
pointerId: number;
startX: number;
startWidth: number;
scale: number;
bounds: InspectorWidthBounds;
last: number;
/** The panel's own `--inspector-width` before the drag, put back when the drag changes nothing. */
inline: string;
};
/**
* Makes the Inspector's left edge a splitter. A drag moves the edge live (the width is written to
* the panel's `--inspector-width` directly, so nothing re-renders per pointer move) and is kept
* when the pointer lifts; arrow keys move it a step; Home and End take it to its narrowest and
* widest; a double-click returns it to the default.
*/
export function useInspectorResize(panelRef: RefObject<HTMLElement | null>) {
const width = useInspectorWidth();
const widest = useSyncExternalStore(subscribeToWindow, widestWidth, () => INSPECTOR_WIDTH_MAX);
const fallback = useSyncExternalStore(subscribeToWindow, defaultWidth, () => 400);
const drag = useRef<Drag | null>(null);
// Every way a drag can stop ends here, once: the pointer lifting, the browser taking the pointer
// back, the window losing focus, or the edge itself going away (the Inspector closed mid-drag).
const endDrag = useCallback(() => {
const state = drag.current;
if (!state) return;
drag.current = null;
document.documentElement.classList.remove(RESIZING_CLASS);
if (state.last !== state.startWidth) {
setInspectorWidth(state.last);
return;
}
// Nothing changed, so nothing re-renders to replace the width the drag wrote.
const panel = panelRef.current;
if (!panel) return;
if (state.inline) panel.style.setProperty("--inspector-width", state.inline);
else panel.style.removeProperty("--inspector-width");
}, [panelRef]);
const handleRef = useCallback((element: HTMLElement | null) => {
if (!element) return;
window.addEventListener("blur", endDrag);
return () => {
window.removeEventListener("blur", endDrag);
endDrag();
};
}, [endDrag]);
const onPointerDown = (event: PointerEvent<HTMLElement>) => {
const panel = panelRef.current;
if (event.button !== 0 || !panel) return;
const scale = uiScale();
const startWidth = panelWidth(panel);
drag.current = {
pointerId: event.pointerId, startX: event.clientX, startWidth, scale,
bounds: inspectorWidthBounds(window.innerWidth, scale), last: startWidth,
inline: panel.style.getPropertyValue("--inspector-width"),
};
event.currentTarget.setPointerCapture(event.pointerId);
document.documentElement.classList.add(RESIZING_CLASS);
event.preventDefault();
};
const onPointerMove = (event: PointerEvent<HTMLElement>) => {
const state = drag.current;
const panel = panelRef.current;
if (!state || state.pointerId !== event.pointerId || !panel) return;
// A release the handle never heard about.
if (event.buttons === 0) {
endDrag();
return;
}
// The edge is on the left: moving the pointer left widens the panel.
const next = clampInspectorWidth(state.startWidth + (state.startX - event.clientX) / state.scale, state.bounds);
if (next === state.last) return;
state.last = next;
panel.style.setProperty("--inspector-width", `${next}px`);
};
const onPointerEnd = (event: PointerEvent<HTMLElement>) => {
const state = drag.current;
if (!state || state.pointerId !== event.pointerId) return;
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
endDrag();
};
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
const panel = panelRef.current;
if (!panel) return;
const bounds = inspectorWidthBounds(window.innerWidth, uiScale());
const current = panelWidth(panel);
let next: number;
switch (event.key) {
case "ArrowLeft": next = current + INSPECTOR_WIDTH_STEP; break;
case "ArrowRight": next = current - INSPECTOR_WIDTH_STEP; break;
case "Home": next = bounds.min; break;
case "End": next = bounds.max; break;
default: return;
}
event.preventDefault();
event.stopPropagation();
// A key that cannot move the edge (End at a smaller window's cap) keeps the saved width.
next = clampInspectorWidth(next, bounds);
if (next !== Math.round(current)) setInspectorWidth(next);
};
// The saved width is the reader's preference; the panel takes as much of it as this window allows.
const bounds = { min: INSPECTOR_WIDTH_MIN, max: widest };
const shown = width === undefined ? undefined : clampInspectorWidth(width, bounds);
const style = (shown === undefined ? undefined : { "--inspector-width": `${shown}px` }) as CSSProperties | undefined;
const handleProps = {
role: "separator",
"aria-orientation": "vertical",
"aria-label": "Resize inspector",
"aria-valuemin": bounds.min,
"aria-valuemax": bounds.max,
"aria-valuenow": shown ?? fallback,
title: "Drag to resize. Double-click to reset.",
tabIndex: 0,
ref: handleRef,
onPointerDown,
onPointerMove,
onPointerUp: onPointerEnd,
onPointerCancel: onPointerEnd,
onLostPointerCapture: endDrag,
onKeyDown,
onDoubleClick: () => setInspectorWidth(undefined),
} as const;
return { style, handleProps };
}
+6 -1
View File
@@ -14,6 +14,7 @@ import { setOutlinesShown, useOutlinesShown } from "../compare/compare-section";
import { AutoHideScrollArea } from "../shared/auto-hide-scroll-area";
import { usePhoneLayout } from "../../utils/phone-layout";
import { useDragToDismiss } from "../phone/phone-chrome";
import { useInspectorResize } from "./inspector-resize";
type RightPanelProps = {
index: MapIndex;
@@ -36,6 +37,9 @@ export function RightPanel(props: RightPanelProps) {
// On a phone the panel is a bottom sheet; dragging its header down closes it.
const phone = usePhoneLayout();
const drag = useDragToDismiss(props.onToggleCollapsed);
// On a desktop its left edge is a splitter; the sheet keeps the window's width.
const panelRef = useRef<HTMLElement>(null);
const resize = useInspectorResize(panelRef);
const selectedPath = props.screen ? displayPathForScreen(props.screen) : undefined;
const screenDiff = props.screen ? props.diff?.screens.get(props.screen.id) : undefined;
// Compare opens only a screen it reviews: a changed screen in the review order, not a state
@@ -84,7 +88,8 @@ export function RightPanel(props: RightPanelProps) {
// button leads the row instead, away from the screen stepper's arrows. Theme and full screen
// live in the canvas camera controls.
return (
<aside className="right-panel" data-drag-sheet aria-label="Inspector panel">
<aside ref={panelRef} className="right-panel" data-drag-sheet aria-label="Inspector panel" style={phone ? undefined : resize.style}>
{phone ? null : <div className="right-panel-resize" {...resize.handleProps} />}
<header className="right-head" {...(phone ? drag : {})}>
{phone ? <span className="right-sheet-grabber" aria-hidden="true" /> : null}
{phone ? panelButton : null}
+2
View File
@@ -535,6 +535,8 @@
.phone-layout .right-float { display: none; }
/* The Inspector slides up over the whole screen; a drag down on its header puts it away. */
.phone-layout .right-panel {
/* The sheet is the window's width; the desktop's half-window limit is not for it. */
max-width: none;
position: fixed;
z-index: 120;
inset: 0;
+35 -3
View File
@@ -1011,7 +1011,7 @@ code {
border-radius: calc(14px * var(--ui-scale));
background: var(--surface);
box-shadow: var(--floating-chrome-shadow);
transform: translateX(-50%);
transform: translateX(calc(-50% - var(--canvas-toolbar-shift, 0px)));
view-transition-name: canvas-toolbar;
}
.canvas-toolbar-inner { display: flex; align-items: center; gap: 2px; zoom: var(--ui-scale); }
@@ -1118,7 +1118,10 @@ code {
z-index: 100;
display: flex;
flex: none;
width: 400px;
/* The reader's own width when they have dragged the edge (utils/inspector-width.ts), else the
default; never more than half the window, so the canvas keeps the other half. */
width: var(--inspector-width, 400px);
max-width: 50%;
height: 100%;
min-height: 0;
flex-direction: column;
@@ -1130,6 +1133,35 @@ code {
/* Two Diff previews, their 8px gap, and the 14px side insets must fit this same width. */
--inspector-shared-preview-max-width: calc((100cqw - 36px) / 2);
}
/* The panel's left edge is a splitter: a 10px strip over the border, quiet until it is hovered,
dragged or focused, when the border thickens into the accent line. */
.right-panel-resize {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: -5px;
width: 10px;
cursor: col-resize;
touch-action: none;
outline: none;
}
.right-panel-resize::before {
position: absolute;
top: 0;
bottom: 0;
left: 4px;
width: 2px;
background: var(--accent);
content: "";
opacity: 0;
transition: opacity var(--toolbar-motion) var(--toolbar-easing) 120ms;
}
.right-panel-resize:hover::before,
.right-panel-resize:focus-visible::before,
.inspector-resizing .right-panel-resize::before { opacity: 1; transition-delay: 0ms; }
/* While the edge is dragged nothing else may select or change the cursor. */
.inspector-resizing, .inspector-resizing * { cursor: col-resize !important; user-select: none !important; }
/* When minimised, the inspector actions join the camera controls as one floating toolbar. */
.right-float {
position: fixed;
@@ -2343,7 +2375,7 @@ html [data-sonner-toaster][data-sonner-theme] {
@keyframes tooltip-in { from { opacity: 0; } }
@media (max-width: 1180px) {
.right-panel { width: 320px; }
.right-panel { width: var(--inspector-width, 320px); }
}
@media (max-width: 900px) {
+59
View File
@@ -0,0 +1,59 @@
import { useSyncExternalStore } from "react";
import { optionalStorage } from "./embedded-report";
const INSPECTOR_WIDTH_STORAGE_KEY = "expo-explore:inspector-width";
/** Below this the Before/After pair no longer reads; above the maximum the canvas is the one squeezed. */
export const INSPECTOR_WIDTH_MIN = 320;
export const INSPECTOR_WIDTH_MAX = 800;
/** How far one arrow key press moves the panel's edge. */
export const INSPECTOR_WIDTH_STEP = 16;
const listeners = new Set<() => void>();
/** The choice made this visit: storage can be denied (a private window), and the drag must still hold. `null` is a reset. */
let chosen: number | null | undefined;
function parseWidth(value: string | null): number | undefined {
if (value === null) return undefined;
const width = Number(value);
return Number.isFinite(width) && width > 0 ? width : undefined;
}
function stored(): number | undefined {
if (chosen !== undefined) return chosen ?? undefined;
return parseWidth(optionalStorage.getItem(INSPECTOR_WIDTH_STORAGE_KEY));
}
/** Sets the Inspector's width in unscaled CSS pixels, or `undefined` to return to the default, and remembers it where it can. */
export function setInspectorWidth(width: number | undefined) {
chosen = width ?? null;
if (width === undefined) optionalStorage.removeItem(INSPECTOR_WIDTH_STORAGE_KEY);
else optionalStorage.setItem(INSPECTOR_WIDTH_STORAGE_KEY, String(width));
for (const listener of listeners) listener();
}
/** The reader's Inspector width, or `undefined` while the panel keeps its default width. */
export function useInspectorWidth(): number | undefined {
return useSyncExternalStore(
(onChange) => {
listeners.add(onChange);
return () => listeners.delete(onChange);
},
stored,
() => undefined,
);
}
export type InspectorWidthBounds = { min: number; max: number };
/**
* The widths the panel may take in a window `windowWidth` wide: at most half of it, so the canvas
* keeps the other half, in the panel's own (unscaled) pixels when the chrome is zoomed by `scale`.
*/
export function inspectorWidthBounds(windowWidth: number, scale = 1): InspectorWidthBounds {
const half = Math.floor(windowWidth / 2 / (scale > 0 ? scale : 1));
return { min: INSPECTOR_WIDTH_MIN, max: Math.max(INSPECTOR_WIDTH_MIN, Math.min(INSPECTOR_WIDTH_MAX, half)) };
}
export function clampInspectorWidth(width: number, bounds: InspectorWidthBounds): number {
return Math.round(Math.min(bounds.max, Math.max(bounds.min, width)));
}