@segnavia/capture 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/dist/geometry.d.ts +17 -0
- package/dist/geometry.js +118 -0
- package/dist/host.d.ts +24 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.js +206 -0
- package/dist/shot.d.ts +36 -0
- package/dist/shot.js +114 -0
- package/package.json +32 -4
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 modstudio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Annotation, Box, TextDirection } from "@segnavia/format";
|
|
2
|
+
//#region src/geometry.d.ts
|
|
3
|
+
export declare const SIDES: readonly ["left", "right", "top", "bottom"];
|
|
4
|
+
export type Side = (typeof SIDES)[number];
|
|
5
|
+
export interface AnnotationSpec {
|
|
6
|
+
number?: number;
|
|
7
|
+
arrow?: Side | 'auto';
|
|
8
|
+
label?: string;
|
|
9
|
+
highlight?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface Viewport {
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
}
|
|
15
|
+
export declare function chooseArrowSide(box: Box, viewport: Viewport, preferred?: Side | 'auto', direction?: TextDirection): Side;
|
|
16
|
+
export declare function layoutAnnotation(box: Box, spec: AnnotationSpec, viewport: Viewport, direction?: TextDirection): Annotation;
|
|
17
|
+
//#endregion
|
package/dist/geometry.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
//#region src/geometry.ts
|
|
2
|
+
const SIDES = [
|
|
3
|
+
"left",
|
|
4
|
+
"right",
|
|
5
|
+
"top",
|
|
6
|
+
"bottom"
|
|
7
|
+
];
|
|
8
|
+
const RING_PADDING = 6;
|
|
9
|
+
const ARROW_LENGTH = 96;
|
|
10
|
+
const ARROW_GAP = 10;
|
|
11
|
+
const BADGE_OFFSET = 4;
|
|
12
|
+
const EDGE_MARGIN = 8;
|
|
13
|
+
function padBox(box, padding = RING_PADDING) {
|
|
14
|
+
return {
|
|
15
|
+
x: box.x - padding,
|
|
16
|
+
y: box.y - padding,
|
|
17
|
+
width: box.width + padding * 2,
|
|
18
|
+
height: box.height + padding * 2
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function roomAround(box, viewport) {
|
|
22
|
+
return {
|
|
23
|
+
left: box.x,
|
|
24
|
+
right: viewport.width - (box.x + box.width),
|
|
25
|
+
top: box.y,
|
|
26
|
+
bottom: viewport.height - (box.y + box.height)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function chooseArrowSide(box, viewport, preferred = "auto", direction = "ltr") {
|
|
30
|
+
const room = roomAround(box, viewport);
|
|
31
|
+
if (preferred !== "auto") {
|
|
32
|
+
if (room[preferred] < 72) throw new Error(`There is ${Math.round(room[preferred])}px of room on the ${preferred}; an arrow needs 72px.`);
|
|
33
|
+
return preferred;
|
|
34
|
+
}
|
|
35
|
+
const order = direction === "rtl" ? [
|
|
36
|
+
"right",
|
|
37
|
+
"left",
|
|
38
|
+
"top",
|
|
39
|
+
"bottom"
|
|
40
|
+
] : SIDES;
|
|
41
|
+
return order.reduce((best, side) => room[side] > room[best] ? side : best, order[0]);
|
|
42
|
+
}
|
|
43
|
+
function arrowGeometry(ring, side, viewport) {
|
|
44
|
+
const center = {
|
|
45
|
+
x: ring.x + ring.width / 2,
|
|
46
|
+
y: ring.y + ring.height / 2
|
|
47
|
+
};
|
|
48
|
+
const room = roomAround(ring, viewport);
|
|
49
|
+
const span = Math.max(24, Math.min(ARROW_LENGTH, room[side] - ARROW_GAP - EDGE_MARGIN));
|
|
50
|
+
const left = ring.x - ARROW_GAP;
|
|
51
|
+
const right = ring.x + ring.width + ARROW_GAP;
|
|
52
|
+
const top = ring.y - ARROW_GAP;
|
|
53
|
+
const bottom = ring.y + ring.height + ARROW_GAP;
|
|
54
|
+
switch (side) {
|
|
55
|
+
case "left": return {
|
|
56
|
+
head: {
|
|
57
|
+
x: left,
|
|
58
|
+
y: center.y
|
|
59
|
+
},
|
|
60
|
+
tail: {
|
|
61
|
+
x: left - span,
|
|
62
|
+
y: center.y
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
case "right": return {
|
|
66
|
+
head: {
|
|
67
|
+
x: right,
|
|
68
|
+
y: center.y
|
|
69
|
+
},
|
|
70
|
+
tail: {
|
|
71
|
+
x: right + span,
|
|
72
|
+
y: center.y
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
case "top": return {
|
|
76
|
+
head: {
|
|
77
|
+
x: center.x,
|
|
78
|
+
y: top
|
|
79
|
+
},
|
|
80
|
+
tail: {
|
|
81
|
+
x: center.x,
|
|
82
|
+
y: top - span
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
case "bottom": return {
|
|
86
|
+
head: {
|
|
87
|
+
x: center.x,
|
|
88
|
+
y: bottom
|
|
89
|
+
},
|
|
90
|
+
tail: {
|
|
91
|
+
x: center.x,
|
|
92
|
+
y: bottom + span
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function layoutAnnotation(box, spec, viewport, direction = "ltr") {
|
|
98
|
+
const ring = padBox(box);
|
|
99
|
+
const arrow = spec.arrow !== void 0 || spec.label !== void 0 ? {
|
|
100
|
+
...arrowGeometry(ring, chooseArrowSide(ring, viewport, spec.arrow ?? "auto", direction), viewport),
|
|
101
|
+
label: spec.label ?? null
|
|
102
|
+
} : null;
|
|
103
|
+
const badgeX = direction === "rtl" ? ring.x + BADGE_OFFSET : ring.x + ring.width - BADGE_OFFSET;
|
|
104
|
+
const badge = spec.number === void 0 ? null : {
|
|
105
|
+
center: {
|
|
106
|
+
x: badgeX,
|
|
107
|
+
y: ring.y + BADGE_OFFSET
|
|
108
|
+
},
|
|
109
|
+
number: spec.number
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
ring: spec.highlight === false ? null : ring,
|
|
113
|
+
badge,
|
|
114
|
+
arrow
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { SIDES, arrowGeometry, chooseArrowSide, layoutAnnotation, padBox, roomAround };
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ShotSpec } from "./shot.js";
|
|
2
|
+
import { Browser, BrowserContextOptions, Page, Response } from "playwright-core";
|
|
3
|
+
//#region src/host.d.ts
|
|
4
|
+
export interface FlowIdentity {
|
|
5
|
+
name: string;
|
|
6
|
+
session?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface HostSession<Extras> {
|
|
9
|
+
context?: BrowserContextOptions;
|
|
10
|
+
contextFor?(flow: FlowIdentity): BrowserContextOptions | Promise<BrowserContextOptions>;
|
|
11
|
+
injectCss?: string;
|
|
12
|
+
extras?(page: Page, flow: FlowIdentity): Extras | Promise<Extras>;
|
|
13
|
+
beforeNavigate?(url: string): Promise<void>;
|
|
14
|
+
observe?(response: Response, flow: FlowIdentity): void;
|
|
15
|
+
refuseShot?(shot: ShotSpec, flow: FlowIdentity): string | null;
|
|
16
|
+
close?(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export interface Host<Extras = Record<string, never>> {
|
|
19
|
+
open(env: {
|
|
20
|
+
browser: Browser;
|
|
21
|
+
baseUrl: string;
|
|
22
|
+
}): Promise<HostSession<Extras>>;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { chooseArrowSide, layoutAnnotation } from "./geometry.js";
|
|
2
|
+
import { ImageOutput, ShotSpec, Target } from "./shot.js";
|
|
3
|
+
import { FlowIdentity, Host, HostSession } from "./host.js";
|
|
4
|
+
import { Manifest, Shot } from "@segnavia/format";
|
|
5
|
+
import { BrowserContextOptions, Page } from "playwright-core";
|
|
6
|
+
//#region src/index.d.ts
|
|
7
|
+
export interface FlowContext<Extras> {
|
|
8
|
+
flow: string;
|
|
9
|
+
page: Page;
|
|
10
|
+
extras: Extras;
|
|
11
|
+
log(message: string): void;
|
|
12
|
+
currentStep(): string;
|
|
13
|
+
step<T>(name: string, body: () => Promise<T>): Promise<T>;
|
|
14
|
+
goto(url: string): Promise<void>;
|
|
15
|
+
until(predicate: string | ((arg: unknown) => unknown), what: string, options?: {
|
|
16
|
+
arg?: unknown;
|
|
17
|
+
timeout?: number;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
viewport(size?: {
|
|
20
|
+
width: number;
|
|
21
|
+
height: number;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
setLocalStorage(entries: Record<string, string | number | boolean>): Promise<void>;
|
|
24
|
+
shot(spec: ShotSpec): Promise<Shot>;
|
|
25
|
+
}
|
|
26
|
+
export interface Flow<Extras> extends FlowIdentity {
|
|
27
|
+
run(flow: FlowContext<Extras>): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export interface CaptureConfig {
|
|
30
|
+
baseUrl: string;
|
|
31
|
+
outputDirectory: string;
|
|
32
|
+
executablePath: string;
|
|
33
|
+
launchArgs?: string[];
|
|
34
|
+
viewport?: {
|
|
35
|
+
width: number;
|
|
36
|
+
height: number;
|
|
37
|
+
};
|
|
38
|
+
scale?: number;
|
|
39
|
+
context?: BrowserContextOptions;
|
|
40
|
+
output?: ImageOutput;
|
|
41
|
+
flows?: string[];
|
|
42
|
+
meta?: Record<string, unknown>;
|
|
43
|
+
log?: (message: string) => void;
|
|
44
|
+
}
|
|
45
|
+
export interface FlowResult {
|
|
46
|
+
name: string;
|
|
47
|
+
ok: boolean;
|
|
48
|
+
error?: string;
|
|
49
|
+
failureScreenshot?: string;
|
|
50
|
+
shots: Shot[];
|
|
51
|
+
}
|
|
52
|
+
export interface CaptureRun {
|
|
53
|
+
results: FlowResult[];
|
|
54
|
+
manifest: Manifest;
|
|
55
|
+
ok: boolean;
|
|
56
|
+
}
|
|
57
|
+
export declare function selectFlows<F extends {
|
|
58
|
+
name: string;
|
|
59
|
+
}>(flows: F[], requested?: string[]): F[];
|
|
60
|
+
export declare function capture<Extras>(host: Host<Extras>, flows: Flow<Extras>[], config: CaptureConfig): Promise<CaptureRun>;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { type FlowIdentity, type Host, type HostSession, type ImageOutput, type ShotSpec, type Target, chooseArrowSide, layoutAnnotation };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { chooseArrowSide, layoutAnnotation } from "./geometry.js";
|
|
2
|
+
import { takeShot } from "./shot.js";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { Manifest } from "@segnavia/format";
|
|
6
|
+
import { chromium } from "playwright-core";
|
|
7
|
+
//#region src/index.ts
|
|
8
|
+
const DEFAULTS = {
|
|
9
|
+
viewport: {
|
|
10
|
+
width: 1280,
|
|
11
|
+
height: 720
|
|
12
|
+
},
|
|
13
|
+
scale: 2,
|
|
14
|
+
output: { format: "png" }
|
|
15
|
+
};
|
|
16
|
+
function selectFlows(flows, requested) {
|
|
17
|
+
if (!requested || requested.length === 0) return flows;
|
|
18
|
+
const matches = (flow, name) => flow.name === name || flow.name.startsWith(`${name}.`);
|
|
19
|
+
const unknown = requested.filter((name) => !flows.some((flow) => matches(flow, name)));
|
|
20
|
+
if (unknown.length > 0) throw new Error(`No flow is named ${unknown.join(", ")}. Flows: ${flows.map((flow) => flow.name).join(", ")}`);
|
|
21
|
+
return flows.filter((flow) => requested.some((name) => matches(flow, name)));
|
|
22
|
+
}
|
|
23
|
+
function injectStyle(css) {
|
|
24
|
+
const apply = () => {
|
|
25
|
+
const style = document.createElement("style");
|
|
26
|
+
style.textContent = css;
|
|
27
|
+
document.documentElement.appendChild(style);
|
|
28
|
+
};
|
|
29
|
+
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", apply);
|
|
30
|
+
else apply();
|
|
31
|
+
}
|
|
32
|
+
async function runFlow(flow, browser, session, config) {
|
|
33
|
+
const staging = path.join(config.outputDirectory, ".staging", flow.name);
|
|
34
|
+
rmSync(staging, {
|
|
35
|
+
recursive: true,
|
|
36
|
+
force: true
|
|
37
|
+
});
|
|
38
|
+
mkdirSync(staging, { recursive: true });
|
|
39
|
+
const identity = {
|
|
40
|
+
name: flow.name,
|
|
41
|
+
session: flow.session
|
|
42
|
+
};
|
|
43
|
+
const shots = [];
|
|
44
|
+
const state = {
|
|
45
|
+
step: "setting up",
|
|
46
|
+
number: 0
|
|
47
|
+
};
|
|
48
|
+
const context = await browser.newContext({
|
|
49
|
+
baseURL: config.baseUrl,
|
|
50
|
+
viewport: config.viewport,
|
|
51
|
+
deviceScaleFactor: config.scale,
|
|
52
|
+
colorScheme: "light",
|
|
53
|
+
reducedMotion: "reduce",
|
|
54
|
+
...config.context,
|
|
55
|
+
...session.context,
|
|
56
|
+
...session.contextFor ? await session.contextFor(identity) : {}
|
|
57
|
+
});
|
|
58
|
+
if (session.injectCss) await context.addInitScript(injectStyle, session.injectCss);
|
|
59
|
+
const page = await context.newPage();
|
|
60
|
+
try {
|
|
61
|
+
if (session.observe) page.on("response", (response) => session.observe?.(response, identity));
|
|
62
|
+
const flowContext = {
|
|
63
|
+
flow: flow.name,
|
|
64
|
+
page,
|
|
65
|
+
extras: session.extras ? await session.extras(page, identity) : {},
|
|
66
|
+
log: (message) => config.log(` ${message}`),
|
|
67
|
+
currentStep: () => state.step,
|
|
68
|
+
async step(name, body) {
|
|
69
|
+
state.step = name;
|
|
70
|
+
state.number += 1;
|
|
71
|
+
config.log(` ${flow.name} › ${name}`);
|
|
72
|
+
return body();
|
|
73
|
+
},
|
|
74
|
+
async goto(url) {
|
|
75
|
+
await session.beforeNavigate?.(url);
|
|
76
|
+
await page.goto(url);
|
|
77
|
+
},
|
|
78
|
+
async until(predicate, what, options = {}) {
|
|
79
|
+
const timeout = options.timeout ?? 3e4;
|
|
80
|
+
try {
|
|
81
|
+
await page.waitForFunction(predicate, options.arg, { timeout });
|
|
82
|
+
} catch {
|
|
83
|
+
throw new Error(`waited ${timeout / 1e3}s for ${what}`);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
async viewport(size) {
|
|
87
|
+
await page.setViewportSize(size ?? config.viewport);
|
|
88
|
+
},
|
|
89
|
+
async setLocalStorage(entries) {
|
|
90
|
+
if (!page.url().startsWith(config.baseUrl)) await flowContext.goto("/");
|
|
91
|
+
await page.evaluate((pairs) => {
|
|
92
|
+
for (const [key, value] of Object.entries(pairs)) localStorage.setItem(key, String(value));
|
|
93
|
+
}, entries);
|
|
94
|
+
},
|
|
95
|
+
async shot(spec) {
|
|
96
|
+
const refusal = session.refuseShot?.(spec, identity);
|
|
97
|
+
if (refusal) throw new Error(`Step "${state.step}": ${refusal}`);
|
|
98
|
+
if (shots.some((shot) => shot.key === spec.key)) throw new Error(`Shot key ${spec.key} is taken twice in ${flow.name}.`);
|
|
99
|
+
const shot = await takeShot(page, spec, {
|
|
100
|
+
step: state.step,
|
|
101
|
+
directory: staging,
|
|
102
|
+
scale: config.scale,
|
|
103
|
+
output: config.output
|
|
104
|
+
});
|
|
105
|
+
const recorded = {
|
|
106
|
+
...shot,
|
|
107
|
+
meta: {
|
|
108
|
+
...config.meta,
|
|
109
|
+
...shot.meta,
|
|
110
|
+
flow: flow.name,
|
|
111
|
+
step: Math.max(state.number, 1),
|
|
112
|
+
stepName: state.step
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
shots.push(recorded);
|
|
116
|
+
config.log(` captured ${spec.key}`);
|
|
117
|
+
return recorded;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
await flow.run(flowContext);
|
|
121
|
+
for (const shot of shots) for (const file of [shot.file, shot.annotatedFile]) if (file) renameSync(path.join(staging, file), path.join(config.outputDirectory, file));
|
|
122
|
+
return {
|
|
123
|
+
name: flow.name,
|
|
124
|
+
ok: true,
|
|
125
|
+
shots
|
|
126
|
+
};
|
|
127
|
+
} catch (error) {
|
|
128
|
+
const failureScreenshot = path.join(config.outputDirectory, ".failures", `${flow.name}.png`);
|
|
129
|
+
mkdirSync(path.dirname(failureScreenshot), { recursive: true });
|
|
130
|
+
await page.screenshot({ path: failureScreenshot }).catch(() => {});
|
|
131
|
+
const message = error.message.split("\n")[0] ?? "";
|
|
132
|
+
return {
|
|
133
|
+
name: flow.name,
|
|
134
|
+
ok: false,
|
|
135
|
+
error: message.startsWith("Step \"") ? message : `Step "${state.step}": ${message}`,
|
|
136
|
+
failureScreenshot,
|
|
137
|
+
shots: []
|
|
138
|
+
};
|
|
139
|
+
} finally {
|
|
140
|
+
await context.close();
|
|
141
|
+
rmSync(staging, {
|
|
142
|
+
recursive: true,
|
|
143
|
+
force: true
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function writeManifest(directory, results) {
|
|
148
|
+
const file = path.join(directory, "manifest.json");
|
|
149
|
+
const manifest = existsSync(file) ? Manifest.parse(JSON.parse(readFileSync(file, "utf8"))) : {
|
|
150
|
+
shots: {},
|
|
151
|
+
updatedAt: ""
|
|
152
|
+
};
|
|
153
|
+
for (const shot of results.flatMap((result) => result.shots)) manifest.shots[shot.key] = shot;
|
|
154
|
+
manifest.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
155
|
+
writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
156
|
+
return manifest;
|
|
157
|
+
}
|
|
158
|
+
async function capture(host, flows, config) {
|
|
159
|
+
const resolved = {
|
|
160
|
+
...DEFAULTS,
|
|
161
|
+
...config,
|
|
162
|
+
log: config.log ?? (() => {})
|
|
163
|
+
};
|
|
164
|
+
const selected = selectFlows(flows, config.flows);
|
|
165
|
+
mkdirSync(resolved.outputDirectory, { recursive: true });
|
|
166
|
+
const browser = await chromium.launch({
|
|
167
|
+
executablePath: resolved.executablePath,
|
|
168
|
+
args: [
|
|
169
|
+
"--hide-scrollbars",
|
|
170
|
+
"--force-color-profile=srgb",
|
|
171
|
+
"--font-render-hinting=none",
|
|
172
|
+
...config.launchArgs ?? []
|
|
173
|
+
]
|
|
174
|
+
});
|
|
175
|
+
const results = [];
|
|
176
|
+
try {
|
|
177
|
+
const session = await host.open({
|
|
178
|
+
browser,
|
|
179
|
+
baseUrl: resolved.baseUrl
|
|
180
|
+
});
|
|
181
|
+
try {
|
|
182
|
+
for (const flow of selected) {
|
|
183
|
+
resolved.log(`flow ${flow.name}`);
|
|
184
|
+
const result = await runFlow(flow, browser, session, resolved);
|
|
185
|
+
resolved.log(result.ok ? ` ok: ${result.shots.length} shots` : ` FAILED: ${result.error}`);
|
|
186
|
+
results.push(result);
|
|
187
|
+
}
|
|
188
|
+
} finally {
|
|
189
|
+
await session.close?.();
|
|
190
|
+
}
|
|
191
|
+
} finally {
|
|
192
|
+
await browser.close();
|
|
193
|
+
}
|
|
194
|
+
const manifest = writeManifest(resolved.outputDirectory, results);
|
|
195
|
+
writeFileSync(path.join(resolved.outputDirectory, "report.json"), `${JSON.stringify({
|
|
196
|
+
meta: config.meta ?? {},
|
|
197
|
+
flows: results
|
|
198
|
+
}, null, 2)}\n`);
|
|
199
|
+
return {
|
|
200
|
+
results,
|
|
201
|
+
manifest,
|
|
202
|
+
ok: results.every((result) => result.ok)
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
export { capture, chooseArrowSide, layoutAnnotation, selectFlows };
|
package/dist/shot.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AnnotationSpec } from "./geometry.js";
|
|
2
|
+
import { Shot } from "@segnavia/format";
|
|
3
|
+
import { Page } from "playwright-core";
|
|
4
|
+
//#region src/shot.d.ts
|
|
5
|
+
export type Target = ({
|
|
6
|
+
role: Parameters<Page['getByRole']>[0];
|
|
7
|
+
name?: string | RegExp;
|
|
8
|
+
} | {
|
|
9
|
+
label: string | RegExp;
|
|
10
|
+
} | {
|
|
11
|
+
text: string | RegExp;
|
|
12
|
+
} | {
|
|
13
|
+
css: string;
|
|
14
|
+
}) & {
|
|
15
|
+
exact?: boolean;
|
|
16
|
+
within?: Target;
|
|
17
|
+
};
|
|
18
|
+
export interface ShotSpec {
|
|
19
|
+
key: string;
|
|
20
|
+
title: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
tags?: string[];
|
|
23
|
+
annotate?: Array<AnnotationSpec & {
|
|
24
|
+
target: Target;
|
|
25
|
+
}>;
|
|
26
|
+
settleMs?: number;
|
|
27
|
+
meta?: Record<string, unknown>;
|
|
28
|
+
}
|
|
29
|
+
export interface ImageOutput {
|
|
30
|
+
format: 'png' | 'webp' | 'jpeg';
|
|
31
|
+
quality?: number[];
|
|
32
|
+
maxBytes?: number;
|
|
33
|
+
annotated?: boolean;
|
|
34
|
+
color?: string;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
package/dist/shot.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { layoutAnnotation } from "./geometry.js";
|
|
2
|
+
import { writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { SHOT_KEY } from "@segnavia/format";
|
|
5
|
+
import { annotationSvg } from "@segnavia/frame/svg";
|
|
6
|
+
import { captureImage } from "@segnavia/render";
|
|
7
|
+
//#region src/shot.ts
|
|
8
|
+
function describeTarget(target) {
|
|
9
|
+
const scope = target.within ? `${describeTarget(target.within)}.` : "";
|
|
10
|
+
if ("role" in target) return `${scope}getByRole(${JSON.stringify(target.role)}${target.name === void 0 ? "" : `, { name: ${String(target.name)} }`})`;
|
|
11
|
+
if ("label" in target) return `${scope}getByLabel(${String(target.label)})`;
|
|
12
|
+
if ("text" in target) return `${scope}getByText(${String(target.text)})`;
|
|
13
|
+
return `${scope}locator(${JSON.stringify(target.css)})`;
|
|
14
|
+
}
|
|
15
|
+
function locate(page, target) {
|
|
16
|
+
const root = target.within ? locate(page, target.within) : page;
|
|
17
|
+
const exact = target.exact ?? true;
|
|
18
|
+
if ("role" in target) return root.getByRole(target.role, target.name === void 0 ? {} : {
|
|
19
|
+
name: target.name,
|
|
20
|
+
exact
|
|
21
|
+
});
|
|
22
|
+
if ("label" in target) return root.getByLabel(target.label, { exact });
|
|
23
|
+
if ("text" in target) return root.getByText(target.text, { exact });
|
|
24
|
+
return root.locator(target.css);
|
|
25
|
+
}
|
|
26
|
+
async function resolveOne(page, target, step) {
|
|
27
|
+
const locator = locate(page, target).filter({ visible: true });
|
|
28
|
+
const count = await locator.count();
|
|
29
|
+
if (count !== 1) throw new Error(`Step "${step}": ${describeTarget(target)} matched ${count} visible elements; expected exactly one.`);
|
|
30
|
+
return locator;
|
|
31
|
+
}
|
|
32
|
+
async function settle(page, ms = 400) {
|
|
33
|
+
const viewport = page.viewportSize();
|
|
34
|
+
if (viewport) await page.mouse.move(viewport.width - 1, viewport.height - 1);
|
|
35
|
+
await page.waitForLoadState("networkidle", { timeout: 15e3 }).catch(() => {});
|
|
36
|
+
await page.evaluate(() => document.fonts.ready.then(() => true));
|
|
37
|
+
await page.waitForFunction(() => [...document.images].every((image) => image.complete), null, { timeout: 15e3 }).catch(() => {});
|
|
38
|
+
await page.waitForTimeout(ms);
|
|
39
|
+
}
|
|
40
|
+
async function measure(page, spec, step, direction) {
|
|
41
|
+
const viewport = page.viewportSize();
|
|
42
|
+
if (!viewport) throw new Error(`Step "${step}": the page has no fixed viewport to measure against.`);
|
|
43
|
+
const annotations = [];
|
|
44
|
+
for (const [index, annotation] of (spec.annotate ?? []).entries()) {
|
|
45
|
+
const locator = await resolveOne(page, annotation.target, step);
|
|
46
|
+
if (index === 0) await locator.scrollIntoViewIfNeeded();
|
|
47
|
+
const box = await locator.boundingBox();
|
|
48
|
+
const inside = box && box.x >= -1 && box.y >= -1 && box.x + box.width <= viewport.width + 1 && box.y + box.height <= viewport.height + 1;
|
|
49
|
+
if (!box || !inside) throw new Error(`Step "${step}": ${describeTarget(annotation.target)} is not fully inside the ${viewport.width}x${viewport.height} viewport.`);
|
|
50
|
+
try {
|
|
51
|
+
annotations.push(layoutAnnotation(box, annotation, viewport, direction));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error(`Step "${step}": ${error.message}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return annotations;
|
|
57
|
+
}
|
|
58
|
+
const OVERLAY_ID = "__segnavia-annotations";
|
|
59
|
+
function drawOverlay({ id, svg }) {
|
|
60
|
+
const overlay = document.createElement("div");
|
|
61
|
+
overlay.id = id;
|
|
62
|
+
overlay.style.cssText = "position:fixed;inset:0;z-index:2147483647;pointer-events:none";
|
|
63
|
+
overlay.innerHTML = svg;
|
|
64
|
+
for (const group of overlay.querySelectorAll("g")) group.setAttribute("style", "opacity:1");
|
|
65
|
+
document.documentElement.appendChild(overlay);
|
|
66
|
+
}
|
|
67
|
+
function removeOverlay(id) {
|
|
68
|
+
document.getElementById(id)?.remove();
|
|
69
|
+
}
|
|
70
|
+
async function takeShot(page, spec, options) {
|
|
71
|
+
if (!SHOT_KEY.test(spec.key)) throw new Error(`Shot key "${spec.key}" must be lowercase words joined by dots or dashes.`);
|
|
72
|
+
if (!spec.title) throw new Error(`Shot ${spec.key} needs a title.`);
|
|
73
|
+
await settle(page, spec.settleMs);
|
|
74
|
+
const direction = await page.evaluate(() => getComputedStyle(document.documentElement).direction === "rtl" ? "rtl" : "ltr");
|
|
75
|
+
const annotations = await measure(page, spec, options.step, direction);
|
|
76
|
+
const viewport = page.viewportSize();
|
|
77
|
+
const extension = options.output.format === "jpeg" ? "jpg" : options.output.format;
|
|
78
|
+
const encode = () => captureImage(page, {
|
|
79
|
+
format: options.output.format,
|
|
80
|
+
quality: options.output.quality,
|
|
81
|
+
limits: { maxBytes: options.output.maxBytes }
|
|
82
|
+
}, false);
|
|
83
|
+
const file = `${spec.key}.${extension}`;
|
|
84
|
+
writeFileSync(path.join(options.directory, file), await encode());
|
|
85
|
+
let annotatedFile = null;
|
|
86
|
+
if (options.output.annotated && annotations.length > 0) {
|
|
87
|
+
annotatedFile = `${spec.key}.annotated.${extension}`;
|
|
88
|
+
await page.evaluate(drawOverlay, {
|
|
89
|
+
id: OVERLAY_ID,
|
|
90
|
+
svg: annotationSvg(viewport, annotations, options.output.color)
|
|
91
|
+
});
|
|
92
|
+
try {
|
|
93
|
+
writeFileSync(path.join(options.directory, annotatedFile), await encode());
|
|
94
|
+
} finally {
|
|
95
|
+
await page.evaluate(removeOverlay, OVERLAY_ID).catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
key: spec.key,
|
|
100
|
+
title: spec.title,
|
|
101
|
+
description: spec.description ?? null,
|
|
102
|
+
tags: spec.tags ?? [],
|
|
103
|
+
file,
|
|
104
|
+
annotatedFile,
|
|
105
|
+
size: viewport,
|
|
106
|
+
scale: options.scale,
|
|
107
|
+
dir: direction,
|
|
108
|
+
annotations,
|
|
109
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
110
|
+
meta: spec.meta ?? {}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
export { describeTarget, locate, resolveOne, settle, takeShot };
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segnavia/capture",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/modstudio/segnavia.git",
|
|
9
|
+
"directory": "packages/capture"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"@segnavia/source": "./src/index.ts",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@segnavia/format": "0.2.0",
|
|
30
|
+
"playwright-core": "1.55.1",
|
|
31
|
+
"@segnavia/frame": "0.2.0",
|
|
32
|
+
"@segnavia/render": "0.2.0"
|
|
33
|
+
}
|
|
34
|
+
}
|
package/README.md
DELETED