Compare commits

...
48 changed files with 2369 additions and 679 deletions

No files matched your search

+7 -1
View File
@@ -61,7 +61,13 @@ jobs:
env:
# npm cannot generate provenance for a private repository.
NPM_CONFIG_PROVENANCE: "false"
run: npm publish --access public
VERSION: ${{ steps.version.outputs.version }}
shell: bash
# A prerelease (0.20.0-next.0) goes to the next tag, so latest keeps the last release.
run: |
set -euo pipefail
if [[ "$VERSION" == *-* ]]; then tag=next; else tag=latest; fi
npm publish --access public --tag "$tag"
- name: Tag the release
if: steps.version.outputs.publish == 'true'
env:
+1 -1
View File
@@ -580,7 +580,7 @@ npm test
- `npm test` rebuilds the CLI and the Viewer first, because the node tests run the compiled `dist/`. After one `npm run build`, `npm run test:node` skips the rebuild.
- The agent runtimes and `eas-cli` are optional dependencies that only capture needs. Do not install with `--omit=optional`, which also drops esbuild's platform package.
- To release, bump `version` in `package.json` and merge to main. The [publish workflow](.github/workflows/publish.yml) publishes any version npm does not have yet.
- To release, bump `version` in `package.json` and merge to main. The [publish workflow](.github/workflows/publish.yml) publishes any version npm does not have yet. A prerelease version such as `0.20.0-next.0` goes to the `next` tag, so `latest` stays on the last release.
```sh
npx playwright install chromium
+1 -1
View File
@@ -217,7 +217,7 @@ exploration:
- /c/[channel]
```
An excluded route stays in its neighbors' navigation context (a screen that links to it is still captured when it changes), but neither revision captures it, it is left off the map and the screen counts, and a change to it gets no before/after comparison. A name that matches no route at either compared revision fails the plan with `EXCLUDE_ROUTE_UNKNOWN`; `doctor` warns about it first. Prefer `parameters` or `setup` when a route does show a screen.
An excluded route stays in its neighbors' navigation context (a screen that links to it is still captured when it changes), but neither revision captures it, it is left off the report (the Map, Screens, search and the screen counts), and a change to it gets no before/after comparison. A name that matches no route at either compared revision fails the plan with `EXCLUDE_ROUTE_UNKNOWN`; `doctor` warns about it first. Prefer `parameters` or `setup` when a route does show a screen.
Capture handles iOS's confirmation to open a link in the expected app. After a form submits a password, iOS may offer to save or update it depending on the simulator's AutoFill state; capture declines that prompt with Not Now in both modes, never stores the credential, and records each decision in `capture-diagnostics/system-prompts.jsonl`. Do not script that tap in setup. Include required system-alert handling in setup or app instructions; Explore does not automatically grant application permissions.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@expo/explore",
"version": "0.19.8",
"version": "0.20.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@expo/explore",
"version": "0.19.8",
"version": "0.20.0",
"license": "MIT",
"dependencies": {
"@expo/repack-app": "0.10.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/explore",
"version": "0.19.8",
"version": "0.20.0",
"description": "Source-driven mobile app maps, deterministic CI capture, and visual reviews",
"license": "MIT",
"type": "module",
+73
View File
@@ -0,0 +1,73 @@
import type { PublicReview } from "./capture.js";
import { navigationCaptureContext } from "./navigation-graph.js";
type Surface = PublicReview["surfaces"][number];
type Side = "base" | "head";
/** Navigation is route-level: a secondary-appearance surface (`<id>@<scheme>`) rides on its route's entry. */
const SCHEME_SUFFIX = /@(light|dark)$/;
const routeOf = (id: string): string => id.replace(SCHEME_SUFFIX, "");
/**
* The surfaces a side planned to capture: every route in `all` mode, the changed routes and their navigation context in
* `changes` mode. Undefined without navigation, which leaves no route outside the context.
*/
export function captureContext(review: PublicReview, side: Side): ReadonlySet<string> | undefined {
const navigation = review.navigation?.[side];
if (!navigation) return undefined;
const inventory = review.surfaces.filter((surface) => surface[side]);
const routes = new Map<string, NonNullable<Surface[Side]>>();
for (const surface of inventory) {
const id = routeOf(surface.id);
if (!routes.has(id)) routes.set(id, { ...surface[side]!, id });
}
const selected = new Set(review.mode === "all" ? [...routes.keys()] : navigationCaptureContext(navigation,
inventory.filter((surface) => surface.status !== "unchanged").map((surface) => routeOf(surface.id)),
[...routes.values()]));
return new Set(inventory.filter((surface) => selected.has(routeOf(surface.id))).map((surface) => surface.id));
}
/** Both a screenshot of the planned route and a verified landing on it. */
export function verifiedCapture(surface: Surface, side: Side): boolean {
const outcome = side === "base" ? surface.baseOutcome : surface.headOutcome;
return Boolean(surface[side]?.kind === "screen" && (side === "base" ? surface.baseImage : surface.headImage)
&& outcome?.status === "captured" && outcome.landing === "verified");
}
/**
* Why a side that exists in its revision has no verified capture, as the report's capture gap: `accepted` when the run
* left it uncaptured on purpose (a redirect declaration, a route named in `exploration.exclude`, or a route outside the
* capture context), `open` for anything else, such as a capture that failed. Undefined for a verified capture or an
* absent side. `context` is the side's `captureContext`.
*/
export function captureGap(review: PublicReview, surface: Surface, side: Side,
context: ReadonlySet<string> | undefined): "accepted" | "open" | undefined {
const entry = surface[side];
if (!entry || verifiedCapture(surface, side)) return undefined;
const image = side === "base" ? surface.baseImage : surface.headImage;
const outcome = side === "base" ? surface.baseOutcome : surface.headOutcome;
const outsideCaptureContext = review.mode === "changes" && context !== undefined && !context.has(surface.id);
const deliberate = !image && !outcome && (entry.kind === "redirect" || surface.excluded === true || outsideCaptureContext
|| (!review.navigation?.[side] && review.mode === "changes" && surface.status === "unchanged"));
return deliberate ? "accepted" : "open";
}
/**
* The surfaces the run never captured on purpose: no screenshot of their own on either side, and every side that exists
* left uncaptured deliberately (`captureGap` is `accepted`). None is one of the report's screens. The Viewer leaves them
* out (viewer/src/utils/omitted-screens.ts reaches the same set from the map's gaps), and the PR comment skips them.
* A side with an open gap, such as a failed capture, keeps the surface: its failure is part of the report.
*/
export function neverCapturedSurfaceIds(review: PublicReview): ReadonlySet<string> {
// The Viewer refuses a review whose navigation names a route its inventory lacks; the comment still renders one,
// without a capture context, so no route counts as outside it.
const contextOf = (side: Side) => { try { return captureContext(review, side); } catch { return undefined; } };
const contexts = { base: contextOf("base"), head: contextOf("head") };
const omitted = new Set<string>();
for (const surface of review.surfaces) {
if (surface.baseImage || surface.headImage) continue;
const gaps = (["base", "head"] as const).map((side) => captureGap(review, surface, side, contexts[side]));
if (gaps.includes("accepted") && !gaps.includes("open")) omitted.add(surface.id);
}
return omitted;
}
+8 -3
View File
@@ -5,6 +5,7 @@ import { CI_COMMENT_MARKER } from "./pr-comment.js";
import { CHANGE_GROUPS, MAX_COMMENT_TARGETS, MAX_NAVIGATION_EDGES, MAX_NAVIGATION_NODES, compareTargets, defaultTargetLabel, foldRecord, strongerGroup, historyLine, orderedPrevious, orderedRecords, previousLine, readCommentRecords, recordLabel, recordLine, recordSummary,
type ChangeGroup, type CommentNavigation, type CommentTarget, type CommentRecords, type HistoryEntry, type NavigationGroup, type NavigationKind, type PlatformRecord } from "./pr-comment-record.js";
import { isAccessibilityOnlyChange } from "../contracts/review-validation.js";
import { neverCapturedSurfaceIds } from "../contracts/surface-capture.js";
import type { PublicCaptureHealth, PublicEvidenceSummary } from "../review/evidence-assessment.js";
import type { ReviewPresentation } from "../contracts/review.js";
import type { ViewerLinks } from "./viewer-links.js";
@@ -294,8 +295,10 @@ export function platformRecordOf(state: PublicCommentState, target?: CommentTarg
if (state.review) {
const evidenceBased = state.review.surfaces.some(surface => surface.review);
record.changes = [];
// A route the run never captured on purpose is not one of the report's screens, here as in the Viewer.
const omitted = neverCapturedSurfaceIds(state.review);
for (const surface of state.review.surfaces) {
if ((surface.head ?? surface.base)?.kind === "redirect") continue;
if (omitted.has(surface.id)) continue;
const group = groupOf(surface, evidenceBased);
if (group === "unlisted") continue;
const scheme = schemeOf(surface.id);
@@ -348,9 +351,10 @@ function navigationOf(review: PublicReview, groups: Map<string, ChangeGroup>): C
if (!review.navigation) return undefined;
const keyOf = new Map<string, string>();
const groupOf = new Map<string, NavigationGroup>();
const omitted = neverCapturedSurfaceIds(review);
for (const surface of review.surfaces) {
const route = surface.head ?? surface.base;
if (!route || route.kind === "redirect") continue;
if (!route || omitted.has(surface.id)) continue;
const key = routePattern(route);
keyOf.set(surface.id.replace(/@(light|dark)$/, ""), key);
const group = groups.get(surface.id);
@@ -718,8 +722,9 @@ export function reviewDevice(state: { runtime?: Pick<SimulatorRuntimeMetadata, "
export function reviewChanges(review: PublicReview): Map<string, ChangeGroup> {
const evidenceBased = review.surfaces.some(surface => surface.review);
const changes = new Map<string, ChangeGroup>();
const omitted = neverCapturedSurfaceIds(review);
for (const surface of review.surfaces) {
if ((surface.head ?? surface.base)?.kind === "redirect") continue;
if (omitted.has(surface.id)) continue;
const group = groupOf(surface, evidenceBased);
if (group !== "unlisted") changes.set(surface.id, group);
}
+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;
}
}
}
+97 -9
View File
@@ -1346,7 +1346,7 @@ test("transition thumbnails without a readable screenshot show the variant thumb
assert.deepEqual(errors, []);
});
test("a docs-only report with zero images and no EAS build opens Screens without a visual verdict", async t => {
test("a docs-only report with zero images and no EAS build has no screens to show, and its link to a route says why", async t => {
const report = reportFixture();
report.review.mode = "changes";
report.review.runtime.projectId = "";
@@ -1359,12 +1359,11 @@ test("a docs-only report with zero images and no EAS build opens Screens without
report.assets = [];
const { page, errors } = await harness(t, await archive(report), { app: true });
await expect(page.locator(".app-shell")).toBeVisible();
await page.getByRole("button", { name: "Screens", exact: true }).click();
await expect(page.locator(".screens-page .screens-cell")).toHaveCount(1);
await expect(page.locator(".screens-page .diff-frame.diff-not-compared")).toHaveCount(1);
// The Inspector's missing screenshot matches the canvas node: the icon above a short label and
// the report's reason for the gap, centred in a phone-shaped preview frame.
await page.locator(".screens-page .screen-screenshot-target").click();
// The change reaches no screen, so the one route was never captured: the Map and Screens say so instead of an empty page.
const empty = page.locator(".map-empty");
await expect(empty.getByRole("heading")).toHaveText("No screens were captured");
// The link names /home, and the Inspector says why it has no screenshot: the icon above a short label and the report's
// reason for the gap, centred in a phone-shaped preview frame.
const placeholder = page.locator(".inspector .inspector-preview .screenshot-placeholder");
await expect(placeholder.locator("span")).toHaveText("No screenshot");
await expect(placeholder.locator(".screenshot-placeholder-detail")).toHaveText("Not compared; no capture was recorded");
@@ -1390,10 +1389,98 @@ test("a docs-only report with zero images and no EAS build opens Screens without
await expect(page.locator(".collapsed-change-count")).toHaveCount(0);
await expect(page.locator(".changes-screen-row")).toHaveCount(0);
await expect(page.locator(".diff-frame.diff-modified, .diff-frame.diff-unchanged")).toHaveCount(0);
await page.getByRole("button", { name: "Screens", exact: true }).click();
await expect(empty.getByRole("heading")).toHaveText("No screens were captured");
await expect(page.locator(".screens-cell, .screens-tree-row")).toHaveCount(0);
assert.equal(await page.evaluate(() => window.createdUrls.length), 0);
assert.deepEqual(errors, []);
});
/** A report with Home (modified) and Profile (not compared) captured, a new route named in exploration.exclude, and a redirect. */
function omittedRoutesReport() {
const report = reportFixture();
const home = report.review.surfaces[0];
const route = (id, path, extra = {}) => ({ ...home.head, id, route: path, path, routeFile: `app/${id}.tsx`, logicalPath: `app/${id}.tsx`, ...extra });
const redirect = route("start", "/start", { kind: "redirect", redirectTo: "/home" });
report.review.surfaces.push(
{ id: "profile", status: "unchanged", base: route("profile", "/profile"), head: route("profile", "/profile"),
baseImage: { ...home.baseImage }, headImage: { ...home.headImage }, baseOutcome: { ...home.baseOutcome }, headOutcome: { ...home.headOutcome } },
{ id: "channel", status: "added", excluded: true, base: null, head: route("channel", "/c/[channel]") },
{ id: "start", status: "unchanged", base: { ...redirect }, head: redirect });
return report;
}
test("a public report's excluded route and redirect are not among its screens: Screens, its counts, find, search and the changes leave them out", { timeout: 60_000 }, async t => {
const { page, errors } = await harness(t, await archive(omittedRoutesReport()), { app: true, query: "&screen=home" });
await expect(page.locator(".map-canvas .react-flow__node")).toHaveCount(2);
// The excluded route is new in this change, but it was never captured: it is not a change to review.
const menu = await openChangesMenu(page);
await expect(menu.getByRole("group", { name: "Filter changes" }).getByRole("button")).toHaveText(["Modified 1"]);
await expect(menu.getByText("/c/[channel]")).toHaveCount(0);
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "Screens", exact: true }).click();
const cells = page.locator(".screens-page .screens-cell");
await expect(cells).toHaveCount(2);
await expect(page.locator(".screens-tree-row[data-screen-id]")).toHaveCount(2);
for (const id of ["channel", "start"]) await expect(page.locator(`[data-screen-id="${id}"]`)).toHaveCount(0);
await expect(page.locator(".screens-filter .screens-chip")).toHaveText(["Changed1", "All2"]);
// ← and → step through the two screens and no others.
await page.locator(".screens-page").click({ position: { x: 4, y: 4 } });
await page.keyboard.press("ArrowRight");
await expect(page.locator(".screens-cell .screen-screenshot-card.selected")).toHaveCount(1);
const picked = async () => page.locator(".screens-cell:has(.screen-screenshot-card.selected)").getAttribute("data-screen-id");
const first = await picked();
await page.keyboard.press("ArrowRight");
await expect.poll(picked).not.toBe(first);
const second = await picked();
await page.keyboard.press("ArrowRight");
await expect.poll(picked).toBe(second);
assert.deepEqual([first, second].sort(), ["home", "profile"]);
// `/` finds the report's screens only.
await page.keyboard.press("/");
const find = page.getByRole("searchbox", { name: "Find screens" });
await expect(find).toBeFocused();
for (const query of ["channel", "start"]) {
await find.fill(query);
await expect(page.locator(".screens-find-empty")).toHaveText(`No screens match “${query}”`);
await expect(cells).toHaveCount(0);
}
await find.fill("profile");
await expect(cells).toHaveCount(1);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
// So does the command palette's screen search.
await page.keyboard.press("ControlOrMeta+KeyK");
const palette = page.getByRole("dialog", { name: "Search Explore" });
const box = palette.getByRole("combobox", { name: "Search screens and commands" });
await expect(box).toBeFocused();
await box.fill("/c/");
await expect(palette.getByRole("option")).toHaveCount(0);
await box.fill("/st");
await expect(palette.getByRole("option")).toHaveCount(0);
await box.fill("/pro");
await expect(palette.getByRole("option")).toHaveText([/\/profile/]);
assert.deepEqual(errors, []);
});
test("a link to an excluded route opens it in the Inspector, which says why it has no screenshot, on the Map and on Screens", { timeout: 60_000 }, async t => {
const { page, errors } = await harness(t, await archive(omittedRoutesReport()), { app: true, query: "&screen=channel" });
const detail = page.locator(".inspector .inspector-preview .screenshot-placeholder-detail");
await expect(detail).toHaveText("Excluded by exploration.exclude; never captured");
await expect(page.locator(".map-canvas .react-flow__node")).toHaveCount(2);
await expect(page.locator(".map-canvas .react-flow__node.selected")).toHaveCount(0);
// The same link on Screens, opened afresh: no card is picked, and the Inspector explains the route.
await page.goto(page.url().replace("#/map/", "#/screens/"));
await page.reload();
await expect(page.locator(".screens-page .screens-cell")).toHaveCount(2);
await expect(page.locator(".screens-cell .screen-screenshot-card.selected")).toHaveCount(0);
await expect(detail).toHaveText("Excluded by exploration.exclude; never captured");
assert.deepEqual(errors, []);
});
test("unverified capture diagnostics stay separate from verified Needs review, and source changes nobody compared are not changes", async t => {
const report = reportFixture();
const home = report.review.surfaces[0];
@@ -1507,10 +1594,11 @@ test("a recorded pull-request artifact opens its verified verdicts and every scr
await expect(menu.getByText(route, { exact: true })).toBeVisible();
}
// Its two redirect declarations (/ and /scan/select-photo) were never captured: they are not among its screens.
await page.getByRole("button", { name: "Screens", exact: true }).click();
const frames = page.locator(".screens-page .diff-frame");
await expect(frames).toHaveCount(35);
for (const [status, count] of [["modified", 3], ["added", 1], ["removed", 1], ["unchanged", 28], ["not-compared", 2]]) {
await expect(frames).toHaveCount(33);
for (const [status, count] of [["modified", 3], ["added", 1], ["removed", 1], ["unchanged", 28], ["not-compared", 0]]) {
await expect(page.locator(`.screens-page .diff-frame.diff-${status}`)).toHaveCount(count);
}
const screenshots = page.locator(".screens-page img[data-screenshot-src]");
@@ -188,12 +188,11 @@ test("Map keeps selected elevated arrows behind screenshots without rendering na
await expect(sourceHitArea.locator("title")).toHaveText("Source navigation\npush · app/home.tsx");
await page.mouse.move(1320, 30);
const dimmedComparisons = [];
for (const presentation of ["muted", "selection"]) {
// Only the Changes filter dims a screen; a selection fades nothing.
for (const presentation of ["muted"]) {
await page.evaluate(mode => {
const profile = document.querySelector('.react-flow__node[data-id="profile"]');
const canvas = document.querySelector(".map-canvas");
profile.classList.toggle("graph-node-muted", mode === "muted");
canvas.classList.toggle("screen-selection-active", mode === "selection");
}, presentation);
const dimmedWithArrows = await profileImage.screenshot({ animations: "disabled" });
await page.locator(".map-surface .react-flow__edges").evaluate(node => { node.style.visibility = "hidden"; });
@@ -216,7 +215,6 @@ test("Map keeps selected elevated arrows behind screenshots without rendering na
}
await page.evaluate(() => {
document.querySelector('.react-flow__node[data-id="profile"]').classList.remove("graph-node-muted");
document.querySelector(".map-canvas").classList.remove("screen-selection-active");
});
await page.getByRole("button", { name: "Open Profile", exact: true }).click();
assert.equal(await page.evaluate(() => window.selectedScreen), "profile");
+11 -3
View File
@@ -242,6 +242,14 @@ test("Compare steps through changed screens and their changed areas", { timeout:
await expect(outlines.nth(1)).toHaveClass(/active/);
await page.keyboard.press("k");
await expect(outlines.nth(0)).toHaveClass(/active/);
// Esc in the bottom bar's More menu closes the menu and only the menu.
const more = page.getByRole("button", { name: "More", exact: true });
await more.click();
await expect(page.getByRole("menu", { name: "More" })).toBeVisible();
await page.keyboard.press("Escape");
await expect(page.getByRole("menu", { name: "More" })).toHaveCount(0);
await expect(more).toBeFocused();
await expect(outlines.nth(0)).toHaveClass(/active/);
await page.keyboard.press("Escape");
await expect(compare.locator(".visual-change-outline.active")).toHaveCount(0);
@@ -310,7 +318,7 @@ test("Compare steps through changed screens and their changed areas", { timeout:
/** The Inspector's one frame for a screen outside the review, and its Swipe frame for a changed one, in this viewport. */
async function inspectorFrames(page, url) {
const games = "expo-tabs-games-index-2c6605360b11";
const index = "expo-index-02872ff9f2ca";
const unchanged = "expo-tabs-scan-index-2bbf42237cc6";
const open = async id => {
await page.goto(`${url}#/screens`);
const all = page.getByRole("button", { name: /^All/ }).first();
@@ -325,14 +333,14 @@ async function inspectorFrames(page, url) {
const swipeImage = page.locator(".sidebar-review-stage img").first();
await expect(swipeImage).toBeVisible();
const changed = await swipeImage.boundingBox();
await open(index);
await open(unchanged);
const single = page.locator(".sidebar-review-off .variant-preview");
await expect(single).toBeVisible();
return { changed, single: await single.boundingBox() };
}
test("the Inspector frames an unchanged screen at the size of a changed screen's Swipe frame", { timeout: 90_000 }, async t => {
// / is unchanged (not compared); /games is modified. The single frame used to take at most half the panel, the
// /scan is unchanged; /games is modified. The single frame used to take at most half the panel, the
// width of one frame of a Before/After pair, while Swipe and Flip fill the panel up to 70 % (phone: 52 %) of the window.
for (const viewport of [{ width: 1024, height: 820 }, { width: 390, height: 844 }]) {
const { page, url, errors } = await openReport(t, viewport);
+266
View File
@@ -0,0 +1,266 @@
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 half-window Inspector", () => {
test.use({ viewport: { width: 820, height: 800 } });
/** The widest the panel may be here: the window less the bottom bar and a 12px gap either side. */
async function widestBesideToolbar(page: Page) {
const toolbarBox = (await page.getByRole("toolbar", { name: "Canvas tools" }).boundingBox())!;
return Math.floor(820 - (toolbarBox.width + 2 * 12));
}
async function expectToolbarBesidePanel(page: Page) {
const toolbar = page.getByRole("toolbar", { name: "Canvas tools" });
await expect(toolbar).toBeVisible();
await expect(toolbar.getByRole("button", { name: "More", exact: true })).toBeVisible();
const toolbarBox = (await toolbar.boundingBox())!;
const panelBox = (await panel(page).boundingBox())!;
expect(toolbarBox.x).toBeGreaterThanOrEqual(12 - 1);
expect(toolbarBox.x + toolbarBox.width + 12).toBeLessThanOrEqual(panelBox.x + 1);
}
test("End stops the Inspector where the toolbar still fits beside it, with More in reach", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
const widest = await widestBesideToolbar(page);
// Half the window would be 410; the toolbar needs more of the canvas than that leaves.
expect(widest).toBeLessThan(410);
expect(widest).toBeGreaterThan(320);
await expect(handle(page)).toHaveAttribute("aria-valuemax", String(widest));
await handle(page).focus();
await page.keyboard.press("End");
await expect.poll(() => panelWidth(page)).toBe(widest);
await expect(handle(page)).toHaveAttribute("aria-valuenow", String(widest));
await page.keyboard.press("ArrowLeft");
await expect.poll(() => panelWidth(page)).toBe(widest);
await expectToolbarBesidePanel(page);
// Narrowed again, the toolbar keeps its gap to the panel.
await page.keyboard.press("Home");
await expect.poll(() => panelWidth(page)).toBe(320);
await expectToolbarBesidePanel(page);
});
test("a drag or a saved width stops there too", async ({ page }) => {
await page.goto("/map?screen=area-0-screen-1");
await expect(panel(page)).toBeVisible();
const widest = await widestBesideToolbar(page);
await dragEdge(page, -300);
await expect.poll(() => panelWidth(page)).toBe(widest);
expect(await storedWidth(page)).toBe(String(widest));
await expectToolbarBesidePanel(page);
await page.evaluate((key) => localStorage.setItem(key, "800"), STORAGE_KEY);
await page.reload();
await expect(panel(page)).toBeVisible();
await expect.poll(() => panelWidth(page)).toBe(widest);
await expectToolbarBesidePanel(page);
// A wider window gives the saved width more room again.
await page.setViewportSize({ width: 1280, height: 800 });
await expect.poll(() => panelWidth(page)).toBe(640);
});
});
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);
});
});
});
+624 -283
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
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("the Inspector stops where the canvas keeps the bottom bar's room, never below the minimum", () => {
// 820 - 424 leaves 396, less than half of 820.
assert.deepEqual(inspectorWidthBounds(820, 1, 424), { min: INSPECTOR_WIDTH_MIN, max: 396 });
// In a wide window half of it is the tighter cap.
assert.deepEqual(inspectorWidthBounds(1440, 1, 424), { min: INSPECTOR_WIDTH_MIN, max: 720 });
// The room is in window pixels, the width in the panel's own: (1000 - 530) / 1.25 = 376.
assert.deepEqual(inspectorWidthBounds(1000, 1.25, 530), { min: INSPECTOR_WIDTH_MIN, max: 376 });
assert.deepEqual(inspectorWidthBounds(700, 1, 424), { min: INSPECTOR_WIDTH_MIN, max: INSPECTOR_WIDTH_MIN });
});
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);
});
+13
View File
@@ -796,3 +796,16 @@ test('an excluded route is neither listed nor counted as an app-wide screen', ()
const body = renderPublicComment(state({ review: review([...evidenceReview().surfaces, excluded]) }));
assert.doesNotMatch(body, /\/channel|App-wide source changes|not compared/);
});
test('an excluded route that is new is not one of the changed screens, nor of the ones the list links to', () => {
const screens = Array.from({ length: 11 }, (_, index) => surface(`screen-${index}`, 'modified', { extra: {
review: { status: 'modified', description: `Changed ${index}` },
visual: { verdict: 'modified', reason: 'repeated-cross-build-delta', mismatchPercentage: 1, threshold: 0.1, tool: '[email protected]' },
} }));
const excluded = surface('channel', 'added', { route: '/c/[channel]', extra: { excluded: true } });
for (const key of ['baseImage', 'headImage', 'baseOutcome', 'headOutcome']) delete excluded[key];
const body = renderPublicComment(state({ review: review([...screens, excluded]) }));
assert.equal(titleOf(body), `### 11 screens changed · [Review in Explore](<${reportUrl}>)`);
assert.equal(listOf(body).at(-1), `- [1 more screen in the report](<${reportUrl}>)`);
assert.doesNotMatch(body, /\/c\/\[channel\]/);
});
+162 -7
View File
@@ -13,6 +13,13 @@ const { presentScreensByPath, presentBuildDiff } = await tsImport(
const { artifactUrl, indexMap } = await tsImport("../../viewer/src/utils/model.ts", import.meta.url);
const { primaryScreenshotForScreen } = await tsImport("../../viewer/src/utils/screen-images.ts", import.meta.url);
const { buildObservedGraph, buildViewerGraph, projectFullGraph } = await tsImport("../../viewer/src/utils/graph-model.ts", import.meta.url);
const { omittedScreenIds, omittedSourceScreenIds, reportScreens, withoutOmittedScreens } = await tsImport("../../viewer/src/utils/omitted-screens.ts", import.meta.url);
const { reviewChanges } = await import("../../dist/report/pr-comment-body.js");
const { neverCapturedSurfaceIds } = await tsImport("../../src/contracts/surface-capture.ts", import.meta.url);
const { buildSearchItems } = await tsImport("../../viewer/src/utils/search.ts", import.meta.url);
/** The Map as the Viewer draws a map without a comparison: its own screens, less the ones it never captured. */
const viewerGraph = (map, index = indexMap(map)) => buildViewerGraph(map, index, omittedScreenIds(map));
function entry(id, route, variant = "default", extra = {}) {
return {
@@ -124,10 +131,10 @@ test("source navigation projects directional context and route variants without
assert.equal(payload.coverage.transitions, 0);
for (const collection of ["transitions", "actionAttempts", "journeys"]) assert.deepEqual(payload.map[collection], []);
assert.equal(buildObservedGraph(payload.map, indexMap(payload.map)).groups.length, 0);
const viewerGraph = buildViewerGraph(payload.map, indexMap(payload.map));
assert.deepEqual(viewerGraph.screens.map(screen => screen.id).sort(), ["camera-alias", "games-free", "games-pro", "scan-breed", "scan-mood"]);
assert.equal(viewerGraph.groups.length, 2);
assert.ok(viewerGraph.groups.every(group => group.transitionIds.length === 0 && group.sourceEdges.length > 0));
const graph = viewerGraph(payload.map);
assert.deepEqual(graph.screens.map(screen => screen.id).sort(), ["camera-alias", "games-free", "games-pro", "scan-breed", "scan-mood"]);
assert.equal(graph.groups.length, 2);
assert.ok(graph.groups.every(group => group.transitionIds.length === 0 && group.sourceEdges.length > 0));
const presentation = presentScreensByPath(payload.map);
const scan = presentation.map.screens.find(screen => screen.route === "/scan/instruction");
assert.equal(scan.variantIds.length, 2);
@@ -139,7 +146,7 @@ test("source navigation projects directional context and route variants without
test("public map omits redirects and unselected changes routes while retaining selected failures", () => {
const review = verifyImages(fixture("changes"));
const current = workspaceSides(publicReviewToWorkspace(review)).current;
const graph = buildViewerGraph(current.map, indexMap(current.map));
const graph = viewerGraph(current.map);
assert.deepEqual(graph.screens.map(screen => screen.id).sort(), ["care-guide", "games-free"]);
assert.equal(current.map.screens.length, 7, "the published source inventory remains available");
@@ -149,7 +156,7 @@ test("public map omits redirects and unselected changes routes while retaining s
status: "failed", attempts: 1, landing: "unverified", reason: "Capture failed",
};
const failedMap = workspaceSides(publicReviewToWorkspace(failed)).current.map;
const failedGraph = buildViewerGraph(failedMap, indexMap(failedMap));
const failedGraph = viewerGraph(failedMap);
assert.equal(failedGraph.screens.some(screen => screen.id === "scan-mood"), true);
assert.equal(failedGraph.screens.some(screen => screen.id === "home"), false);
});
@@ -833,7 +840,7 @@ test("an excluded route leaves the map with an accepted gap, like a redirect", (
excluded.excluded = true;
for (const side of ["base", "head"]) { delete excluded[`${side}Image`]; delete excluded[`${side}Outcome`]; }
const { current } = workspaceSides(publicReviewToWorkspace(review));
const graph = buildViewerGraph(current.map, indexMap(current.map));
const graph = viewerGraph(current.map);
assert.equal(graph.screens.some(screen => screen.id === "games-pro"), false, "never captured, so not a card on the map");
assert.ok(current.map.screens.some(screen => screen.id === "games-pro"), "the inventory still knows the route");
const gap = current.map.gaps.find(gap => gap.screenId === "games-pro");
@@ -885,3 +892,151 @@ test("a screen's note is its first open gap of any kind, and an accepted gap onl
assert.equal(indexMap({ ...current.map, gaps: [resolved, accepted] }).screenNotes.get("games-free"), accepted.message);
assert.equal(indexMap({ ...current.map, gaps: [resolved] }).screenNotes.has("games-free"), false);
});
/** What the Viewer leaves out of a review and the comparison it then shows, computed as app.tsx does. */
function viewerOmission(review) {
const workspace = publicReviewToWorkspace(review);
const diff = diffFor(review);
const presentation = presentScreensByPath(diff.map);
const omitted = omittedScreenIds(diff.map, { diff, presentation });
const presented = presentBuildDiff(diff, presentation);
// The surfaces the Viewer leaves out, before path grouping: a removed screen goes back to its surface id.
const removed = new Map(review.surfaces.map(surface => [removedScreenId(workspace.catalog.defaultBaselineBuildId, surface.id), surface.id]));
const surfaces = new Set([...omittedSourceScreenIds(diff.map, diff)].map(id => removed.get(id) ?? id));
return { diff, presentation, omitted, presented, shown: withoutOmittedScreens(presented, omitted), surfaces,
graph: buildViewerGraph(presentation.map, presentation.index, omitted) };
}
test("a public report's never-captured routes are not its screens anywhere; a captured screen and a local map keep theirs", () => {
const review = verifyImages(fixture());
// A new route named in exploration.exclude, and a route that was a redirect and is now a captured screen.
review.surfaces.push({ id: "channel", status: "added", excluded: true, base: null, head: entry("channel", "/c/[channel]") });
const nowCaptured = review.surfaces.find(surface => surface.id === "games-pro");
nowCaptured.status = "modified";
nowCaptured.base = entry("games-pro", "/games", "pro", { kind: "redirect", redirectTo: "/games" });
delete nowCaptured.baseImage; delete nowCaptured.baseOutcome;
const { presentation, presented, omitted, shown, graph } = viewerOmission(review);
assert.equal(presented.screens.get("channel").status, "added", "the comparison alone would count it as a change");
assert.deepEqual([...omitted].sort(), ["channel", "home"], "the excluded route and the redirect; the route captured now stays");
assert.deepEqual(reportScreens(presentation.map.screens, omitted).map(screen => screen.id).sort(),
graph.screens.map(screen => screen.id).sort(), "Screens lists what the Map draws");
assert.deepEqual(buildSearchItems({ screens: reportScreens(presentation.map.screens, omitted) }).filter(item => omitted.has(item.screenId)), []);
assert.deepEqual([...shown.screens.keys()].filter(id => omitted.has(id)), []);
assert.equal(shown.counts.added, presented.counts.added - 1);
assert.equal(shown.counts["not-compared"], presented.counts["not-compared"] - 1);
assert.equal(Object.values(shown.counts).reduce((sum, count) => sum + count, 0), shown.screens.size);
assert.ok(shown.index.screens.has("channel"), "a link to it still opens it");
assert.equal(shown.index.screenNotes.get("channel"), "Excluded by exploration.exclude; never captured");
// A captured route whose excluded variant joins it on one card stays on the Map and in Screens.
const variants = navigationReview();
const pro = variants.surfaces.find(surface => surface.id === "games-pro");
pro.excluded = true;
for (const side of ["base", "head"]) { delete pro[`${side}Image`]; delete pro[`${side}Outcome`]; }
const { current } = workspaceSides(publicReviewToWorkspace(variants));
const family = presentScreensByPath(current.map);
const familyOmitted = omittedScreenIds(current.map, { presentation: family });
const games = family.map.screens.find(screen => screen.route === "/games");
assert.equal(games.variantIds.length, 2);
assert.ok(reportScreens(family.map.screens, familyOmitted).includes(games));
assert.ok(buildViewerGraph(family.map, family.index, familyOmitted).screens.includes(games));
// A local map with the same gaps lists every screen.
const diff = diffFor(review);
const local = { ...diff.map, run: { ...diff.map.run, id: "local-run" } };
assert.equal(omittedScreenIds(local, { diff, presentation: presentScreensByPath(local) }).size, 0);
});
test("an open capture gap keeps a screen that also has an accepted one, from the baseline or from a sibling", () => {
// `/scan/camera` was a redirect and is now a screen whose capture failed: the comparison retargets the baseline's
// accepted redirect gap onto it, beside the head's open failure.
const redirected = verifyImages(fixture());
const camera = redirected.surfaces.find(surface => surface.id === "camera-alias");
camera.status = "modified";
camera.base = entry("camera-alias", "/scan/camera?action=mood", "mood", { kind: "redirect", redirectTo: "/games" });
delete camera.baseImage; delete camera.baseOutcome; delete camera.headImage;
camera.headOutcome = { status: "failed", attempts: 2, landing: "unverified", reason: "timeout" };
const baseline = viewerOmission(redirected);
assert.deepEqual(baseline.diff.map.gaps.filter(gap => gap.screenId === "camera-alias").map(gap => gap.status).sort(), ["accepted", "open"]);
assert.equal(baseline.omitted.has("camera-alias"), false);
assert.equal(baseline.shown.screens.get("camera-alias").status, "unavailable");
assert.equal(baseline.shown.counts.unavailable, 1, "the failed capture is still counted");
assert.ok(baseline.graph.screens.some(screen => screen.id === "camera-alias"));
assert.equal(neverCapturedSurfaceIds(redirected).has("camera-alias"), false);
// `/games` free's capture failed and `/games` pro is excluded: both gaps land on the one `/games` card.
const sibling = verifyImages(fixture());
const pro = sibling.surfaces.find(surface => surface.id === "games-pro");
pro.excluded = true;
for (const side of ["base", "head"]) { delete pro[`${side}Image`]; delete pro[`${side}Outcome`]; }
const free = sibling.surfaces.find(surface => surface.id === "games-free");
delete free.headImage;
free.headOutcome = { status: "failed", attempts: 2, landing: "unverified", reason: "timeout" };
const merged = viewerOmission(sibling);
assert.equal(merged.omitted.has("games-free"), false);
assert.equal(merged.shown.screens.get("games-free").status, "unavailable");
assert.equal(merged.shown.counts.unavailable, 1);
assert.ok(merged.surfaces.has("games-pro"), "the excluded variant itself is still never captured");
assert.equal(merged.surfaces.has("games-free"), false);
});
test("a removed screen keeps its card when the route that replaces it on the same path is a redirect or excluded", () => {
for (const replacement of [
{ kind: "redirect", entry: entry("sweet-bee-new", "/games/sweet-bee", "default", { kind: "redirect", redirectTo: "/games" }) },
{ kind: "excluded", entry: entry("sweet-bee-new", "/games/sweet-bee"), excluded: true },
]) {
const review = verifyImages(fixture());
review.surfaces.push({ id: "sweet-bee-new", status: "added", base: null, head: replacement.entry,
...(replacement.excluded ? { excluded: true } : {}) });
const { omitted, shown, graph, surfaces, presentation } = viewerOmission(review);
const card = presentation.representativeIdByScreenId.get("sweet-bee-new");
assert.equal(omitted.has(card), false, `${replacement.kind}: the removed screen's capture keeps the card`);
assert.ok(shown.screens.get(card)?.beforeScreenshot, `${replacement.kind}: Compare and Changes keep the removed screenshot`);
assert.ok(graph.screens.some(screen => screen.id === card));
assert.ok(surfaces.has("sweet-bee-new"), `${replacement.kind}: the replacement on its own is never captured`);
assert.equal(surfaces.has("sweet-bee"), false);
assert.equal(reviewChanges(review).get("sweet-bee"), "removed", "the comment lists the removal the Viewer shows");
}
});
test("a captured screen that becomes a redirect keeps its card and its screenshot from before", () => {
const review = verifyImages(fixture());
const camera = review.surfaces.find(surface => surface.id === "camera-alias");
camera.status = "modified";
camera.head = entry("camera-alias", "/scan/camera?action=mood", "mood", { kind: "redirect", redirectTo: "/games" });
delete camera.headImage; delete camera.headOutcome;
const { omitted, shown, graph, surfaces } = viewerOmission(review);
assert.equal(omitted.has("camera-alias"), false);
assert.ok(shown.screens.get("camera-alias").beforeScreenshot);
assert.ok(graph.screens.some(screen => screen.id === "camera-alias"));
assert.equal(surfaces.has("camera-alias"), false);
assert.equal(neverCapturedSurfaceIds(review).has("camera-alias"), false);
});
test("the Viewer leaves out exactly the surfaces the PR comment skips", () => {
const review = verifyImages(fixture());
review.surfaces.push(
{ id: "channel", status: "added", excluded: true, base: null, head: entry("channel", "/c/[channel]") },
{ id: "old-start", status: "removed", base: entry("old-start", "/start", "default", { kind: "redirect", redirectTo: "/games" }), head: null },
{ id: "sweet-bee-new", status: "added", base: null, head: entry("sweet-bee-new", "/games/sweet-bee", "default", { kind: "redirect", redirectTo: "/games" }) },
);
const camera = review.surfaces.find(surface => surface.id === "camera-alias");
camera.head = entry("camera-alias", "/scan/camera?action=mood", "mood", { kind: "redirect", redirectTo: "/games" });
camera.status = "modified";
delete camera.headImage; delete camera.headOutcome;
const skipped = neverCapturedSurfaceIds(review);
assert.deepEqual([...skipped].sort(), ["channel", "home", "old-start", "sweet-bee-new"]);
assert.deepEqual([...viewerOmission(review).surfaces].sort(), [...skipped].sort());
const listed = reviewChanges(review);
for (const id of skipped) assert.equal(listed.has(id), false, `${id} is not a listed change`);
assert.equal(listed.get("care-guide"), "added");
assert.equal(listed.get("sweet-bee"), "removed");
const changes = verifyImages(fixture("changes"));
assert.deepEqual([...viewerOmission(changes).surfaces].sort(), [...neverCapturedSurfaceIds(changes)].sort());
const navigated = navigationReview();
assert.deepEqual([...viewerOmission(navigated).surfaces].sort(), [...neverCapturedSurfaceIds(navigated)].sort());
assert.ok(neverCapturedSurfaceIds(navigated).size > 0);
});
+4
View File
@@ -113,6 +113,10 @@ test("the palette's commands follow the canvas: Compare steps changes with the a
assert.ok(!ids(compare).includes("go:compare"));
assert.ok(ids(compare).includes("go:map"));
// Full screen, where the browser has it, prints F; without it there is no command.
assert.equal(commandItems({ ...base, canvas: "map", fullscreen: false }, actions).find((item) => item.id === "command:view:fullscreen").shortcut, "F");
assert.ok(!ids(map).includes("view:fullscreen"));
// A phone has no keyboard shortcuts to list.
assert.ok(ids(map).includes("go:shortcuts"));
assert.ok(!ids(commandItems({ ...base, canvas: "map", phone: true }, actions)).includes("go:shortcuts"));
+8
View File
@@ -70,3 +70,11 @@ test("⌥1–⌥8 open a target by its place, with ⌥ alone; D and ` are plain
assert.ok(matchesShortcut(key("KeyD"), SHORTCUTS.target.menu));
assert.ok(matchesShortcut(key("Backquote"), SHORTCUTS.target.last));
});
test("F is full screen, a plain key: ⌘F stays the browser's find", () => {
assert.equal(formatShortcut(SHORTCUTS.view.fullscreen, true), "F");
assert.ok(matchesShortcut(key("KeyF"), SHORTCUTS.view.fullscreen));
assert.ok(!matchesShortcut(key("KeyF", { metaKey: true }), SHORTCUTS.view.fullscreen));
assert.ok(!matchesShortcut(key("KeyF", { ctrlKey: true }), SHORTCUTS.view.fullscreen));
assert.ok(!matchesShortcut(key("KeyF", { shiftKey: true }), SHORTCUTS.view.fullscreen));
});
+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, []);
+38 -18
View File
@@ -7,12 +7,13 @@ import { isEmbeddedArtifactUrl, leaseEmbeddedArtifactUrl, optionalStorage, viewe
import { REPORT_SOURCE } from "./utils/report-source";
import { CanvasToolbar } from "./components/canvas/toolbar";
import { CanvasCameraControls } from "./components/canvas/camera-controls";
import { MoreMenu } from "./components/canvas/more-menu";
import { CanvasVisibleFrameProvider } from "./components/canvas/visible-frame-provider";
import { AppLoading } from "./components/shared/app-loading";
import { ReportLoadingShell } from "./components/shared/report-loading-shell";
import { screenLabel } from "./utils/screen-path";
import { AppPill, PLATFORM_NAMES, runTargets, siblingReportUrl, targetSwitch } from "./components/panels/app-pill";
import { useFullscreen } from "./components/panels/shell-actions";
import { fullscreenSupported, useFullscreen } from "./components/panels/shell-actions";
import { getCanvasZoomState, runCanvasZoomCommand } from "./utils/canvas-zoom";
import { commandItems, suggestedCommands } from "./utils/commands";
import { changedScreens, focusCounts as countFocusStatuses, isCapturedChange, type ChangedScreen } from "./utils/changed-screens";
@@ -72,6 +73,7 @@ import {
isBlackBoxMap,
} from "./utils/graph-model";
import { buildSearchItems, suggestedSearchItems } from "./utils/search";
import { omittedScreenIds, reportScreens, withoutOmittedScreens } from "./utils/omitted-screens";
import {
presentBuildDiff,
presentScreensByPath,
@@ -383,11 +385,8 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
const revisionRef = useRef<{ runId: string; revision: number } | undefined>(undefined);
const pollingRef = useRef(false);
const theme = themePreference === "system" ? preferredSystemTheme : themePreference;
// Auto → Dark → Light → Auto, as the button's tooltip spells out.
const toggleTheme = useCallback(() => {
setThemePreference(current => current === "system" ? "dark" : current === "dark" ? "light" : "system");
}, []);
// The T key flips what is on screen, dark to light and back; only the button returns to Auto.
// The T key flips what is on screen, dark to light and back; only the More menu's theme switch
// (or the palette) returns to Auto.
const flipTheme = useCallback(() => {
setThemePreference(current => (current === "system" ? preferredSystemTheme : current) === "dark" ? "light" : "dark");
}, [preferredSystemTheme]);
@@ -1043,6 +1042,10 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
setHandoffOpen(true);
} else if (matchesShortcut(event, SHORTCUTS.appearance.theme)) {
flipTheme();
} else if (matchesShortcut(event, SHORTCUTS.view.fullscreen)) {
// The More menu and the palette offer full screen only where the browser has it.
if (phoneRef.current || !fullscreenSupported()) return;
toggleFullscreen();
} else if (matchesShortcut(event, SHORTCUTS.appearance.app)) {
// Only a report captured in both schemes has another appearance to show.
const { options, current } = appearanceRef.current;
@@ -1064,7 +1067,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
return () => {
window.removeEventListener("keydown", onKeyDown);
};
}, [chooseAppearance, clearSelectedScreen, flipTheme, navigate, searchOpen, selectCanvas, toggleRightPanel]);
}, [chooseAppearance, clearSelectedScreen, flipTheme, navigate, searchOpen, selectCanvas, toggleFullscreen, toggleRightPanel]);
// A side-panel row or a deep link is a "go to": the camera fits that screen and the step is
// kept. Screens inventory clicks only select in place; Map clicks also focus the chosen screen. Repeating a selected target refits it without adding history.
@@ -1196,11 +1199,18 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
() => (reviewedMap ? presentScreensByPath(reviewedMap) : undefined),
[reviewedMap],
);
// A route the report never captured is not one of its screens, so the comparison names it nowhere (omitted-screens.ts).
const omittedIds = useMemo(
() => (reviewedMap && screenPresentation
? omittedScreenIds(reviewedMap, { diff: sourceDiff, presentation: screenPresentation })
: new Set<string>()),
[reviewedMap, screenPresentation, sourceDiff],
);
const diff = useMemo(
() => (sourceDiff && screenPresentation
? presentBuildDiff(sourceDiff, screenPresentation)
? withoutOmittedScreens(presentBuildDiff(sourceDiff, screenPresentation), omittedIds)
: undefined),
[screenPresentation, sourceDiff],
[omittedIds, screenPresentation, sourceDiff],
);
// The Screens page says which screens changed in an appearance other than the one shown.
const changedElsewhere = useMemo(() => {
@@ -1220,7 +1230,9 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
comparison: filterComparisonAppearance(wholeComparison, otherScope),
...(wholeReview ? { review: filterReviewAppearance(wholeReview, otherScope) } : {}),
});
const presented = presentBuildDiff(otherDiff, presentScreensByPath(otherDiff.map));
const otherPresentation = presentScreensByPath(otherDiff.map);
const presented = withoutOmittedScreens(presentBuildDiff(otherDiff, otherPresentation),
omittedScreenIds(otherDiff.map, { diff: otherDiff, presentation: otherPresentation }));
for (const [id, entry] of presented.screens) {
if (["modified", "added", "removed"].includes(entry.status)) changed.set(id, [...(changed.get(id) ?? []), option]);
}
@@ -1258,9 +1270,10 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
: !baseline ? "This report has no baseline build to compare against."
: !diff ? "The baseline is still loading."
: "No screen looks different from the baseline.";
// Search finds the report's screens, as Screens lists them; a link to one it never captured still opens it.
const searchIndex = useMemo(
() => map ? buildSearchItems({ screens: map.screens }) : [],
[map],
() => map ? buildSearchItems({ screens: reportScreens(map.screens, omittedIds) }) : [],
[map, omittedIds],
);
const openChangedScreen = useCallback((screenId: string) => {
const current = routeRef.current;
@@ -1574,7 +1587,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
theme: themePreference,
appearances: appearances.length > 1 ? appearances.map((option) => ({ id: option, label: appearanceLabel(option), current: option === appearance })) : [],
inspector: phone || comparingScreens ? undefined : { open: !rightCollapsed },
fullscreen: !phone && typeof document.documentElement.requestFullscreen === "function" ? fullscreen : undefined,
fullscreen: !phone && fullscreenSupported() ? fullscreen : undefined,
targets: (() => {
const run = runTargets(map.run);
const noun = run.targets.every((target) => target.id === target.platform) ? "platform" as const : "device" as const;
@@ -1632,6 +1645,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
index={index}
diff={diff}
routeFiles={routeFiles}
omittedScreenIds={omittedIds}
changedElsewhere={changedElsewhere}
selectedScreenId={selectedScreenId}
{...(focusRequest ? { focusRequest } : {})}
@@ -1684,6 +1698,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
direction="TB"
focus={focusFilter}
projectionFitKey={mapProjectionFitKey}
omittedScreenIds={omittedIds}
{...(diff ? { diff } : {})}
{...(selectedScreenId ? { selectedScreenId } : {})}
{...(focusRequest ? { focusRequest } : {})}
@@ -1692,10 +1707,8 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
/>
)}
</div>
{phone ? null : (
<CanvasCameraControls inspectorCollapsed={comparing ? false : rightCollapsed} theme={theme} themePreference={themePreference} onToggleTheme={toggleTheme}
camera={route.canvas === "map"} />
)}
{/* Top right holds the camera only, so only the Map has anything there. */}
{phone || route.canvas !== "map" ? null : <CanvasCameraControls />}
{phone ? (
<PhoneTabBar
canvas={route.canvas}
@@ -1706,7 +1719,13 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
canvas={route.canvas}
searchOpen={searchOpen}
{...(handoffAction ? { actions: handoffAction } : {})}
onOpenShortcuts={() => setShortcutsOpen(true)}
more={<MoreMenu
themePreference={themePreference}
onChangeTheme={setThemePreference}
{...(fullscreenSupported() ? { fullscreen: { active: fullscreen, onToggle: toggleFullscreen } } : {})}
{...(comparingScreens ? {} : { inspector: { open: !rightCollapsed, onToggle: toggleRightPanel } })}
onOpenShortcuts={() => setShortcutsOpen(true)}
/>}
onSelectCanvas={selectCanvas}
onOpenSearch={() => setSearchOpen(true)}
/>}
@@ -1714,6 +1733,7 @@ const ViewerApp = memo(function ViewerApp({ reportKey }: { reportKey: number })
{shortcutsOpen ? (
<ShortcutsDialog
context={{ canvas: route.canvas, review: reviewingInSidebar, hasChanges: compareOrder.length > 0, handoff: Boolean(handoffInput), appearances: appearances.length > 1,
fullscreen: !phone && fullscreenSupported(),
...(switchTargets ? { targets: switchTargets } : {}) }}
onClose={() => setShortcutsOpen(false)}
/>
@@ -6,20 +6,9 @@ import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
import { KeyHint } from "../shared/key-hint";
import { Menu, type MenuItem } from "../shared/menu";
import { Tooltip } from "../shared/tooltip";
import { FullscreenToggleButton, ThemeToggleButton, type ShellActionsProps, type ShellTheme } from "../panels/shell-actions";
import { useCanvasVisibleFrame } from "./visible-frame-provider";
import { setFollowSelection, useFollowSelection } from "../../utils/follow-selection";
type CanvasCameraControlsProps = {
/** Makes room for the collapsed inspector controls at the window edge. */
inspectorCollapsed: boolean;
theme: ShellTheme;
themePreference: ShellActionsProps["themePreference"];
onToggleTheme: () => void;
/** Fit, center and zoom act on a canvas; a page (Screens) or Compare shows only the page actions. */
camera?: boolean;
};
const CAMERA_CONTROLS_MINIMUM_FRAME_WIDTH = 240;
function ZoomControl() {
@@ -114,11 +103,11 @@ function RecenterControl() {
}
/**
* Camera actions belong to the canvas, not to either inspector panel. The page-level theme and
* full screen actions share the toolbar, so it stays in one place whether the inspector is open
* or not.
* Camera actions belong to the canvas, not to either inspector panel: fit, center and the zoom
* level, top right on the Map. Screens and Compare have no camera, so nothing renders there; the
* page-wide theme and full screen live in the bottom bar's "More" menu.
*/
export function CanvasCameraControls({ inspectorCollapsed, theme, themePreference, onToggleTheme, camera = true }: CanvasCameraControlsProps) {
export function CanvasCameraControls() {
const { visibleFrame } = useCanvasVisibleFrame();
if (visibleFrame && visibleFrame.width < CAMERA_CONTROLS_MINIMUM_FRAME_WIDTH) return null;
const style = visibleFrame ? ({
@@ -126,24 +115,12 @@ export function CanvasCameraControls({ inspectorCollapsed, theme, themePreferenc
} as CSSProperties) : undefined;
return (
<div
className={`canvas-camera-controls${inspectorCollapsed ? " inspector-collapsed" : ""}`}
style={style}
role="group"
aria-label="Canvas camera controls">
<div className="canvas-camera-controls" style={style} role="group" aria-label="Canvas camera controls">
<div className="canvas-camera-controls-inner">
{camera ? (
<>
<FitControl />
<span className="camera-control-divider" aria-hidden="true" />
<RecenterControl />
<span className="camera-control-divider" aria-hidden="true" />
<ZoomControl />
<span className="camera-control-divider" aria-hidden="true" />
</>
) : null}
<ThemeToggleButton theme={theme} themePreference={themePreference} onToggleTheme={onToggleTheme} className="camera-action-button" />
<FullscreenToggleButton className="camera-action-button" />
<FitControl />
<RecenterControl />
<span className="camera-control-divider" aria-hidden="true" />
<ZoomControl />
</div>
</div>
);
+180
View File
@@ -0,0 +1,180 @@
import { useCallback, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, Ellipsis, Keyboard, Maximize, Minimize, Monitor, Moon, PanelRight, Sun } from "lucide-react";
import { Menu } from "../shared/menu";
import { Tooltip } from "../shared/tooltip";
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
import type { ThemePreference } from "../../utils/navigation";
const THEME_OPTIONS: { id: ThemePreference; label: string; title: string; icon: ReactNode }[] = [
{ id: "system", label: "Auto", title: "Auto (system)", icon: <Monitor /> },
{ id: "light", label: "Light", title: "Light", icon: <Sun /> },
{ id: "dark", label: "Dark", title: "Dark", icon: <Moon /> },
];
export type MoreMenuProps = {
themePreference: ThemePreference;
onChangeTheme: (theme: ThemePreference) => void;
/** Full screen's state and toggle; left out where the browser has no full screen. */
fullscreen?: { active: boolean; onToggle: () => void } | undefined;
/** The Inspector's state and toggle; left out where there is no Inspector (Compare). */
inspector?: { open: boolean; onToggle: () => void } | undefined;
onOpenShortcuts: () => void;
};
/**
* The bottom bar's last button: the page-wide settings that have no place on a canvas. Every row
* reads the same way, icon, label, control and key: the Viewer's theme (Auto, Light, Dark; T
* flips light and dark), full screen (F), the Inspector (I) and the keyboard shortcuts (?).
*/
export function MoreMenu(props: MoreMenuProps) {
const [open, setOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLDivElement>(null);
// The menu opens on the current theme, as a choice menu opens on its current choice.
const currentThemeRef = useRef<HTMLButtonElement>(null);
const themeLabelId = useId();
const close = useCallback(() => setOpen(false), []);
// ↑ and ↓ move between rows (the theme row's stop is its current choice), ← and → between the
// three themes. Tab leaves the menu, as it does a native one. The menu's keys are its own: Esc
// and the arrows are marked used, so a canvas behind it (Compare's screens and areas) leaves them.
// ? opens the shortcuts as the row does, so the dialog hands focus back to More.
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const list = listRef.current;
if (!list) return;
if (event.key === "Tab") {
close();
return;
}
if (event.key === "Escape") {
event.preventDefault();
close();
return;
}
if (event.key === "?" && !event.metaKey && !event.ctrlKey && !event.altKey) {
event.preventDefault();
close();
props.onOpenShortcuts();
return;
}
const active = document.activeElement as HTMLElement | null;
if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
const radios = [...list.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
const at = active ? radios.indexOf(active) : -1;
if (at < 0) return;
radios[(at + (event.key === "ArrowRight" ? 1 : -1) + radios.length) % radios.length]?.focus();
return;
}
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const rows = [...list.querySelectorAll<HTMLElement>("[data-more-row]")];
if (rows.length === 0) return;
const at = rows.findIndex((row) => active && row.contains(active));
const next = event.key === "Home" ? 0
: event.key === "End" ? rows.length - 1
: (Math.max(at, event.key === "ArrowDown" ? -1 : 0) + (event.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length;
const row = rows[next];
const stop = row?.matches('[role="menuitem"], [role="menuitemcheckbox"]') ? row
: row?.querySelector<HTMLElement>('[aria-checked="true"]') ?? row?.querySelector<HTMLElement>('[role="menuitemradio"]');
stop?.focus();
};
return (
<>
<Tooltip label="More" placement="top" disabled={open}>
<button
ref={buttonRef}
type="button"
className={`toolbar-button${open ? " active" : ""}`}
aria-label="More"
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen((current) => !current)}>
<Ellipsis />
</button>
</Tooltip>
<Menu open={open} anchorRef={buttonRef} initialFocusRef={currentThemeRef} align="end" className="more-menu" onDismiss={close}>
<div ref={listRef} className="more-menu-list" role="menu" aria-label="More" onKeyDown={onKeyDown}>
<div className="more-menu-row" role="group" aria-labelledby={themeLabelId} data-more-row>
<span className="more-menu-icon" aria-hidden="true"><Moon /></span>
<span className="more-menu-label" id={themeLabelId}>Theme</span>
<span className="more-theme-switch">
{THEME_OPTIONS.map((option) => {
const checked = props.themePreference === option.id;
return (
<button
key={option.id}
ref={checked ? currentThemeRef : undefined}
type="button"
className="more-theme-option"
role="menuitemradio"
aria-checked={checked}
aria-label={option.label}
title={option.title}
tabIndex={-1}
onClick={() => props.onChangeTheme(option.id)}>
{option.icon}
</button>
);
})}
</span>
<kbd className="more-menu-key" aria-hidden="true">{formatShortcut(SHORTCUTS.appearance.theme)}</kbd>
</div>
{props.fullscreen ? (
<button
type="button"
className="more-menu-row more-menu-item"
role="menuitem"
tabIndex={-1}
aria-keyshortcuts={SHORTCUTS.view.fullscreen.key}
data-more-row
onClick={() => {
props.fullscreen?.onToggle();
close();
}}>
<span className="more-menu-icon" aria-hidden="true">{props.fullscreen.active ? <Minimize /> : <Maximize />}</span>
<span className="more-menu-label">{props.fullscreen.active ? "Exit full screen" : "Full screen"}</span>
<kbd className="more-menu-key" aria-hidden="true">{formatShortcut(SHORTCUTS.view.fullscreen)}</kbd>
</button>
) : null}
{props.inspector ? (
<button
type="button"
className="more-menu-row more-menu-item"
role="menuitemcheckbox"
aria-checked={props.inspector.open}
tabIndex={-1}
aria-keyshortcuts={SHORTCUTS.panel.right.key}
data-more-row
onClick={() => {
props.inspector?.onToggle();
close();
}}>
<span className="more-menu-icon" aria-hidden="true"><PanelRight /></span>
<span className="more-menu-label">Inspector</span>
{props.inspector.open ? <span className="more-menu-check" aria-hidden="true"><Check /></span> : null}
<kbd className="more-menu-key" aria-hidden="true">{formatShortcut(SHORTCUTS.panel.right)}</kbd>
</button>
) : null}
<button
type="button"
className="more-menu-row more-menu-item"
role="menuitem"
tabIndex={-1}
aria-haspopup="dialog"
aria-keyshortcuts="?"
data-more-row
onClick={() => {
close();
props.onOpenShortcuts();
}}>
<span className="more-menu-icon" aria-hidden="true"><Keyboard /></span>
<span className="more-menu-label">Keyboard shortcuts</span>
<kbd className="more-menu-key" aria-hidden="true">?</kbd>
</button>
</div>
</Menu>
</>
);
}
@@ -31,8 +31,8 @@ export type ScreenScreenshotCardProps = {
loading?: "eager" | "lazy";
leading?: ReactNode;
trailing?: ReactNode;
/** Where the "Open in Inspector" tooltip sits: away from the route heading, which is above the screenshot on the Map. */
tooltipPlacement?: "top" | "bottom";
/** Say "Open in Inspector" in a tooltip over the screenshot (Screens). The Map's cards go without. */
inspectorTooltip?: boolean;
/** Short lines about the screen, inside the card after its screenshot (Screens: how it was reached, where else it changed). */
note?: ReactNode;
onClick: MouseEventHandler<HTMLButtonElement>;
@@ -92,10 +92,10 @@ export function ScreenScreenshotCard(props: ScreenScreenshotCardProps) {
free of block children. */}
<span className="screen-screenshot-slot">
{props.leading}
{/* With a pointer, what a click does is said once, zoom-independent, in the shared tooltip
after its usual delay; the selected screen is already in the Inspector. The button has
no title of its own, so no native tooltip joins it; the heading names the screen. */}
<Tooltip label="Open in Inspector" placement={props.tooltipPlacement ?? "top"} disabled={Boolean(props.selected)}>
{/* On Screens, with a pointer, what a click does is said once in the shared tooltip after
its usual delay; the selected screen is already in the Inspector. The button has no
title of its own, so no native tooltip joins it; the heading names the screen. */}
<Tooltip label="Open in Inspector" placement="top" disabled={props.inspectorTooltip === false || Boolean(props.selected)}>
<button
type="button"
className="screen-screenshot-target"
+44 -12
View File
@@ -1,7 +1,8 @@
import { GitCompareArrows, Keyboard, LayoutGrid, Map, Search } from "lucide-react";
import { type CSSProperties } from "react";
import { GitCompareArrows, LayoutGrid, Map, Search } from "lucide-react";
import { type CSSProperties, useLayoutEffect, useState } from "react";
import { Tooltip } from "../shared/tooltip";
import { useCanvasVisibleFrame } from "./visible-frame-provider";
import { setToolbarRoom } from "../../utils/inspector-width";
import { CANVAS_NUMBER_KEYS, formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
import { KeyHint } from "../shared/key-hint";
import {
@@ -26,23 +27,59 @@ type CanvasToolbarProps = {
actions?: React.ReactNode;
onSelectCanvas: (canvas: CanvasView) => void;
onOpenSearch: () => void;
onOpenShortcuts: () => void;
/** The bar's last button: the "More" menu with theme, full screen and keyboard shortcuts. */
more: React.ReactNode;
};
/** 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]);
// The Inspector stops short of covering the bar: it may widen only as far as leaves the canvas
// room for the bar and a gap either side.
useLayoutEffect(() => {
if (ownWidth > 0) setToolbarRoom(ownWidth + 2 * TOOLBAR_PANEL_GAP);
}, [ownWidth]);
// 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.
// collision-free layout. It returns as soon as either panel is collapsed. The Inspector's width is
// capped to leave the bar its room, so this is a last resort: a desktop window (820px and up)
// always fits the bar beside the narrowest Inspector.
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, which the Inspector's cap keeps from happening.
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">
@@ -96,12 +133,7 @@ export function CanvasToolbar(props: CanvasToolbarProps) {
<span className="toolbar-divider" aria-hidden="true" />
<Tooltip label="Keyboard shortcuts" shortcut="?" placement="top">
<button type="button" className="toolbar-button" aria-label="Keyboard shortcuts"
aria-haspopup="dialog" onClick={props.onOpenShortcuts}>
<Keyboard />
</button>
</Tooltip>
{props.more}
</div>
</div>
);
@@ -12,7 +12,8 @@ export type TransitionEdgeData = {
transitionCount: number;
active: boolean;
primary: boolean;
dimmed: boolean;
/** Another screen is selected: the edge steps back to a hairline, so the selection's own stand out. */
quiet: boolean;
sourceOnly?: boolean;
previousSource?: boolean;
tooltip?: string;
@@ -39,9 +40,10 @@ export function TransitionEdge(props: EdgeProps<TransitionGraphEdge>) {
curvature: 0.24,
});
const emphasized = Boolean(props.data?.active || props.selected || hovered);
const dimmed = Boolean(props.data?.dimmed && !emphasized);
const quiet = Boolean(props.data?.quiet && !emphasized);
const stroke = emphasized
? "var(--accent)"
: quiet ? "var(--border-subtle)"
: props.data?.previousSource ? "var(--danger)" : props.data?.primary ? "var(--graph-line)" : "var(--graph-line-soft)";
return (
@@ -66,9 +68,8 @@ export function TransitionEdge(props: EdgeProps<TransitionGraphEdge>) {
style={{
...props.style,
stroke,
strokeWidth: emphasized ? 2.2 : props.data?.primary ? 1.15 : 0.9,
strokeWidth: emphasized ? 2.5 : quiet ? 1 : props.data?.primary ? 1.15 : 0.9,
strokeDasharray: props.data?.sourceOnly ? "6 5" : emphasized || props.data?.primary ? undefined : "4 7",
opacity: dimmed ? 0.12 : 1,
}}
/>
</>
@@ -107,6 +107,13 @@ export function ZoomBridge(props: {
publishZoom(Math.round(zoom * 100) / 100);
}, [props.cameraReady, zoom]);
// What a stroke that must stay legible at any zoom divides by (the Map's selection ring). It
// moves in quarter-octave steps, so a pinch restyles the canvas a few times, not every frame.
const strokeZoom = 2 ** (Math.round(Math.log2(zoom) * 4) / 4);
useEffect(() => {
canvas?.style.setProperty("--canvas-zoom", String(strokeZoom));
}, [canvas, strokeZoom]);
useEffect(() => {
// Re-registering after selection changes publishes the new capability to the zoom menu.
// Reading through getNodes keeps the commands themselves on the latest canvas snapshot.
@@ -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,
@@ -19,6 +19,8 @@ export type ShortcutContext = {
handoff?: boolean;
/** The report was captured in both light and dark, so the app's appearance can be switched. */
appearances?: boolean;
/** The browser can put the Viewer in full screen. */
fullscreen?: boolean;
/** The run's other targets are one switch away; the pill calls them devices, or platforms in reports from before targets. */
targets?: { noun: "device" | "platform"; count: number };
};
@@ -94,6 +96,7 @@ export function shortcutGroups(context: ShortcutContext): Group[][] {
...(context.canvas === "compare" ? [] : [{ label: "Show or hide the inspector", keys: [SHORTCUTS.panel.right] }]),
{ label: "Viewer theme: dark or light", keys: [SHORTCUTS.appearance.theme] },
...(context.appearances ? [{ label: "The app's appearance: light or dark", keys: [SHORTCUTS.appearance.app] }] : []),
...(context.fullscreen ? [{ label: "Enter or exit full screen", keys: [SHORTCUTS.view.fullscreen] }] : []),
{ label: "Show this list", keys: ["?"] },
],
};
@@ -119,7 +122,7 @@ export function shortcutGroups(context: ShortcutContext): Group[][] {
return [here, [goTo, view]];
}
/** The keyboard reference, opened with "?" or the button at the end of the bottom bar. */
/** The keyboard reference, opened with "?" or from the More menu at the end of the bottom bar. */
export function ShortcutsDialog(props: { context: ShortcutContext; onClose: () => void }) {
const dialogRef = useModalDialog(true, props.onClose);
useEffect(() => {
@@ -0,0 +1,183 @@
import {
useCallback, useRef, useSyncExternalStore, type CSSProperties, type KeyboardEvent, type PointerEvent, type RefObject,
} from "react";
import {
clampInspectorWidth, getToolbarRoom, inspectorWidthBounds, INSPECTOR_WIDTH_MAX, INSPECTOR_WIDTH_MIN, INSPECTOR_WIDTH_STEP,
setInspectorWidth, subscribeToToolbarRoom, 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);
}
/** The widest the panel can be now: it follows the window, `--ui-scale` and the bottom bar's width. */
function currentBounds(): InspectorWidthBounds {
return inspectorWidthBounds(window.innerWidth, uiScale(), getToolbarRoom());
}
function subscribeToBounds(onChange: () => void): () => void {
const unsubscribeToolbar = subscribeToToolbarRoom(onChange);
const unsubscribeWindow = subscribeToWindow(onChange);
return () => {
unsubscribeToolbar();
unsubscribeWindow();
};
}
function widestWidth(): number {
return currentBounds().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(subscribeToBounds, 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: currentBounds(), 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 = currentBounds();
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 };
}
+15 -19
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef } from "react";
import { GitCompareArrows, PanelRight, ScanSearch, X } from "lucide-react";
import { GitCompareArrows, ScanSearch, X } from "lucide-react";
import { Tooltip } from "../shared/tooltip";
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
import { InspectorPanel } from "./inspector";
@@ -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
@@ -55,36 +59,28 @@ export function RightPanel(props: RightPanelProps) {
if (scrollRef.current) scrollRef.current.scrollTop = 0;
}, [screenId]);
// Collapsed, the panel icon brings the Inspector back; open, an X closes it.
// Closed, the Inspector leaves no button behind: a selection, Return or I opens it. Open, an X
// closes it.
if (props.collapsed) return null;
const panelButton = (
<Tooltip
label={props.collapsed ? "Expand inspector" : "Close inspector"}
shortcut={formatShortcut(SHORTCUTS.panel.right)}
placement="bottom-end">
<Tooltip label="Close inspector" shortcut={formatShortcut(SHORTCUTS.panel.right)} placement="bottom-end">
<button
type="button"
className="icon-button"
aria-label={props.collapsed ? "Expand inspector" : "Close inspector"}
aria-expanded={!props.collapsed}
aria-label="Close inspector"
aria-expanded
onClick={props.onToggleCollapsed}>
{props.collapsed ? <PanelRight aria-hidden="true" /> : <X aria-hidden="true" />}
<X aria-hidden="true" />
</button>
</Tooltip>
);
if (props.collapsed) {
return (
<div className="right-float" role="toolbar" aria-label="Canvas actions">
{panelButton}
</div>
);
}
// One header row: the screen's status and path, then the close button. On a phone the close
// button leads the row instead, away from the screen stepper's arrows. Theme and full screen
// live in the canvas camera controls.
// live in the bottom bar's "More" menu.
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}
+13 -60
View File
@@ -1,25 +1,18 @@
import { useEffect, useState } from "react";
import { Maximize, Minimize, Moon, Sun, SunMoon } from "lucide-react";
import { Tooltip } from "../shared/tooltip";
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
import type { ThemePreference } from "../../utils/navigation";
export type ShellTheme = "light" | "dark";
export type ShellActionsProps = {
/** The theme on screen: the preference, or the system's when that is Auto. */
theme: ShellTheme;
themePreference: ThemePreference;
/** Steps Auto → Dark → Light → Auto. */
onToggleTheme: () => void;
/** The host toolbar's button class, so the actions match their neighbours. */
className?: string;
};
import { useCallback, useEffect, useState } from "react";
function fullscreenActive(): boolean {
return typeof document !== "undefined" && document.fullscreenElement !== null;
}
/**
* Whether this browser can put the page in full screen at all: iPhone Safari has no element full
* screen, and a frame that was not allowed it (an embedded Viewer) refuses every request.
*/
export function fullscreenSupported(): boolean {
return typeof document !== "undefined" && typeof document.documentElement.requestFullscreen === "function"
&& document.fullscreenEnabled !== false;
}
/** Tracks the page-level fullscreen state, including exits triggered by the browser itself. */
export function useFullscreen(): [boolean, () => void] {
const [active, setActive] = useState(fullscreenActive);
@@ -30,54 +23,14 @@ export function useFullscreen(): [boolean, () => void] {
return () => document.removeEventListener("fullscreenchange", sync);
}, []);
const toggle = () => {
const toggle = useCallback(() => {
if (document.fullscreenElement) {
void document.exitFullscreen().catch(() => {});
return;
}
if (typeof document.documentElement.requestFullscreen !== "function") return;
if (!fullscreenSupported()) return;
void document.documentElement.requestFullscreen().catch(() => {});
};
}, []);
return [active, toggle];
}
const THEME_LABELS: Record<ThemePreference, string> = {
system: "Theme: Auto (system)",
dark: "Theme: Dark",
light: "Theme: Light",
};
/** The theme button shows the current preference; a press steps Auto → Dark → Light. */
export function ThemeToggleButton(props: ShellActionsProps) {
const Icon = props.themePreference === "system" ? SunMoon : props.themePreference === "dark" ? Moon : Sun;
return (
<Tooltip label={THEME_LABELS[props.themePreference]} shortcut={formatShortcut(SHORTCUTS.appearance.theme)} placement="bottom">
<button
type="button"
className={props.className ?? "icon-button"}
aria-label="Toggle theme"
data-theme-preference={props.themePreference}
onClick={props.onToggleTheme}>
<Icon aria-hidden="true" />
</button>
</Tooltip>
);
}
export function FullscreenToggleButton(props: Pick<ShellActionsProps, "className">) {
const [active, toggle] = useFullscreen();
const label = active ? "Exit full screen" : "Enter full screen";
return (
<Tooltip label={label} placement="bottom">
<button
type="button"
className={props.className ?? "icon-button"}
aria-label={label}
aria-pressed={active}
onClick={toggle}>
{active ? <Minimize aria-hidden="true" /> : <Maximize aria-hidden="true" />}
</button>
</Tooltip>
);
}
+2 -2
View File
@@ -531,10 +531,10 @@
.changes-menu .panel-search-clear { width: 44px; height: 44px; }
/* The minimap repeats what a phone already shows whole, and covers a sixth of it. */
.phone-layout .canvas-minimap-shell { display: none; }
/* With nothing selected there is no Inspector to reopen. */
.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;
+18 -1
View File
@@ -237,12 +237,29 @@ export function Menu({ items = [], children, initialFocusRef, open, ariaLabel, c
if (initialFocusRef && event.target instanceof Node
&& !popoverRef.current?.contains(event.target) && !anchorRef?.current?.contains(event.target)) dismissRef.current();
};
// A trigger can also move with no scroll or resize, as the bottom bar does when the Inspector
// opens beside it; an anchored menu checks where its trigger is once a frame while it is open.
let frame = 0;
let anchorAt = "";
const follow = () => {
const rect = anchorRef?.current?.getBoundingClientRect();
const at = rect ? `${rect.left},${rect.top}` : "";
if (at !== anchorAt) {
if (anchorAt) place();
anchorAt = at;
}
frame = requestAnimationFrame(follow);
};
window.addEventListener("pointerdown", onPointerDown);
window.addEventListener("keydown", onKeyDown);
window.addEventListener("resize", place);
if (anchorRef) window.addEventListener("scroll", onScroll, true);
if (anchorRef) {
window.addEventListener("scroll", onScroll, true);
follow();
}
window.addEventListener("focusin", onFocusIn);
return () => {
cancelAnimationFrame(frame);
window.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("resize", place);
@@ -0,0 +1,22 @@
import type { ExploreMap } from "../../utils/model";
/**
* The Map and Screens with no screen to show. A run that observed none says what stopped it; a public report whose routes
* were all deliberately left uncaptured (omitted-screens.ts) says so, rather than showing an empty page.
*/
export function NoScreens(props: { map: ExploreMap }) {
const recorded = props.map.screens.length > 0;
const blockers = props.map.gaps.filter((gap) => gap.status === "open" && !gap.screenId).map((gap) => gap.message);
return (
<div className="graph-canvas canvas-empty">
<div className="page-empty compact-empty map-empty" role="status">
<h2>{recorded ? "No screens were captured" : "No screens were recorded"}</h2>
{recorded
? <p>Every route in this report is a redirect, is named in exploration.exclude, or is outside what the change reaches.</p>
: blockers.length > 0
? blockers.map((message) => <p key={message}>{message}</p>)
: <p>The run ended before any screen of the app was observed.</p>}
</div>
</div>
);
}
+17 -9
View File
@@ -12,7 +12,9 @@ import { shortcutsLive } from "../../utils/shortcuts";
import { normalizeSearchText } from "../../utils/search";
import { createKeyHold } from "../../utils/key-hold";
import { placeholderScreen } from "../../utils/map-frame";
import { reportScreens } from "../../utils/omitted-screens";
import { ScreenScreenshotCard } from "../canvas/screen-screenshot-card";
import { NoScreens } from "../shared/no-screens";
import { useCanvasVisibleFrame } from "../canvas/visible-frame-provider";
import { PhoneSheet } from "../phone/phone-chrome";
import { PanelSearch } from "../shared/panel-search";
@@ -33,6 +35,8 @@ export type ScreensViewProps = {
/** The other appearances each screen changed in, when the report captured several. */
changedElsewhere?: ReadonlyMap<string, Appearance[]> | undefined;
selectedScreenId?: string | undefined;
/** The routes a public report never captured: not listed, counted or found, as on the Map (omitted-screens.ts). */
omittedScreenIds?: ReadonlySet<string> | undefined;
/** A request (search, the Changes menu) to bring a screen into view; a new key asks again for the same screen. */
focusRequest?: FocusRequest | undefined;
/** The Changes menu's status filter: screens outside it are dimmed, as on the Map. */
@@ -269,19 +273,21 @@ function Legend(props: { others: Appearance[] }) {
* phone, a section per route folder (or per tab, when there are no route files), with the tree behind a Tree button.
*/
export function ScreensView(props: ScreensViewProps) {
// The report's screens, as the Map draws them: a public report's routes it never captured are not among them.
const screens = useMemo(() => reportScreens(props.map.screens, props.omittedScreenIds ?? new Set()), [props.map.screens, props.omittedScreenIds]);
const tree: ScreenTree = useMemo(
() => screenTree(props.map.screens, props.index, props.routeFiles),
[props.index, props.map.screens, props.routeFiles],
() => screenTree(screens, props.index, props.routeFiles),
[props.index, screens, props.routeFiles],
);
const typicalSize = useMemo(
() => typicalScreenshotSize(props.map.screens.map(screen => screenshotSize(primaryScreenshotForScreen(screen, props.index)))),
[props.index, props.map.screens],
() => typicalScreenshotSize(screens.map(screen => screenshotSize(primaryScreenshotForScreen(screen, props.index)))),
[props.index, screens],
);
const changedIds = useMemo(
() => new Set(props.map.screens
() => new Set(screens
.filter(screen => isChanged(props.diff, screen.id) || (props.changedElsewhere?.get(screen.id)?.length ?? 0) > 0)
.map(screen => screen.id)),
[props.changedElsewhere, props.diff, props.map.screens],
[props.changedElsewhere, props.diff, screens],
);
const [filter, setFilter] = useState<Filter>(props.phone && changedIds.size > 0 ? "changed" : "all");
const [treeOpen, setTreeOpen] = useState(false);
@@ -290,9 +296,9 @@ export function ScreensView(props: ScreensViewProps) {
const [query, setQuery] = useState("");
// The phone layout has no field to show or clear a query, so a query typed on desktop does not narrow it.
const findQuery = findOpen && !props.phone ? query : "";
const matches = useMemo(() => findMatches(props.map.screens, props.index, findQuery), [props.index, props.map.screens, findQuery]);
const matches = useMemo(() => findMatches(screens, props.index, findQuery), [props.index, screens, findQuery]);
const inChanged = filter === "changed" && changedIds.size > 0;
const inFilter = inChanged ? changedIds : new Set(props.map.screens.map(screen => screen.id));
const inFilter = inChanged ? changedIds : new Set(screens.map(screen => screen.id));
const shown = matches ? new Set([...inFilter].filter(id => matches.has(id))) : inFilter;
const sections = tree.sections
.map(section => ({ ...section, screenIds: section.screenIds.filter(id => shown.has(id)) }))
@@ -406,7 +412,7 @@ export function ScreensView(props: ScreensViewProps) {
setFilter(value);
}}>
{value === "changed" ? "Changed" : "All"}
<span className="screens-chip-count">{value === "changed" ? changedIds.size : props.map.screens.length}</span>
<span className="screens-chip-count">{value === "changed" ? changedIds.size : screens.length}</span>
</button>
))}
</div>
@@ -563,6 +569,8 @@ export function ScreensView(props: ScreensViewProps) {
? ({ "--screens-right-inset": `calc(100% - ${visibleFrame.x + visibleFrame.width}px)` } as CSSProperties)
: undefined;
if (screens.length === 0) return <NoScreens map={props.map} />;
const cell = (id: string) => {
const screen = props.index.screens.get(id);
return screen ? (
+45 -34
View File
@@ -8,6 +8,7 @@ import {
} from "../canvas/stage";
import type { ProjectionMotionMetadata } from "../canvas/projection-motion";
import { ScreenScreenshotCard } from "../canvas/screen-screenshot-card";
import { NoScreens } from "../shared/no-screens";
import { TransitionEdge, type TransitionGraphEdge } from "../canvas/transition-edge";
import {
buildViewerGraph,
@@ -31,6 +32,7 @@ import { arrowsOwnedBy, mapKeyDirection, mapKeyEntry, mapKeyTarget, type MapKeyD
import { createKeyHold } from "../../utils/key-hold";
const HOVER_CLEAR_DELAY = 180;
const PRESSABLE = 'button, a, summary, [role="button"]';
const MAP_LAYOUT_REVISION = "flat-v1";
const MAP_FIT_VIEW_OPTIONS = {
padding: 0.04,
@@ -115,8 +117,8 @@ function ScreenNodeCard({ data, selected }: NodeProps<ScreenGraphNode>) {
imageHeight={data.screenshotSize?.imageHeight ?? data.frame.screen.height}
placeholderSize={data.frame.screen}
loading="lazy"
// The route heads the card, so the tooltip goes below it.
tooltipPlacement="bottom"
// The ring says which screen is which; a click opening it in the Inspector needs no tooltip.
inspectorTooltip={false}
leading={<Handle type="target" position={horizontal ? Position.Left : Position.Top} className="graph-handle" />}
trailing={<Handle type="source" position={horizontal ? Position.Right : Position.Bottom} className="graph-handle" />}
onMouseEnter={() => data.onHover(data.screen.id)}
@@ -342,8 +344,9 @@ function projectionElements(
const edges: TransitionGraphEdge[] = structure.groups.map((group) => {
const hierarchyEdge = structure.primaryEdgeKeys.has(group.key);
const connected = group.from === selectedScreenId || group.to === selectedScreenId;
const dimmed = false;
const active = connected;
// While a screen is selected, every other transition quiets to a hairline; cards never fade.
const quiet = Boolean(selectedScreenId) && !connected;
const sourceOnly = group.transitionIds.length === 0 && Boolean(group.sourceEdges?.length);
const previousSource = group.sourceRevision === "baseline";
const removed = previousSource || (!group.synthetic && diff?.screens.get(group.to)?.status === "removed");
@@ -356,25 +359,26 @@ function projectionElements(
const primary = hierarchyEdge;
const stroke = active
? "var(--accent)"
: quiet ? "var(--border-subtle)"
: removed ? "var(--danger)" : primary ? "var(--graph-line)" : "var(--graph-line-soft)";
return {
id: edgeElementId(group.key),
source: group.from,
target: group.to,
type: "transition",
className: `${hierarchyEdge ? "graph-edge-primary" : "graph-edge-secondary"}${sourceOnly ? " graph-edge-source" : ""}${previousSource ? " graph-edge-source-baseline" : ""}${active ? " graph-edge-active" : ""}${dimmed ? " graph-edge-dimmed" : ""}`,
className: `${hierarchyEdge ? "graph-edge-primary" : "graph-edge-secondary"}${sourceOnly ? " graph-edge-source" : ""}${previousSource ? " graph-edge-source-baseline" : ""}${active ? " graph-edge-active" : ""}${quiet ? " graph-edge-quiet" : ""}`,
markerEnd: {
type: MarkerType.ArrowClosed,
width: active || hierarchyEdge ? 14 : 11,
height: active || hierarchyEdge ? 14 : 11,
width: active || (hierarchyEdge && !quiet) ? 14 : 11,
height: active || (hierarchyEdge && !quiet) ? 14 : 11,
color: stroke,
},
style: {
stroke,
strokeWidth: active ? 2.2 : hierarchyEdge ? 1.15 : 0.9,
strokeWidth: active ? 2.5 : quiet ? 1 : hierarchyEdge ? 1.15 : 0.9,
strokeDasharray: !hierarchyEdge && !active && !removed ? "4 7" : undefined,
},
data: { label, transitionCount: group.transitionIds.length, active, primary, dimmed, sourceOnly, previousSource, ...(tooltip ? { tooltip } : {}) },
data: { label, transitionCount: group.transitionIds.length, active, primary, quiet, sourceOnly, previousSource, ...(tooltip ? { tooltip } : {}) },
// React Flow renders a positive edge z-index above root nodes. Keep every connection in
// the base edge layer so selected/highlighted paths still pass behind screen imagery.
zIndex: 0,
@@ -433,7 +437,7 @@ function sameTransitionEdge(a: TransitionGraphEdge, b: TransitionGraphEdge) {
&& a.data?.transitionCount === b.data?.transitionCount
&& a.data?.active === b.data?.active
&& a.data?.primary === b.data?.primary
&& a.data?.dimmed === b.data?.dimmed;
&& a.data?.quiet === b.data?.quiet;
}
function reuseUnchangedElements(
@@ -477,7 +481,11 @@ type BaseCanvasProps = {
onSelectScreen: (id: string, options?: { replace?: boolean }) => void;
onClearSelection?: () => void;
};
export type MapViewProps = BaseCanvasProps & { projectionFitKey?: number };
export type MapViewProps = BaseCanvasProps & {
projectionFitKey?: number;
/** The routes a public report never captured: not drawn (omitted-screens.ts). */
omittedScreenIds?: ReadonlySet<string> | undefined;
};
function ConnectionCanvas(props: MapViewProps) {
const surfaceRef = useRef<HTMLDivElement>(null);
@@ -490,7 +498,10 @@ function ConnectionCanvas(props: MapViewProps) {
});
const previousLayout = useRef<{ nodes: CanvasGraphNode[]; edges: TransitionGraphEdge[] } | undefined>(undefined);
const observedGraph = useMemo(() => buildViewerGraph(props.map, props.index), [props.index, props.map]);
const observedGraph = useMemo(
() => buildViewerGraph(props.map, props.index, props.omittedScreenIds),
[props.index, props.map, props.omittedScreenIds],
);
const projection = useMemo(() => projectFullGraph(observedGraph), [observedGraph]);
const structure = useMemo(
() => projectedStructure(projection, props.index, isBlackBoxMap(props.map)),
@@ -557,7 +568,8 @@ function ConnectionCanvas(props: MapViewProps) {
}, [applyHover]);
// The arrow keys (or h j k l) walk the map from the selected screen: along an edge in the
// layout's flow, across to the neighbour on the same rank otherwise. With nothing selected they
// enter the map at its edge, as on the Screens page. A held key keeps walking.
// enter the map at its edge, as on the Screens page. A held key keeps walking. Return opens the
// selection in the Inspector.
const { selectedScreenId } = props;
const selectedRef = useRef(selectedScreenId);
selectedRef.current = selectedScreenId;
@@ -568,22 +580,39 @@ function ConnectionCanvas(props: MapViewProps) {
if (!structure) return undefined;
return from ? mapKeyTarget(structure, from, direction) : mapKeyEntry(structure, direction);
};
// A click leaves the keyboard focus on the clicked screen's button, where Return would press it
// and open that screen again. A walk lets go of it, so Return reaches the screen walked to.
const walkTo = (id: string) => {
const focused = document.activeElement;
if (focused instanceof HTMLElement && surfaceRef.current?.contains(focused)) focused.blur();
selectScreen(id);
};
const onKeyDown = (event: KeyboardEvent) => {
hold.interrupt(event);
if (event.repeat && hold.holding(event.code)) { event.preventDefault(); return; }
if (event.defaultPrevented || !shortcutsLive(event) || arrowsOwnedBy(event.target)) return;
if (event.key === "Enter") {
// A focused button or link keeps its own Return; elsewhere on the page it opens the selection.
const target = event.target instanceof Element ? event.target : null;
const selected = selectedRef.current;
if (!selected || event.isComposing || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
if (target && target !== document.body && (target.closest(PRESSABLE) || !surfaceRef.current?.contains(target))) return;
event.preventDefault();
selectScreen(selected);
return;
}
const direction = mapKeyDirection(event);
if (!direction) return;
if (!structureRef.current) return;
event.preventDefault();
let at = move(direction, selectedRef.current);
if (!at) return;
selectScreen(at);
walkTo(at);
hold.begin(event.code, () => {
const target = move(direction, at);
if (!target) return false;
at = target;
selectScreen(target);
walkTo(target);
return true;
});
};
@@ -636,30 +665,12 @@ function ConnectionCanvas(props: MapViewProps) {
.sort((left, right) => left.depth - right.depth || left.y - right.y || left.x - right.x || left.index - right.index)
.map(({ id }) => id), [layout.nodes]);
const phone = usePhoneLayout();
const selectedScreenVisible = Boolean(
props.selectedScreenId && layout.nodes.some((node) => node.id === props.selectedScreenId),
);
if (props.map.screens.length === 0) {
const blockers = props.map.gaps.filter((gap) => gap.status === "open" && !gap.screenId).map((gap) => gap.message);
return (
<div className="graph-canvas canvas-empty">
<div className="page-empty compact-empty map-empty">
<h2>No screens were recorded</h2>
{blockers.length > 0
? blockers.map((message) => <p key={message}>{message}</p>)
: <p>The run ended before any screen of the app was observed.</p>}
</div>
</div>
);
}
if (observedGraph.screens.length === 0) return <NoScreens map={props.map} />;
return (
<div ref={surfaceRef} className="connection-canvas-surface map-surface">
<CanvasStage
ariaLabel="Screen map"
className={[
"map-canvas",
selectedScreenVisible ? "screen-selection-active" : "",
].filter(Boolean).join(" ")}
className="map-canvas"
nodes={layout.nodes}
edges={layout.edges}
nodeTypes={NODE_TYPES}
+6 -15
View File
@@ -24,7 +24,7 @@ export function reportContractGap(gap: ReviewContractGap): void {
console.warn(`Explore report: ${where} failed the review contract (${gap.message}); ${gap.dropped} omitted.`);
}
import { sourceImpactSentences } from "../../../src/contracts/source-change";
import { navigationCaptureContext } from "../../../src/contracts/navigation-graph";
import { captureContext, captureGap, verifiedCapture } from "../../../src/contracts/surface-capture";
import { projectSourceNavigation } from "../utils/source-navigation";
type Side = "base" | "head";
@@ -89,12 +89,6 @@ function unattributedSummary(surface: Surface, side: Side): string {
return "destination unverified";
}
function verifiedCapture(surface: Surface, side: Side): boolean {
const outcome = side === "base" ? surface.baseOutcome : surface.headOutcome;
return Boolean(surface[side]?.kind === "screen" && imageFor(surface, side)
&& outcome?.status === "captured" && outcome.landing === "verified");
}
function comparisonReview(surface: Surface): Surface["review"] {
if (surface.status === "added" || surface.status === "removed") {
return surface.review?.status === surface.status ? surface.review : undefined;
@@ -217,10 +211,7 @@ function sidePayload(review: PublicReview, side: Side): { map: ExploreMap; cover
const id = routeOf(surface.id);
if (!routes.has(id)) routes.set(id, { ...surface[side]!, id });
}
const selectedRoutes = navigation ? new Set(review.mode === "all" ? [...routes.keys()] : navigationCaptureContext(navigation,
inventory.filter(surface => surface.status !== "unchanged").map(surface => routeOf(surface.id)),
[...routes.values()])) : undefined;
const selected = selectedRoutes ? new Set(inventory.filter(surface => selectedRoutes.has(routeOf(surface.id))).map(surface => surface.id)) : undefined;
const selected = captureContext(review, side);
// Planned structural groups describe the full inventory, including routes outside the
// capture budget. Keep their placeholders available in every canvas.
const declared = inventory;
@@ -356,11 +347,11 @@ function sidePayload(review: PublicReview, side: Side): { map: ExploreMap; cover
screenshotArtifactId: artifact.id,
});
}
if (!verifiedCapture(surface, side)) {
const outcome = side === "base" ? surface.baseOutcome : surface.headOutcome;
// The gap's status is the one the PR comment reads too (surface-capture.ts), so both leave out the same routes.
const gap = captureGap(review, surface, side, selected);
if (gap) {
const outsideCaptureContext = review.mode === "changes" && selected !== undefined && !selected.has(surface.id);
const deliberatelyOmitted = !image && !outcome && (entry.kind === "redirect" || surface.excluded === true || outsideCaptureContext
|| (!navigation && review.mode === "changes" && surface.status === "unchanged"));
const deliberatelyOmitted = gap === "accepted";
map.gaps.push({
id: `capture:${side}:${surface.id}`,
screenId: surface.id,
+152 -108
View File
@@ -110,7 +110,6 @@
/* How far an item the Changes filter does not cover falls back. Low enough to read as
background at a glance, high enough that the canvas keeps its shape. */
--dim-out: 0.35;
--hover-neighbour-frame: color-mix(in srgb, var(--accent) 55%, var(--border-subtle));
--shadow-xs: 0 1px 3px rgba(0, 0, 0, 0.025), 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 10px 20px rgba(0, 0, 0, 0.1), 0 3px 6px rgba(0, 0, 0, 0.05);
@@ -134,13 +133,10 @@
--icon-hit-min: 32px;
/* Chevrons, carets and status glyphs that sit inline next to text. */
--icon-glyph-inline: 14px;
/* Floating canvas chrome shares a y=30px center line. The collapsed inspector joins the
camera controls into one compact toolbar. Reserve space for the visible actions only. */
/* Floating canvas chrome shares a y=30px center line. Reserve space for the visible actions only. */
--floating-chrome-top: 14px;
--floating-chrome-height: 42px;
--canvas-chrome-inline-inset: 12px;
--right-float-edge: 12px;
--right-float-width: calc(var(--icon-btn-md) + 6px);
--left-collapsed-pill-width: 420px;
--left-collapsed-pill-height: var(--floating-chrome-height);
--left-collapsed-pill-top: var(--floating-chrome-top);
@@ -305,16 +301,14 @@ code {
}
:root[data-canvas-transition-direction]::view-transition-group(app-pill),
:root[data-canvas-transition-direction]::view-transition-group(canvas-camera-controls),
:root[data-canvas-transition-direction]::view-transition-group(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-group(right-floating-controls) {
:root[data-canvas-transition-direction]::view-transition-group(canvas-toolbar) {
z-index: 101;
animation: none;
}
:root[data-canvas-transition-direction]::view-transition-image-pair(canvas-minimap),
:root[data-canvas-transition-direction]::view-transition-image-pair(app-pill),
:root[data-canvas-transition-direction]::view-transition-image-pair(canvas-camera-controls),
:root[data-canvas-transition-direction]::view-transition-image-pair(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-image-pair(right-floating-controls) {
:root[data-canvas-transition-direction]::view-transition-image-pair(canvas-toolbar) {
isolation: isolate;
}
:root[data-canvas-transition-direction]::view-transition-old(canvas-view-content),
@@ -326,9 +320,7 @@ code {
:root[data-canvas-transition-direction]::view-transition-old(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-old(phone-top-actions),
:root[data-canvas-transition-direction]::view-transition-new(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-new(phone-top-actions),
:root[data-canvas-transition-direction]::view-transition-old(right-floating-controls),
:root[data-canvas-transition-direction]::view-transition-new(right-floating-controls) {
:root[data-canvas-transition-direction]::view-transition-new(phone-top-actions) {
mix-blend-mode: normal;
}
:root[data-canvas-transition-direction="forward"]::view-transition-old(canvas-view-content) {
@@ -351,15 +343,13 @@ code {
}
:root[data-canvas-transition-direction]::view-transition-old(app-pill),
:root[data-canvas-transition-direction]::view-transition-old(canvas-camera-controls),
:root[data-canvas-transition-direction]::view-transition-old(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-old(right-floating-controls) {
:root[data-canvas-transition-direction]::view-transition-old(canvas-toolbar) {
animation: none;
opacity: 0;
}
:root[data-canvas-transition-direction]::view-transition-new(app-pill),
:root[data-canvas-transition-direction]::view-transition-new(canvas-camera-controls),
:root[data-canvas-transition-direction]::view-transition-new(canvas-toolbar),
:root[data-canvas-transition-direction]::view-transition-new(right-floating-controls) {
:root[data-canvas-transition-direction]::view-transition-new(canvas-toolbar) {
animation: none;
opacity: 1;
}
@@ -461,6 +451,8 @@ code {
--graph-line-soft: #c5c7ce;
/* One flat fill for a group — no border, no second tone inside it. */
--canvas-group: #f5f5f6;
/* The ring a hovered Map card takes: a step past the border scale, short of the connectors. */
--hover-ring: #b9bbc6;
color: var(--text);
background: var(--screen);
}
@@ -480,6 +472,7 @@ code {
--graph-line: #696e77;
--graph-line-soft: #3f4349;
--canvas-group: #18191b;
--hover-ring: #5a6169;
}
/* The canvas is a fixed map: dragging anywhere pans, while clicking an object selects it. */
.graph-canvas .canvas-tool-pan,
@@ -499,27 +492,14 @@ code {
.graph-canvas .transition-edge-hitarea { cursor: pointer; pointer-events: stroke; }
.graph-canvas .transition-edge-path { transition: stroke 100ms ease, stroke-width 100ms ease, opacity 140ms ease; }
.graph-canvas .graph-edge-secondary { opacity: 0.72; }
.graph-canvas .graph-edge-dimmed { opacity: 0.14; }
.graph-canvas .graph-edge-active { opacity: 1; }
.graph-canvas .react-flow__node { transition: opacity 180ms ease, filter 180ms ease; }
.graph-canvas .canvas-focus-animating .react-flow__node { transition: none; }
/* Focus: what the chosen state does not cover only steps back, so the map is still readable. */
.graph-canvas .react-flow__node.graph-node-muted { opacity: var(--dim-out); --map-card-opacity: var(--dim-out); }
/* A route-selected screenshot stays visually anchored while the surrounding screenshots recede.
They fade as focus dims them, by opacity alone: a filter would grey the card's opaque backing.
Summary cards retain their normal contrast so the selected screen's semantic context is legible. */
.map-canvas.screen-selection-active .react-flow__node-screen:not(.selected) {
opacity: var(--dim-out);
--map-card-opacity: var(--dim-out);
}
.map-canvas.screen-selection-active .react-flow__node-screen:not(.selected):hover,
.map-canvas.screen-selection-active .react-flow__node-screen:not(.selected):focus-within {
opacity: 1;
--map-card-opacity: 1;
}
/* Hover never recedes anything, but where focus or a selection has already dimmed the map, the
hovered screen and the screens it connects to come back up, with the transitions between them,
so the neighbourhood reads. These come after both dimming rules so the pointer's context wins. */
/* Hover never recedes anything, but where the Changes filter has dimmed the map, the hovered
screen and the screens it connects to come back up, with the transitions between them, so the
neighbourhood reads. These come after the dimming rule so the pointer's context wins. */
.connection-canvas-surface.canvas-hovering .react-flow__node-screen.graph-node-hover-related {
opacity: 1;
--map-card-opacity: 1;
@@ -687,7 +667,7 @@ code {
/* Hover and selection draw a 3px ring in the accent colour: the 1px border recoloured plus a 2px
shadow outside it, so the image keeps its size (a thicker border would shrink the picture inside
its box). Changed screens keep their own colour at the same weight: the diff rules below win on
specificity. */
specificity. The Map leaves the border to the status and rings the card from outside instead. */
.screen-node-image:hover img,
.screen-screenshot-card.selected .screen-node-image img { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent); }
.screen-node-image:hover > .image-placeholder,
@@ -707,8 +687,8 @@ code {
border-radius: 17px;
pointer-events: none;
}
/* Selection needs no ring: the canvas dims every other screen. The highlight ring stays for the
transient pointer-over state that panels project onto the canvas. */
/* Selection needs no overlay: the Map rings the screenshot and Screens frames the card. The
highlight ring stays for the transient pointer-over state that panels project onto the canvas. */
.canvas-active-frame.is-highlighted::after {
border-color: var(--accent);
box-shadow: 0 0 24px color-mix(in srgb, var(--accent) 24%, transparent);
@@ -723,10 +703,9 @@ code {
pointer-events: none;
}
/* A screen's handles are ports on its frame: they take the frame colour, whether that is the
status colour of a changed screen or the accent of a hovered or selected one, and a ring in
the canvas colour keeps them legible as connection points on the border. */
status colour of a changed screen or the accent of a selected one, and a ring in the canvas
colour keeps them legible as connection points on the border. */
.screen-screenshot-card { --screen-frame: var(--graph-line); }
.screen-screenshot-card:has(.screen-node-image:hover),
.screen-screenshot-card.selected,
.screen-screenshot-card.highlighted { --screen-frame: var(--accent); }
.screen-screenshot-card:is(.diff-added, .diff-modified, .diff-removed) { --screen-frame: var(--diff); }
@@ -738,23 +717,48 @@ code {
opacity: 1;
}
/* Hover is transient canvas state. Nothing recedes: the pointer's screen gets its ring, the
transitions into and out of it turn accent, and the screens at their other ends take a tinted
frame, so the neighbourhood reads without the rest of the map changing. Only the symmetric
difference of related nodes/edges receives a class, avoiding a React commit across the graph. */
.connection-canvas-surface.canvas-hovering .graph-edge-hover-related .transition-edge-path {
stroke: var(--accent) !important;
stroke-width: 2.2 !important;
/* A Map card's border is its status alone. Selection rings it from outside instead: an accent
ring past a gap in the canvas colour, outside the status border, with a soft lift; hover draws
the same ring in grey. The ring scales with the canvas, so below a readable zoom its unit grows
to keep it about a screen pixel and a half wide (--canvas-zoom, set by the zoom bridge). */
.map-surface .screen-screenshot-card {
--ring-unit: clamp(1px, 0.6px / var(--canvas-zoom, 1), 6px);
--ring-status: 0px;
}
.map-surface .screen-screenshot-card:is(.diff-added, .diff-modified, .diff-removed) { --ring-status: 2px; }
.map-surface .screen-screenshot-card .screen-node-image :is(img, .image-placeholder) {
border-color: var(--border-subtle);
box-shadow: none;
}
.map-surface .react-flow__node-screen:is(.selected, .graph-node-hover-subject) .screen-screenshot-card .screen-node-image :is(img, .image-placeholder) {
box-shadow:
0 0 0 var(--ring-status) var(--diff, transparent),
0 0 0 calc(var(--ring-status) + 4 * var(--ring-unit)) var(--screen),
0 0 0 calc(var(--ring-status) + 6.5 * var(--ring-unit)) var(--ring-color),
var(--ring-lift, 0 0 transparent);
}
.map-surface .react-flow__node-screen.graph-node-hover-subject { --ring-color: var(--hover-ring); }
.map-surface .react-flow__node-screen.selected {
--ring-color: var(--accent);
--ring-lift: 0 calc(10 * var(--ring-unit)) calc(28 * var(--ring-unit)) color-mix(in srgb, var(--accent) 18%, transparent);
}
.map-surface .react-flow__node-screen.selected .screen-node-title { color: var(--accent-strong); }
/* Keyboard focus is dashed, past where a ring would sit, so it never reads as either. */
.map-surface .screen-screenshot-target:focus-visible {
outline: 2px dashed var(--accent-strong) !important;
outline-offset: calc(var(--ring-status) + 9 * var(--ring-unit)) !important;
filter: none !important;
}
/* Hover is transient canvas state. Nothing recedes: the pointer's screen takes its grey ring and
the transitions into and out of it darken. Only the symmetric difference of related
nodes/edges receives a class, avoiding a React commit across the graph. A selected screen's
transitions stay accent. */
.connection-canvas-surface.canvas-hovering .graph-edge-hover-related:not(.graph-edge-active) .transition-edge-path {
stroke: var(--tertiary) !important;
stroke-width: 2 !important;
stroke-dasharray: none !important;
}
.connection-canvas-surface.canvas-hovering .react-flow__node-screen.graph-node-hover-related:not(.graph-node-hover-subject)
.screen-screenshot-card:not(.selected, .diff-added, .diff-modified, .diff-removed) {
--screen-frame: var(--hover-neighbour-frame);
}
.connection-canvas-surface.canvas-hovering .react-flow__node-screen.graph-node-hover-related:not(.graph-node-hover-subject)
.screen-screenshot-card:not(.selected, .diff-added, .diff-modified, .diff-removed) .screen-node-image :is(img, .image-placeholder) {
border-color: var(--hover-neighbour-frame);
}
/* Semantic Map: an area is a meaningful destination, never an anonymous "X states" step. */
.semantic-summary-node {
@@ -928,7 +932,7 @@ code {
/* The phone map's open hint. The first tap there only selects, so the pill sits in the middle of
the selected screenshot (always on the image whatever the slot's shape) and says what the next
tap does. In a wider window the card's tooltip carries the message and nothing covers the image. */
tap does. In a wider window a click opens the Inspector at once and nothing covers the image. */
.screen-screenshot-target { cursor: pointer; }
.screen-open-hint {
position: absolute;
@@ -954,7 +958,7 @@ code {
.screen-open-hint > svg { width: 14px; height: 14px; flex: none; }
/* Only the phone layout's map shows the pill, on the selected screen, where a second tap or click
opens the Inspector. That layout is a width, not a device, and has no tooltips, so a narrow
desktop window shows it too. Elsewhere the screenshot button's tooltip says it instead. */
desktop window shows it too. */
.phone-layout .map-canvas .screen-screenshot-card.selected .screen-open-hint {
display: inline-flex;
animation: screen-open-hint-in 140ms ease-out;
@@ -998,7 +1002,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); }
@@ -1105,7 +1109,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;
@@ -1117,33 +1124,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);
}
/* When minimised, the inspector actions join the camera controls as one floating toolbar. */
.right-float {
position: fixed;
z-index: 100;
top: var(--chrome-top);
right: var(--right-float-edge);
width: calc(var(--right-float-width) * var(--ui-scale));
height: var(--chrome-height);
display: flex;
align-items: center;
gap: 2px;
padding: calc(3px * var(--ui-scale));
border: 0;
border-radius: 0 calc(8px * var(--ui-scale)) calc(8px * var(--ui-scale)) 0;
background: var(--side-panel-surface);
box-shadow: none;
/* No backdrop blur: the surface is opaque, and a blurred backdrop leaves this toolbar's view
transition snapshot stale, so a button that moves into its place paints late. */
view-transition-name: right-floating-controls;
/* 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-float > * { zoom: var(--ui-scale); }
.right-float .icon-button.active { color: var(--text); background: var(--element); }
.right-float .icon-button[disabled] { color: var(--border); cursor: default; background: transparent; }
.right-float .icon-button:hover {
border-color: transparent;
background: var(--panel-hover);
.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; }
.right-head {
display: flex;
flex: none;
@@ -1202,7 +1211,8 @@ code {
position: absolute;
z-index: 20;
top: var(--chrome-top);
right: calc(var(--canvas-visible-right-inset, 0px) + 8px);
/* Mirrors the pill: the same inset from the canvas' right edge as the pill's from its left. */
right: calc(var(--canvas-visible-right-inset, 0px) + var(--canvas-chrome-inline-inset));
display: inline-flex;
height: var(--chrome-height);
align-items: center;
@@ -1213,30 +1223,9 @@ code {
color: var(--text);
background: var(--side-panel-surface);
box-shadow: var(--floating-chrome-shadow);
/* No backdrop blur, as on .right-float: with it, entering Compare painted full screen late. */
/* No backdrop blur: with it, the view transition's snapshot of these controls painted late. */
view-transition-name: canvas-camera-controls;
}
.canvas-camera-controls.inspector-collapsed {
right: calc(
var(--canvas-visible-right-inset, 0px) +
var(--right-float-edge) + var(--right-float-width) * var(--ui-scale) - 1px
);
border: 0;
border-radius: calc(8px * var(--ui-scale)) 0 0 calc(8px * var(--ui-scale));
box-shadow: none;
}
.canvas-camera-controls.inspector-collapsed::before {
position: absolute;
z-index: -1;
top: 0;
right: calc((var(--right-float-width) * var(--ui-scale) - 1px) * -1);
bottom: 0;
left: 0;
border-radius: calc(8px * var(--ui-scale));
box-shadow: var(--floating-chrome-shadow);
content: "";
pointer-events: none;
}
.canvas-camera-controls .camera-action-button,
.canvas-camera-controls .zoom-button {
border: 0;
@@ -1260,7 +1249,6 @@ code {
flex: none;
background: var(--border-subtle);
}
.canvas-camera-controls.inspector-collapsed .camera-control-divider { display: none; }
.canvas-camera-controls .zoom-button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
@@ -2056,6 +2044,61 @@ code {
.menu-row-shortcut { flex: none; margin-left: 16px; color: var(--tertiary); font-size: 11px; }
.menu-separator { height: 1px; margin: 4px 6px; background: var(--popover-line); }
/* ── More menu (the bottom bar's "…") ───────────────────────────────────── */
/* The menu is anchored to its button, but clears the bar the button sits in. The popover itself
is the surface, as the Changes menu's is: an anchored popover scrolls, and would clip a shadow
drawn by the list inside it. Only a window too short for the menu scrolls it. */
.menu-popover.more-menu {
overflow-x: hidden !important;
border: 1px solid var(--popover-line);
border-radius: calc(9px * var(--ui-scale));
background: var(--popover);
box-shadow: var(--popover-shadow);
translate: 0 calc(-12px * var(--ui-scale));
}
/* Rows read icon, label, control, key, in the menu's own type and colours. */
.more-menu-list { display: flex; width: 248px; flex-direction: column; padding: 4px; }
.more-menu-row {
display: flex;
width: 100%;
min-height: 34px;
align-items: center;
gap: 8px;
padding: 4px 6px 4px 8px;
border-radius: 5px;
color: var(--text);
background: transparent;
font-size: 12px;
text-align: left;
}
.more-menu-item:hover,
.more-menu-item:focus-visible { background: var(--popover-hover); outline: none; }
.more-menu-icon { display: flex; width: 16px; flex: none; align-items: center; justify-content: center; color: var(--secondary); }
.more-menu-icon > svg { width: 15px; height: 15px; }
.more-menu-label { min-width: 0; flex: 1; white-space: nowrap; }
.more-menu-check { display: flex; flex: none; color: var(--secondary); }
.more-menu-check > svg { width: 14px; height: 14px; }
/* The key column lines up down the menu, whatever the row holds before it. */
.more-menu-key { min-width: 22px; flex: none; text-align: center; }
/* A compact three-way switch: Auto, Light, Dark, on the segmented control's track and thumb. */
.more-theme-switch { display: flex; flex: none; gap: 2px; padding: 2px; border-radius: 7px; background: var(--segment-track); }
.more-theme-option {
display: flex;
width: 26px;
height: 22px;
align-items: center;
justify-content: center;
border-radius: 5px;
color: var(--tertiary);
background: transparent;
transition: color 120ms ease, background 120ms ease;
}
.more-theme-option > svg { width: 14px; height: 14px; }
.more-theme-option:hover { color: var(--text); }
.more-theme-option[aria-checked="true"] { color: var(--text); background: var(--segment-thumb); box-shadow: 0 1px 2px rgb(0 0 0 / 0.12); }
.more-theme-option:focus-visible { outline: 2px solid var(--accent); outline-offset: 0; }
/* ── Feedback dialog ────────────────────────────────────────────────────── */
.dialog-backdrop {
@@ -2202,7 +2245,8 @@ code {
.search-command-result-copy code { color: inherit; font-size: inherit; }
.search-command-section + .search-command-section { margin-top: 4px; }
.search-command-section > .search-command-section-label { padding: 8px 8px 4px; }
.search-command-result-key {
.search-command-result-key,
.more-menu-key {
padding: 2px 6px;
border: 1px solid var(--border);
border-radius: 5px;
@@ -2330,7 +2374,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) {
+2 -1
View File
@@ -102,7 +102,8 @@ export function commandItems(context: CommandContext, actions: CommandActions):
{ keywords: ["app", "appearance", "scheme", "captured"], shortcut: !appearance.current && context.appearances.length === 2 ? key(SHORTCUTS.appearance.app) : undefined });
}
if (context.fullscreen !== undefined) {
add("view:fullscreen", "View", context.fullscreen ? "Exit full screen" : "Enter full screen", actions.toggleFullscreen, { keywords: ["fullscreen", "window", "focus"] });
add("view:fullscreen", "View", context.fullscreen ? "Exit full screen" : "Enter full screen", actions.toggleFullscreen,
{ keywords: ["fullscreen", "window", "focus"], shortcut: key(SHORTCUTS.view.fullscreen) });
}
for (const target of context.targets) {
+9 -8
View File
@@ -123,15 +123,16 @@ export function buildObservedGraph(map: ExploreMap, index: MapIndex): ObservedGr
};
}
/** The Viewer can overlay declarations; the observed graph and event indexes stay intact. */
export function buildViewerGraph(map: ExploreMap, index: MapIndex): ObservedGraph {
const NONE: ReadonlySet<string> = new Set();
/**
* The Viewer can overlay declarations; the observed graph and event indexes stay intact. A public report preserves its
* complete source inventory, but the routes it never captured are not its screens: `omitted` names them, the one set
* every view of the report takes (omitted-screens.ts). The launch is never among them: it is where the app starts,
* drawn above the start screens with a synthetic edge into each of them.
*/
export function buildViewerGraph(map: ExploreMap, index: MapIndex, omitted: ReadonlySet<string> = NONE): ObservedGraph {
const observed = buildObservedGraph(map, index);
// A public report preserves its complete source inventory, but an accepted capture gap
// marks a redirect or a route outside changes-mode selection. Neither is a screen image. The app
// launch is not a route, so its accepted "no splash observed" gap keeps it on the map: it is where
// the app starts, drawn above the start screens with a synthetic edge into each of them.
const omitted = new Set<string>();
if (map.run.id.startsWith("public:")) for (const gap of map.gaps) if (gap.status === "accepted" && gap.screenId && !isLaunchScreen({ id: gap.screenId })) omitted.add(gap.screenId);
const screens = observed.screens.filter(screen => !omitted.has(screen.id));
const visibleIds = new Set(screens.map(screen => screen.id));
const launchEdges = launchGroups(screens);
+83
View File
@@ -0,0 +1,83 @@
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,
);
}
/** The room the bottom bar needs beside the Inspector, in window pixels: its measured width and a gap either side. */
let toolbarRoom = 0;
const toolbarListeners = new Set<() => void>();
/** The bottom bar reports the room it needs whenever its measured width changes (with `--ui-scale` too). */
export function setToolbarRoom(room: number) {
if (room === toolbarRoom) return;
toolbarRoom = room;
for (const listener of toolbarListeners) listener();
}
export function getToolbarRoom(): number {
return toolbarRoom;
}
export function subscribeToToolbarRoom(onChange: () => void): () => void {
toolbarListeners.add(onChange);
return () => toolbarListeners.delete(onChange);
}
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, and never so wide that the canvas beside it loses the `toolbarRoom` the
* bottom bar needs (window pixels), in the panel's own (unscaled) pixels when the chrome is zoomed
* by `scale`. Neither cap goes below the minimum.
*/
export function inspectorWidthBounds(windowWidth: number, scale = 1, room = 0): InspectorWidthBounds {
const zoom = scale > 0 ? scale : 1;
const half = Math.floor(windowWidth / 2 / zoom);
const besideBar = Math.floor((windowWidth - room) / zoom);
return { min: INSPECTOR_WIDTH_MIN, max: Math.max(INSPECTOR_WIDTH_MIN, Math.min(INSPECTOR_WIDTH_MAX, half, besideBar)) };
}
export function clampInspectorWidth(width: number, bounds: InspectorWidthBounds): number {
return Math.round(Math.min(bounds.max, Math.max(bounds.min, width)));
}
+73
View File
@@ -0,0 +1,73 @@
import type { BuildDiff, DiffStatus, ScreenDiff } from "./build-diff";
import { isLaunchScreen, type ExploreMap, type Screen } from "./model";
import type { ScreenPresentation } from "./screen-presentation";
const NONE: ReadonlySet<string> = new Set();
/**
* The screens of a public report's map, before path grouping, that the run never captured on purpose: a redirect
* declaration, a route named in `exploration.exclude`, or one outside the capture context in changes mode. Each has an
* accepted capture gap, no open one, and no screenshot of its own on either side. A screenshot a redirect borrows from
* the route it declares is not its own: build-diff names a side's own capture by its observation id. An open gap, such
* as a failed capture, keeps the screen: its failure is part of the report. The app launch is not a route, and a local
* map leaves nothing out.
*
* This is the map's view of `neverCapturedSurfaceIds` (src/contracts/surface-capture.ts), which the PR comment uses.
*/
export function omittedSourceScreenIds(
source: Pick<ExploreMap, "run" | "gaps" | "screens">,
diff?: Pick<BuildDiff, "screens">,
): ReadonlySet<string> {
if (!source.run.id.startsWith("public:")) return NONE;
const accepted = new Set<string>();
const open = new Set<string>();
for (const gap of source.gaps) {
if (gap.screenId && gap.status === "accepted") accepted.add(gap.screenId);
if (gap.screenId && gap.status === "open") open.add(gap.screenId);
}
const omitted = new Set<string>();
for (const screen of source.screens) {
if (!accepted.has(screen.id) || open.has(screen.id) || isLaunchScreen(screen) || screen.observationIds.length > 0) continue;
const compared = diff?.screens.get(screen.id);
if (compared?.baselineObservationId || compared?.currentObservationId) continue;
omitted.add(screen.id);
}
return omitted;
}
/**
* The screens none of the report's views list: the Map, Screens, search, Compare, the Changes list and their counts all
* take this one set. With a path presentation, a card leaves only when every screen it stands for does, a removed one
* included, so a card whose current route is a redirect still shows the screenshot of the screen it replaced. The map's
* index keeps them all: a link to one opens it in the Inspector, which says why it has no screenshot.
*/
export function omittedScreenIds(
source: Pick<ExploreMap, "run" | "gaps" | "screens">,
options: { diff?: Pick<BuildDiff, "screens"> | undefined; presentation?: Pick<ScreenPresentation, "families"> | undefined } = {},
): ReadonlySet<string> {
const members = omittedSourceScreenIds(source, options.diff);
if (!options.presentation || members.size === 0) return members;
return new Set(options.presentation.families
.filter((family) => family.members.every((member) => members.has(member.id)))
.map((family) => family.representative.id));
}
/** The report's screens: the map's screens but the omitted ones. */
export function reportScreens<T extends Pick<Screen, "id">>(screens: readonly T[], omitted: ReadonlySet<string>): readonly T[] {
return omitted.size ? screens.filter((screen) => !omitted.has(screen.id)) : screens;
}
/**
* The comparison without the omitted screens, so no count, Changes row, Compare step or Changed filter names a route
* that was never captured. Its map and index keep them, for a link to one.
*/
export function withoutOmittedScreens(diff: BuildDiff, omitted: ReadonlySet<string>): BuildDiff {
if (![...diff.screens.keys()].some((id) => omitted.has(id))) return diff;
const screens = new Map<string, ScreenDiff>();
const counts: Record<DiffStatus, number> = { ...diff.counts };
for (const [id, screen] of diff.screens) {
if (omitted.has(id)) counts[screen.status] -= 1;
else screens.set(id, screen);
}
return { ...diff, screens, counts };
}
+4
View File
@@ -77,6 +77,10 @@ export const SHORTCUTS = {
theme: plain("KeyT", "T"),
app: shift("KeyT", "T"),
},
/** F puts the whole Viewer in or out of full screen, where the browser allows it. */
view: {
fullscreen: plain("KeyF", "F"),
},
/** Canvas edits follow the platform-standard history keys. */
edit: {
undo: mod("KeyZ", "Z"),