@blackbelt-technology/frontend-mockup-loop 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.pi/skills/frontend-mockup-loop/SKILL.md +87 -8
  2. package/README.md +47 -2
  3. package/package.json +43 -4
  4. package/references/live-mock-site.md +332 -0
  5. package/site/Site.tsx +627 -0
  6. package/site/clock.ts +39 -0
  7. package/site/fixtures.ts +144 -0
  8. package/site/frame-env.ts +59 -0
  9. package/site/kit.tsx +175 -0
  10. package/site/main.tsx +11 -0
  11. package/site/pane-runtime.ts +230 -0
  12. package/site/pane-scroll-guard.ts +70 -0
  13. package/site/ring-line.ts +100 -0
  14. package/site/script.ts +201 -0
  15. package/site/site.css +179 -0
  16. package/site/step-gate.ts +138 -0
  17. package/site/tsconfig.json +16 -0
  18. package/site/virtual.d.ts +16 -0
  19. package/src/extension.ts +189 -58
  20. package/src/mock-site/base.d.mts +2 -0
  21. package/src/mock-site/base.mjs +28 -0
  22. package/src/mock-site/browser.d.mts +8 -0
  23. package/src/mock-site/browser.mjs +72 -0
  24. package/src/mock-site/capture.d.mts +8 -0
  25. package/src/mock-site/capture.mjs +221 -0
  26. package/src/mock-site/check.mjs +8 -0
  27. package/src/mock-site/cli.d.mts +3 -0
  28. package/src/mock-site/cli.mjs +96 -0
  29. package/src/mock-site/decisions.d.mts +6 -0
  30. package/src/mock-site/decisions.mjs +71 -0
  31. package/src/mock-site/discover.d.mts +7 -0
  32. package/src/mock-site/discover.mjs +137 -0
  33. package/src/mock-site/env.d.mts +15 -0
  34. package/src/mock-site/env.mjs +228 -0
  35. package/src/mock-site/frameworks.d.mts +5 -0
  36. package/src/mock-site/frameworks.mjs +27 -0
  37. package/src/mock-site/headless.d.mts +9 -0
  38. package/src/mock-site/headless.mjs +207 -0
  39. package/src/mock-site/locate.d.mts +3 -0
  40. package/src/mock-site/locate.mjs +30 -0
  41. package/src/mock-site/options.d.mts +19 -0
  42. package/src/mock-site/options.mjs +45 -0
  43. package/src/mock-site/plugin.d.mts +21 -0
  44. package/src/mock-site/plugin.mjs +191 -0
  45. package/src/mock-site/refs.d.mts +7 -0
  46. package/src/mock-site/refs.mjs +65 -0
  47. package/src/mock-site/serve-cli.mjs +43 -0
  48. package/src/mock-site/video.mjs +8 -0
  49. package/src/mock-site-serve.ts +186 -0
package/site/clock.ts ADDED
@@ -0,0 +1,39 @@
1
+ // GENERIC pane clock (framework-free): a scripted pane's "now" starts at `clockAt`
2
+ // on every loop and advances in real time from there, so relative times render the
3
+ // same on every loop. See change: add-mock-site-exact-env (design D4).
4
+
5
+ export interface PaneClock {
6
+ /** Current pane time (ms since epoch). */
7
+ now(): number;
8
+ /** Restart at the start instant (a new loop). */
9
+ reset(): void;
10
+ }
11
+
12
+ /** Start instant: `clockAt` (ISO-8601) when given, else the page-load time. */
13
+ export function clockStart(clockAt: string | undefined, pageLoad: number): number {
14
+ if (clockAt === undefined) return pageLoad;
15
+ const t = Date.parse(clockAt);
16
+ if (Number.isNaN(t)) throw new Error(`clockAt is not an ISO-8601 instant: ${clockAt}`);
17
+ return t;
18
+ }
19
+
20
+ export function createClock(start: number, realNow: () => number = () => performance.timeOrigin + performance.now()): PaneClock {
21
+ let t0 = realNow();
22
+ return {
23
+ now: () => start + (realNow() - t0),
24
+ reset: () => { t0 = realNow(); },
25
+ };
26
+ }
27
+
28
+ /** Replace the window's `Date` so `new Date()` / `Date.now()` follow the pane clock. */
29
+ export function installClock(win: Window & typeof globalThis, clock: PaneClock): void {
30
+ const Real = win.Date;
31
+ class MkDate extends Real {
32
+ constructor(...args: unknown[]) {
33
+ if (args.length === 0) super(clock.now());
34
+ else super(...(args as [string | number | Date]));
35
+ }
36
+ static now(): number { return clock.now(); }
37
+ }
38
+ win.Date = MkDate as DateConstructor;
39
+ }
@@ -0,0 +1,144 @@
1
+ // GENERIC network fixtures (framework-free). A mock's `fixtures()` factory runs once
2
+ // per pane and per script loop; its handlers answer the app's fetch / XHR /
3
+ // WebSocket traffic INSIDE the pane's own document (no service worker: works on a
4
+ // plain-HTTP LAN URL). Unhandled requests get 501 and are reported as missing
5
+ // fixtures. Interceptors are lazy-loaded optional peers.
6
+ // See change: add-mock-site-exact-env (design D3).
7
+
8
+ import { stripBase } from "./frame-env.ts";
9
+
10
+ export interface FixtureRequest {
11
+ method: string;
12
+ url: URL;
13
+ path: string;
14
+ /** `:name` segments of the matched route. */
15
+ params: Record<string, string>;
16
+ body: string;
17
+ json<T = unknown>(): T;
18
+ }
19
+ /** A `Response`, or any JSON-serialisable value (sent as 200 application/json). */
20
+ export type FixtureReply = Response | unknown;
21
+ export interface FixtureSocket {
22
+ send(data: string | object): void;
23
+ close(): void;
24
+ onMessage(cb: (data: string) => void): void;
25
+ }
26
+ export interface HarFixtures { entries: { method: string; path: string; query?: string; status: number; contentType?: string; body: string }[] }
27
+ export interface Fixtures {
28
+ /** Keys `"GET /api/runs/:id"` (or bare `"/api/x"` = any method). */
29
+ http?: Record<string, (req: FixtureRequest) => FixtureReply | Promise<FixtureReply>>;
30
+ /** Keys: WebSocket URL path. */
31
+ ws?: Record<string, (socket: FixtureSocket) => void>;
32
+ /** Captured traffic (`mock-capture` → `fixtures.har.json`), used after `http`. */
33
+ har?: HarFixtures;
34
+ /** Requests allowed to reach the network (URL substring or RegExp). */
35
+ passthrough?: (string | RegExp)[];
36
+ }
37
+
38
+ /** Same-origin dev-server traffic that is never a fixture concern. */
39
+ const DEV_PATHS = /^\/(@vite|@fs|@id|@react-refresh|node_modules|__mock)\b/;
40
+
41
+ /** `:params` of `pattern` against `path`, or null. */
42
+ export function matchPath(pattern: string, path: string): Record<string, string> | null {
43
+ const a = pattern.split("/"), b = path.split("/");
44
+ if (a.length !== b.length) return null;
45
+ const out: Record<string, string> = {};
46
+ for (let i = 0; i < a.length; i++) {
47
+ if (a[i].startsWith(":")) out[a[i].slice(1)] = decodeURIComponent(b[i]);
48
+ else if (a[i] !== b[i]) return null;
49
+ }
50
+ return out;
51
+ }
52
+
53
+ export type Resolved =
54
+ | { kind: "http"; handler: (req: FixtureRequest) => FixtureReply | Promise<FixtureReply>; params: Record<string, string> }
55
+ | { kind: "har"; entry: HarFixtures["entries"][number] }
56
+ | { kind: "passthrough" }
57
+ | { kind: "missing" };
58
+
59
+ /** Decide how a request is answered (pure). */
60
+ export function resolveRequest(fx: Fixtures, method: string, url: URL, origin: string): Resolved {
61
+ // The base is stripped ONLY for the dev-path test: fixture matching below sees the raw path.
62
+ if (url.origin === origin && DEV_PATHS.test(stripBase(url.pathname))) return { kind: "passthrough" };
63
+ const m = method.toUpperCase();
64
+ for (const [key, handler] of Object.entries(fx.http ?? {})) {
65
+ const sp = key.indexOf(" ");
66
+ const [km, kp] = sp > 0 ? [key.slice(0, sp).toUpperCase(), key.slice(sp + 1).trim()] : ["*", key.trim()];
67
+ if (km !== "*" && km !== m) continue;
68
+ const params = matchPath(kp, url.pathname);
69
+ if (params) return { kind: "http", handler, params };
70
+ }
71
+ const har = (fx.har?.entries ?? []).filter((e) => e.method === m && e.path === url.pathname);
72
+ const entry = har.find((e) => (e.query ?? "") === url.search) ?? har[0];
73
+ if (entry) return { kind: "har", entry };
74
+ if ((fx.passthrough ?? []).some((p) => (typeof p === "string" ? url.href.includes(p) : p.test(url.href)))) return { kind: "passthrough" };
75
+ return { kind: "missing" };
76
+ }
77
+
78
+ /** A fixture reply as a `Response`. */
79
+ function toResponse(v: FixtureReply): Response {
80
+ if (v instanceof Response) return v;
81
+ return new Response(JSON.stringify(v ?? null), { status: 200, headers: { "content-type": "application/json" } });
82
+ }
83
+
84
+ export interface InstalledFixtures {
85
+ /** New fixture instance (fresh factory call) for the next loop. */
86
+ reset(): void;
87
+ }
88
+
89
+ /** Install fetch / XHR / WebSocket interception into THIS window (the pane document). */
90
+ export async function installFixtures(factory: () => Fixtures, onMissing: (m: { method: string; path: string }) => void): Promise<InstalledFixtures> {
91
+ const [{ FetchInterceptor }, { XMLHttpRequestInterceptor }, { WebSocketInterceptor }] = await Promise.all([
92
+ import("@mswjs/interceptors/fetch"),
93
+ import("@mswjs/interceptors/XMLHttpRequest"),
94
+ import("@mswjs/interceptors/WebSocket"),
95
+ ]);
96
+ let fx = factory();
97
+ const origin = location.origin;
98
+ for (const I of [FetchInterceptor, XMLHttpRequestInterceptor]) {
99
+ const it = new I();
100
+ it.on("request", async ({ request, controller }) => {
101
+ const url = new URL(request.url);
102
+ const r = resolveRequest(fx, request.method, url, origin);
103
+ if (r.kind === "passthrough") return;
104
+ if (r.kind === "missing") {
105
+ onMissing({ method: request.method.toUpperCase(), path: stripBase(url.pathname) });
106
+ controller.respondWith(new Response(`no fixture for ${request.method} ${url.pathname}`, { status: 501 }));
107
+ return;
108
+ }
109
+ if (r.kind === "har") {
110
+ const e = r.entry;
111
+ const empty = e.status === 204 || e.status === 304;
112
+ controller.respondWith(new Response(empty ? null : e.body, { status: e.status, headers: { "content-type": e.contentType ?? "application/json" } }));
113
+ return;
114
+ }
115
+ const body = await request.clone().text();
116
+ const req: FixtureRequest = { method: request.method.toUpperCase(), url, path: url.pathname, params: r.params, body, json: () => JSON.parse(body) };
117
+ controller.respondWith(toResponse(await r.handler(req)));
118
+ });
119
+ it.apply();
120
+ }
121
+ const ws = new WebSocketInterceptor();
122
+ ws.on("connection", ({ client, server, info }) => {
123
+ const url = new URL(client.url);
124
+ const protocols = ([] as string[]).concat(info.protocols ?? []);
125
+ const handler = Object.entries(fx.ws ?? {}).find(([p]) => matchPath(p, url.pathname))?.[1];
126
+ if (handler) {
127
+ handler({
128
+ send: (d) => client.send(typeof d === "string" ? d : JSON.stringify(d)),
129
+ close: () => client.close(),
130
+ onMessage: (cb) => client.addEventListener("message", (e) => cb(String(e.data))),
131
+ });
132
+ return;
133
+ }
134
+ const devSocket = protocols.some((p) => p.startsWith("vite-")) || (url.host === location.host && DEV_PATHS.test(stripBase(url.pathname)));
135
+ if (devSocket || (fx.passthrough ?? []).some((p) => (typeof p === "string" ? url.href.includes(p) : p.test(url.href)))) {
136
+ server.connect();
137
+ return;
138
+ }
139
+ onMissing({ method: "WS", path: stripBase(url.pathname) });
140
+ client.close(4004, "no fixture");
141
+ });
142
+ ws.apply();
143
+ return { reset: () => { fx = factory(); } };
144
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Opaque-frame and base-path helpers shared by the shell, the pane runtime and the fixture layer.
3
+ *
4
+ * Tier 5 (`/preview/<pid>/`) frames the site in a sandbox WITHOUT `allow-same-origin`: `window.origin` is the string
5
+ * `"null"`, `postMessage(…, location.origin)` throws and storage is unavailable. Tiers 1-4 frame a real origin and need none
6
+ * of it. Messaging rule (both directions): post to ONE known window only (`parent` / `frame.contentWindow`), with `"*"` only
7
+ * while opaque, and accept a message only from that window (`e.source`). Payloads carry no decisions, fixtures or URLs.
8
+ * See change: serve-live-previews-on-capability-origin (D11 (3), (5), (9), (10)).
9
+ */
10
+
11
+ /** The Vite `base` this document is served under (always ends with `/`). */
12
+ export const BASE: string = import.meta.env?.BASE_URL ?? "/";
13
+
14
+ /**
15
+ * Is this document in an opaque origin (a sandboxed frame without `allow-same-origin`)? `window.origin` is the DOCUMENT's
16
+ * origin ("null" when sandboxed); `location.origin` is the URL's origin and stays the real one even in such a frame, so it
17
+ * only says "null" for URLs that have none (kept as the fallback when a host exposes no `window.origin`).
18
+ */
19
+ export const isOpaque = (): boolean => (globalThis as { origin?: string }).origin === "null" || location.origin === "null";
20
+
21
+ /** `targetOrigin` for a `postMessage` to a known window: `"*"` only while opaque, the real origin otherwise. */
22
+ export const postTarget = (): string => (isOpaque() ? "*" : location.origin);
23
+
24
+ /** Origin check for an INBOUND message; opaque frames carry the origin `"null"` and rely on the `e.source` check instead. */
25
+ export const originOk = (e: MessageEvent): boolean => (isOpaque() ? e.origin === "null" : e.origin === location.origin);
26
+
27
+ /** Is `source` the window of one of this document's child frames? */
28
+ export const fromChildFrame = (source: MessageEventSource | null): boolean =>
29
+ source !== null && Array.from(document.querySelectorAll("iframe")).some((f) => f.contentWindow === source);
30
+
31
+ type Kind = "local" | "session";
32
+ const area = (kind: Kind): Storage | null => {
33
+ try {
34
+ return kind === "local" ? localStorage : sessionStorage;
35
+ } catch {
36
+ return null; // a SecurityError in an opaque frame
37
+ }
38
+ };
39
+ /** Storage read that never throws (`null` when unavailable). */
40
+ export const readStore = (kind: Kind, key: string): string | null => {
41
+ try {
42
+ return area(kind)?.getItem(key) ?? null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ };
47
+ /** Storage write that never throws. */
48
+ export const writeStore = (kind: Kind, key: string, value: string): void => {
49
+ try {
50
+ area(kind)?.setItem(key, value);
51
+ } catch {
52
+ /* unavailable / quota */
53
+ }
54
+ };
55
+
56
+ /** Strip `base` from a path ONLY when the path is under it (`/some/prefix/x` → `/x`); anything else is returned as is. */
57
+ export function stripBase(pathname: string, base: string = BASE): string {
58
+ return base !== "/" && pathname.startsWith(base) ? `/${pathname.slice(base.length)}` : pathname;
59
+ }
package/site/kit.tsx ADDED
@@ -0,0 +1,175 @@
1
+ // GENERIC mock kit — English only, no app names.
2
+ // A mock = one PAGE (or flow); a frame = Current | Proposed panes of REAL app components.
3
+ // The kit adds only the review layer: numbered rings around any element + reference links.
4
+ // Import in a mock as `mock-site/kit` (plugin alias). See change: add-live-component-mock-site,
5
+ // add-mock-site-exact-env (fixtures, script, surroundings, framework),
6
+ // add-mock-locate-frame (Locate frame, ring line).
7
+ import { createContext, type ReactElement, type ReactNode, useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
8
+ import { createPortal } from "react-dom";
9
+ import { locateProblems } from "../src/mock-site/locate.mjs";
10
+ import { isRingN, refId } from "../src/mock-site/refs.mjs";
11
+ import type { Fixtures } from "./fixtures.ts";
12
+ import { watchRingLine } from "./ring-line.ts";
13
+ import type { ScriptStep } from "./script.ts";
14
+
15
+ export type { FixtureReply, FixtureRequest, FixtureSocket, Fixtures, HarFixtures } from "./fixtures.ts";
16
+ export type { ScriptStep } from "./script.ts";
17
+ export { locateProblems, refId };
18
+ export type Status = "open" | "accepted" | "rejected";
19
+ /** One decision per mock page, written by the `mock-decide` CLI (`by: "user"` = legacy site button). */
20
+ export interface Decision { status: Exclude<Status, "open">; by: "user" | "agent"; note?: string; at: string }
21
+
22
+ interface FrameBase {
23
+ /** Key word first: "Sessions page - desktop". */
24
+ title: string;
25
+ /** Pane width in px (default 640). Ignored when phone. */
26
+ width?: number;
27
+ /** Render each side in a real 375px iframe so the app's @media rules apply. */
28
+ phone?: boolean;
29
+ /** One-line reason (≤ 120 chars), shown under the title and in the page overview. */
30
+ why?: string;
31
+ /** Today's UI with today's props. Omit for a part that does not exist yet ("New"). */
32
+ current?: ReactNode;
33
+ /** Animate `steps` in one pane (reduced motion: side by side). */
34
+ play?: boolean;
35
+ /** Real interactions on the real components (click / type / …), looped with a visible pointer. Wins over `steps`. */
36
+ script?: ScriptStep[];
37
+ /** Side the script drives (default "proposed"). */
38
+ side?: "proposed" | "current" | "both";
39
+ /** ISO-8601 instant the pane clock starts at on every loop (default: page load). */
40
+ clockAt?: string;
41
+ /** false = run the script once and stop (default: loop). */
42
+ loop?: boolean;
43
+ /** Network fixtures for this frame's panes (overrides the mock's). */
44
+ fixtures?: () => Fixtures;
45
+ /** Shared app shell / route around the content: identical in both panes, only the slot differs. */
46
+ surroundings?: (slot: ReactNode) => ReactNode;
47
+ }
48
+ /** A frame shows `proposed` (with optional `current`) or a `steps` flow; it must have one of them. */
49
+ export type Frame = FrameBase & (
50
+ | { proposed: ReactNode; steps?: Step[] }
51
+ /** States of one flow, drawn instead of clicked: side by side by default. Ring numbers stay unique across steps. */
52
+ | { proposed?: ReactNode; steps: Step[] }
53
+ );
54
+
55
+ /** One state of a flow. Wrap the element whose click leads to the next step in `Tap`. */
56
+ export interface Step { label: string; proposed: ReactNode }
57
+
58
+ /** One Locate walk: the full app page and the user's path to the reviewed part, ending with `spot`. */
59
+ export interface LocateWalk {
60
+ /** The whole app page (real shell components), opened at the landing view. */
61
+ page: ReactNode;
62
+ /** Steps a user takes from the landing view; the last one is `act: "spot"` on the part. */
63
+ script: ScriptStep[];
64
+ /** Network fixtures for the Locate pane (default: the mock's). */
65
+ fixtures?: () => Fixtures;
66
+ /** ISO-8601 instant the pane clock starts at on every loop. */
67
+ clockAt?: string;
68
+ }
69
+ /** Where the reviewed part lives and how a user gets there; shown first, not counted as a frame. */
70
+ export interface Locate extends LocateWalk {
71
+ /** Page width in px (default 1100); a narrower review column scales the pane down. */
72
+ width?: number;
73
+ /** Page height in px (default 640). */
74
+ height?: number;
75
+ /** Phone walk in a real 375px pane; required when any frame is `phone: true`. */
76
+ phone?: LocateWalk & { /** Page height in px (default 760). */ height?: number };
77
+ }
78
+
79
+ /** Default export of `<root>/<id>/mock.tsx`. The id is the directory name. */
80
+ export interface Mock {
81
+ title: string;
82
+ /** Screen area, free text. */
83
+ category: string;
84
+ /** The change / ticket it belongs to (optional). */
85
+ change?: string;
86
+ /** Component framework of the panes (default "react"; others need an adapter). */
87
+ framework?: string;
88
+ /** Network fixtures: called once per pane and per script loop (fresh state each time). */
89
+ fixtures?: () => Fixtures;
90
+ /** Locate frame: the full page + the walk to the part (`#<id>/locate`). Missing -> `NO LOCATE`. */
91
+ locate?: Locate;
92
+ frames: Frame[];
93
+ }
94
+
95
+ /** The content slot inside `surroundings` (no box of its own). */
96
+ export const Slot = ({ children }: { children: ReactNode }): ReactElement => <div data-mk-slot="" style={{ display: "contents" }}>{children}</div>;
97
+
98
+ /** A pane's node: `content` inside the frame's surroundings when declared (present in both panes or neither). */
99
+ export function paneContent(f: Pick<Frame, "surroundings">, content: ReactNode): ReactNode {
100
+ return f.surroundings ? f.surroundings(<Slot>{content}</Slot>) : content;
101
+ }
102
+
103
+ const MAX_TIP = 40;
104
+ export const MAX_WHY = 120;
105
+
106
+ /** True inside the animated player: `Tap` pulses instead of showing a static marker. */
107
+ export const InPlayer = createContext(false);
108
+ /** Marks the click target that leads to the next step (no handler: mocks stay prop-driven). */
109
+ export function Tap({ children }: { children: ReactNode }): ReactElement {
110
+ const anim = useContext(InPlayer);
111
+ return <span className={`mk-tap${anim ? " mk-tap-anim" : ""}`}>{children}<span className="mk-tap-dot" aria-hidden /></span>;
112
+ }
113
+
114
+ /** `<id>/<frame>/<side>` of the pane being rendered; rings derive their ref from it. */
115
+ export const RefBase = createContext<string | null>(null);
116
+ /** Top-level site URL of a ref (never the `?pane=` iframe URL). */
117
+ const refUrl = (ref: string): string => `${location.href.split("#", 1)[0]}#${ref}`; // `location.origin` is "null" in an opaque frame
118
+
119
+ /** Link to a ref: navigates the TOP page (also from a phone iframe) and copies the URL. */
120
+ export function RefLink({ to, className, children, title }: { to: string; className?: string; children: ReactNode; title?: string }): ReactElement {
121
+ return (
122
+ <a href={refUrl(to)} target="_top" className={className} title={title ?? `Copy link: #${to}`}
123
+ onClick={() => { void navigator.clipboard?.writeText(refUrl(to)).catch(() => {}); }}>{children}</a>
124
+ );
125
+ }
126
+
127
+ function Ring({ n, tip, kind, block, children }: { n: number | string; tip: string; kind: "bad" | "ok"; block?: boolean; children: ReactNode }): ReactElement {
128
+ // Line + badge = children of the ring (absolute) -> scroll natively with the element, no JS, no lag.
129
+ // Tip = body layer (escapes pane clipping), measured on hover, closed on any scroll.
130
+ const el = useRef<HTMLSpanElement>(null);
131
+ const line = useRef<HTMLSpanElement>(null);
132
+ // Line clamp before first paint; recomputed only on layout change (never on scroll).
133
+ useLayoutEffect(() => (el.current && line.current ? watchRingLine(el.current, line.current) : undefined), []);
134
+ const [box, setBox] = useState<DOMRect | null>(null);
135
+ useEffect(() => {
136
+ if (!box) return;
137
+ const hide = () => setBox(null);
138
+ addEventListener("scroll", hide, true);
139
+ return () => removeEventListener("scroll", hide, true);
140
+ }, [box]);
141
+ const show = () => { if (el.current && !document.documentElement.classList.contains("mk-no-rings")) setBox(el.current.getBoundingClientRect()); };
142
+ const below = !!box && box.top < 56;
143
+ const base = useContext(RefBase);
144
+ const okN = isRingN(n);
145
+ const ref = base && okN ? `${base}/${n}` : null;
146
+ return (
147
+ <span ref={el} id={ref ? refId(ref) : undefined} className={`mk-ring mk-${kind}${block ? " mk-block" : ""}`} tabIndex={0} aria-label={tip}
148
+ onMouseEnter={show} onFocus={show} onMouseLeave={() => setBox(null)} onBlur={() => setBox(null)}>
149
+ {children}
150
+ <span ref={line} className="mk-ring-line" aria-hidden />
151
+ {ref ? <RefLink to={ref} className={`mk-ring-n mk-${kind}`}>{String(n)}</RefLink> : <span className={`mk-ring-n mk-${kind}`} aria-hidden>{String(n)}</span>}
152
+ {!okN ? <span className="mk-long">BAD N</span> : tip.length > MAX_TIP ? <span className="mk-long">TIP &gt; {MAX_TIP}</span> : null}
153
+ {box ? createPortal(
154
+ <span className={`mk-tip mk-${kind}${below ? " mk-below" : ""}`} style={{ left: box.left + box.width / 2, top: below ? box.bottom + 12 : box.top - 12 }}>{tip}</span>,
155
+ document.body) : null}
156
+ </span>
157
+ );
158
+ }
159
+
160
+ type RingProps = { n: number | string; tip: string; block?: boolean; children: ReactNode };
161
+ /** A problem on the Current side (red). `block` keeps a block / grid cell's layout. */
162
+ export const Issue = (p: RingProps): ReactElement => <Ring {...p} kind="bad" />;
163
+ /** The fix on the Proposed side (green), numbered like its Issue. */
164
+ export const Fix = (p: RingProps): ReactElement => <Ring {...p} kind="ok" />;
165
+
166
+ /** Every `tip` in a JSX tree — feeds search. */
167
+ export function tipsOf(node: unknown, out: string[] = []): string[] {
168
+ if (Array.isArray(node)) { node.forEach((n) => tipsOf(n, out)); return out; }
169
+ if (node && typeof node === "object" && "props" in (node as object)) {
170
+ const p = (node as { props: Record<string, unknown> }).props;
171
+ if (typeof p.tip === "string") out.push(p.tip);
172
+ for (const v of Object.values(p)) if (v && typeof v === "object") tipsOf(v, out);
173
+ }
174
+ return out;
175
+ }
package/site/main.tsx ADDED
@@ -0,0 +1,11 @@
1
+ // GENERIC entry: the project's app module (real CSS, token bridge, providers), then the shell.
2
+ // Served by the mock-site plugin's HTML entry (the package ships no index.html).
3
+ // The pane scroll guard evaluates first: before the app module, the shell and setup().
4
+ import "./pane-scroll-guard.ts";
5
+ import { Providers, setup } from "virtual:mock-site/app";
6
+ import { createRoot } from "react-dom/client";
7
+ import "./site.css";
8
+ import { Site } from "./Site.tsx";
9
+
10
+ await setup?.();
11
+ createRoot(document.getElementById("root")!).render(<Providers><Site /></Providers>);
@@ -0,0 +1,230 @@
1
+ // GENERIC isolated-pane runtime (framework-free): runs inside one `?pane=` document.
2
+ // Installs the mock's fixtures and the pane clock BEFORE first render, then (for
3
+ // a driven side of a scripted frame) loops the script: remount with a fresh fixture
4
+ // instance + clock per loop, hold, repeat. Publishes `window.__mkHealth` and posts
5
+ // health / missing-fixture reports to the parent shell.
6
+ // An embedded live pane first pre-measures its stage (one silent fast loop, `mkStage`);
7
+ // pause / hidden / step controls go through a step gate (`mkStep` in, `mkGate` out).
8
+ // Query params: `mkLoops=N` (stop after N loops), `mkFast=1` (no pointer travel).
9
+ // See change: add-mock-site-exact-env (design D3, D4, D5), mock-player-step-controls (D2-D4).
10
+
11
+ import { clockStart, createClock, installClock } from "./clock.ts";
12
+ import { type Fixtures, installFixtures } from "./fixtures.ts";
13
+ import { originOk, postTarget } from "./frame-env.ts";
14
+ import { createOverlay, type Overlay, type RunResult, runSteps, type ScriptStep } from "./script.ts";
15
+ import { createStepGate, Rewind, type StepGate } from "./step-gate.ts";
16
+
17
+ const HOLD_MS = 1800;
18
+ const FAST_HOLD_MS = 150;
19
+ /** Pre-measure: total budget, per-step settle cap, stable-for window. */
20
+ const MEASURE_BUDGET_MS = 15_000;
21
+ const SETTLE_CAP_MS = 1000;
22
+ const SETTLE_STABLE_MS = 200;
23
+
24
+ export interface Health { completed: number; failed: number; errors: string[]; /** Duration of each finished loop (ms; `mock-check` mean). */ loopMs?: number[] }
25
+
26
+ export interface PaneRuntimeOptions {
27
+ spec: string;
28
+ fixtures?: () => Fixtures;
29
+ script?: ScriptStep[];
30
+ /** This pane runs the script (its side is driven). */
31
+ driven: boolean;
32
+ clockAt?: string;
33
+ loop?: boolean;
34
+ /** Reduced-motion step pane: run silently up to this step, then stop. */
35
+ step?: number;
36
+ /** Re-render the pane content (new React key); resolves after commit. */
37
+ remount: () => Promise<void>;
38
+ /** Fixtures + clock are in place: render the content. */
39
+ ready: () => void;
40
+ }
41
+
42
+ const post = (msg: object) => parent.postMessage(msg, postTarget());
43
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
44
+
45
+ export interface LoopContext {
46
+ spec: string;
47
+ /** 1-based loop number (health error prefix). */
48
+ n: number;
49
+ gate: Pick<StepGate, "wait" | "stop">;
50
+ overlay: Overlay | null;
51
+ fast: boolean;
52
+ /** Finished one-shot: rest at the end instead of returning (Back still works). */
53
+ hold: boolean;
54
+ /** A failed loop stops the gate (live view; headless checks keep looping). */
55
+ stopOnFail: boolean;
56
+ /** Fresh fixtures + clock, cleared overlay, remounted content. */
57
+ reset: () => Promise<void>;
58
+ health: Health;
59
+ post: (msg: object) => void;
60
+ }
61
+
62
+ /**
63
+ * One visible loop through the gate. A step back (`Rewind`) remounts, replays silently
64
+ * (no health, no `mkHealth`) and continues the same loop from the landing step; any other
65
+ * throw is a failed loop. Health: completion counted once per loop, failure once (it ends
66
+ * the loop). See change: mock-player-step-controls (design D3).
67
+ */
68
+ export async function playLoop(doc: Document, script: ScriptStep[], c: LoopContext): Promise<RunResult> {
69
+ let counted = false;
70
+ const report = (r: RunResult) => {
71
+ if (r.ok) {
72
+ if (counted) return;
73
+ counted = true;
74
+ c.health.completed++;
75
+ } else {
76
+ c.health.failed++;
77
+ c.health.errors.push(`loop ${c.n}: ${r.error}`);
78
+ c.overlay?.error(r.error);
79
+ if (c.stopOnFail) c.gate.stop();
80
+ }
81
+ c.post({ mkHealth: c.spec, completed: c.health.completed, failed: c.health.failed, error: r.ok ? undefined : r.error });
82
+ };
83
+ let from = 0;
84
+ for (;;) {
85
+ try {
86
+ const r = await runSteps(doc, script, { from, fast: c.fast, overlay: c.overlay, paused: (k) => c.gate.wait(k) });
87
+ report(r);
88
+ if (!r.ok) return r;
89
+ await c.gate.wait(script.length, c.hold);
90
+ return r;
91
+ } catch (e) {
92
+ if (!(e instanceof Rewind)) {
93
+ const r: RunResult = { ok: false, error: String((e as Error)?.message ?? e) };
94
+ report(r);
95
+ return r;
96
+ }
97
+ await c.reset();
98
+ const replay = await runSteps(doc, script, { upTo: e.to, fast: true, overlay: null });
99
+ if (!replay.ok) { report(replay); return replay; }
100
+ from = e.to;
101
+ }
102
+ }
103
+ }
104
+
105
+ /** Pane height: the overflowing root, else the body content (incl. portals, never fixed UI). */
106
+ function stageHeight(doc: Document): number {
107
+ const root = doc.documentElement;
108
+ if (root.scrollHeight > root.clientHeight) return root.scrollHeight;
109
+ const win = doc.defaultView!;
110
+ let h = doc.body.scrollHeight;
111
+ for (const el of Array.from(doc.body.children)) {
112
+ if (win.getComputedStyle(el).position === "fixed") continue;
113
+ h = Math.max(h, Math.ceil(el.getBoundingClientRect().bottom + win.scrollY));
114
+ }
115
+ return h;
116
+ }
117
+
118
+ /**
119
+ * One silent fast loop measuring the tallest height (after mount and after each step,
120
+ * settled), bounded by a total budget; a failing step ends it. See change:
121
+ * mock-player-step-controls (design D4).
122
+ */
123
+ async function measureStage(doc: Document, script: ScriptStep[]): Promise<number> {
124
+ let max = 0;
125
+ const sample = () => { const h = stageHeight(doc); max = Math.max(max, h); return h; };
126
+ const ro = new ResizeObserver(() => sample());
127
+ ro.observe(doc.body);
128
+ const ac = new AbortController();
129
+ // The budget runs from the pane document's start (≈ iframe mount), not from this call.
130
+ const timer = setTimeout(() => ac.abort(), Math.max(0, MEASURE_BUDGET_MS - performance.now()));
131
+ const settle = async () => {
132
+ const end = Date.now() + SETTLE_CAP_MS;
133
+ let last = sample();
134
+ let since = Date.now();
135
+ while (Date.now() < end && !ac.signal.aborted) {
136
+ await sleep(50);
137
+ const h = sample();
138
+ if (h !== last) { last = h; since = Date.now(); } else if (Date.now() - since >= SETTLE_STABLE_MS) break;
139
+ }
140
+ };
141
+ try {
142
+ const r = await runSteps(doc, script, { fast: true, overlay: null, signal: ac.signal, paused: () => settle() });
143
+ if (r.ok) await settle();
144
+ } finally {
145
+ clearTimeout(timer);
146
+ ro.disconnect();
147
+ }
148
+ return max || stageHeight(doc);
149
+ }
150
+
151
+ export async function startPane(o: PaneRuntimeOptions): Promise<void> {
152
+ const params = new URLSearchParams(location.search);
153
+ const win = window as Window & typeof globalThis & { __mkHealth?: Health & { error?: string } };
154
+ let fx: { reset(): void } | null = null;
155
+ try {
156
+ if (o.fixtures) fx = await installFixtures(o.fixtures, (m) => post({ mkMissing: o.spec, method: m.method, path: m.path }));
157
+ } catch (e) {
158
+ const error = `fixtures unavailable (install the optional peer @mswjs/interceptors): ${String((e as Error).message ?? e)}`;
159
+ win.__mkHealth = { completed: 0, failed: 0, errors: [error], error };
160
+ post({ mkHealth: o.spec, completed: 0, failed: 0, error });
161
+ }
162
+ const clock = o.script || o.clockAt ? createClock(clockStart(o.clockAt, performance.timeOrigin)) : null;
163
+ if (clock) installClock(win, clock);
164
+ o.ready();
165
+ if (!o.script?.length || !o.driven) return;
166
+ const script = o.script;
167
+ const health: Health = { completed: 0, failed: 0, errors: [] };
168
+ win.__mkHealth = health;
169
+
170
+ if (o.step !== undefined) {
171
+ // Reduced-motion step pane: run silently up to step k, then stop.
172
+ post({ mkReady: o.spec });
173
+ clock?.reset();
174
+ const r = await runSteps(document, script, { upTo: o.step, fast: true, overlay: null });
175
+ if (r.ok) health.completed++;
176
+ else {
177
+ health.failed++;
178
+ health.errors.push(`loop 1: ${r.error}`);
179
+ document.body.dataset.mkStepError = r.error;
180
+ }
181
+ post({ mkHealth: o.spec, completed: health.completed, failed: health.failed, error: r.ok ? undefined : r.error });
182
+ return;
183
+ }
184
+
185
+ const fast = params.has("mkFast");
186
+ const want = Number(params.get("mkLoops"));
187
+ const loops = Number.isInteger(want) && want > 0 ? want : o.loop === false ? 1 : Infinity;
188
+ const checking = params.has("mkLoops");
189
+ const overlay = createOverlay(document);
190
+ const reset = async () => { fx?.reset(); clock?.reset(); overlay.clear(); await o.remount(); };
191
+ const N = script.length;
192
+ // Paused by the reviewer, or held by the shell while the pane is off-screen (a running
193
+ // script must never move the reviewer's page); stepped with mkStep while paused.
194
+ const gate = createStepGate({
195
+ steps: N,
196
+ loop: o.loop !== false,
197
+ onHeld: (k) => overlay.caption(k === 0 ? `0/${N} start` : `${k}/${N} ${script[k - 1].say}`),
198
+ onChange: (state) => post({ mkGate: o.spec, state }),
199
+ });
200
+ addEventListener("message", (e) => {
201
+ if (e.source !== parent || !originOk(e)) return;
202
+ const d = e.data;
203
+ if (typeof d?.mkPause === "boolean") gate.setPaused(d.mkPause);
204
+ else if (typeof d?.mkHidden === "boolean") gate.setHidden(d.mkHidden);
205
+ else if (d?.mkStep === 1 || d?.mkStep === -1) gate.step(d.mkStep);
206
+ });
207
+ post({ mkReady: o.spec }); // the shell answers with the current mkHidden / mkPause state
208
+
209
+ // Embedded live pane: measure the stage behind the shell's loading cover, then start.
210
+ const measure = parent !== window && !checking;
211
+ if (measure) {
212
+ document.body.dataset.mkMeasuring = "1";
213
+ const h = await measureStage(document, script);
214
+ post({ mkStage: o.spec, h });
215
+ delete document.body.dataset.mkMeasuring;
216
+ }
217
+
218
+ for (let i = 0; i < loops; i++) {
219
+ if (i > 0 || measure) await reset();
220
+ else clock?.reset();
221
+ const t0 = performance.now();
222
+ const r = await playLoop(document, script, {
223
+ spec: o.spec, n: i + 1, gate, overlay, fast, hold: o.loop === false && !checking,
224
+ stopOnFail: !checking, reset, health, post,
225
+ });
226
+ (health.loopMs ??= []).push(Math.round(performance.now() - t0));
227
+ if (!r.ok && !checking) return; // live view stops at the failing step, showing it
228
+ if (i + 1 < loops && gate.state.kind === "playing") await sleep(fast ? FAST_HOLD_MS : HOLD_MS);
229
+ }
230
+ }