@bridge-ds/visual 0.2.3 → 0.3.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/dist/capture.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface LaunchOptions {
7
7
  channel?: string;
8
8
  }
9
9
  export declare function launch(o?: LaunchOptions): Promise<Browser>;
10
- export declare function newContext(browser: Browser, viewport: Viewport): Promise<BrowserContext>;
10
+ export declare function newContext(browser: Browser, viewport: Viewport, deviceScaleFactor?: number): Promise<BrowserContext>;
11
11
  export declare function newPage(ctx: BrowserContext): Promise<Page>;
12
12
  /** Waits for fonts, images, two frames, and a DOM whose markup stops changing (bounded). */
13
13
  export declare function settle(page: Page, o?: {
package/dist/index.d.ts CHANGED
@@ -3,5 +3,6 @@ export { selectImpact, storiesFromSource, storyId, storyComponent, type SelectIn
3
3
  export { diffPngs, boxesFromDiff, boxesFromCells, padTo, decodePng, encodePng, type DiffResult } from './diff.js';
4
4
  export { COMMENT_MARKER, hasVisualChange, rankShots, renderComment, summarize, summaryLine, type CommentOptions } from './manifest.js';
5
5
  export { DEFAULT_ROUTES, DEFAULT_TENANTS, routeUrl, storyUrl, shotKey } from './routes.js';
6
+ export { captureFigmaReferences, type ReferencesOptions, type ReferencesResult } from './references.js';
6
7
  export { linkNodeModules } from './workspace.js';
7
8
  export type * from './types.js';
package/dist/index.js CHANGED
@@ -793,6 +793,148 @@ function impactedModules(index, input) {
793
793
  return { modules, globalHits };
794
794
  }
795
795
 
796
+ // ../core/src/component-spec.ts
797
+ var COMPONENT_SPECS_VERSION = 1;
798
+ var variantKeyOf = (props) => Object.keys(props).sort().map((k) => `${k}=${props[k]}`).join(", ") || "Default";
799
+ function parseComponentSpecs(text) {
800
+ let data;
801
+ try {
802
+ data = JSON.parse(text);
803
+ } catch {
804
+ throw new Error("component-specs.json is not valid JSON.");
805
+ }
806
+ const f = data;
807
+ if (!f || typeof f !== "object" || !Array.isArray(f.components)) throw new Error('component-specs.json has no "components" list.');
808
+ if (f.version !== COMPONENT_SPECS_VERSION) throw new Error(`component-specs.json is version ${String(f.version)}; this tool reads version ${COMPONENT_SPECS_VERSION}.`);
809
+ return f;
810
+ }
811
+
812
+ // ../core/src/fidelity-references.ts
813
+ var FIGMA_REFERENCES_DIR = "figma-references";
814
+ var FIGMA_REFERENCES_MANIFEST = `${FIGMA_REFERENCES_DIR}/manifest.json`;
815
+ var FIGMA_REFERENCE_STORY = "internal-figma-reference--variant";
816
+ var FIGMA_FILL_WIDTH_TOKEN = "size.80";
817
+ var STATE_PSEUDO = {
818
+ default: "rest",
819
+ rest: "rest",
820
+ enabled: "rest",
821
+ hover: "hover",
822
+ hovered: "hover",
823
+ pressed: "active",
824
+ active: "active",
825
+ focus: "focus-visible",
826
+ focused: "focus-visible",
827
+ "focus visible": "focus-visible",
828
+ disabled: "disabled"
829
+ };
830
+ var iconName = (component) => component.replace(/^Icon\//, "");
831
+ var exportName = (name) => name.replace(/[^A-Za-z0-9]+/g, "");
832
+ function planReference(spec, variant, file) {
833
+ if (spec.view === "popup") return { ok: false, reason: "drawn open in Figma; the code image shows it closed" };
834
+ const props = { ...spec.fixed ?? {} };
835
+ let pseudo;
836
+ for (const axis of spec.axes) {
837
+ const value = variant.props[axis.name];
838
+ if (value === void 0) return { ok: false, reason: `the variant has no ${axis.name} value` };
839
+ if (axis.prop) {
840
+ props[axis.prop] = value === "true" ? true : value === "false" ? false : value;
841
+ continue;
842
+ }
843
+ if (axis.name === "Checked") {
844
+ props.checked = value === "true";
845
+ if (value === "mixed") props.indeterminate = true;
846
+ continue;
847
+ }
848
+ if (axis.name.toLowerCase() !== "state") return { ok: false, reason: `${axis.name} has no matching option in code` };
849
+ const s = STATE_PSEUDO[value.toLowerCase()];
850
+ if (!s) return { ok: false, reason: `the ${value} state has no code equivalent to render` };
851
+ if (s === "disabled") props.disabled = true;
852
+ else if (s !== "rest") pseudo = s;
853
+ }
854
+ const root = spec.parts.find((p) => !p.parent);
855
+ if (!root) return { ok: false, reason: "the spec has no root layer" };
856
+ const children = (id) => spec.parts.filter((p) => p.parent === id);
857
+ const textOf = (part) => {
858
+ const swapTo = variant.slots?.[part.id] ?? part.swap?.default;
859
+ if (part.swap && swapTo) {
860
+ const slot = file?.slots?.find((s) => s.name === swapTo);
861
+ if (!slot) return { reason: `${swapTo} is not in the specs` };
862
+ if (slot.kind !== "text" || !slot.text) return { reason: `Figma shows a placeholder (${swapTo}) that code has no example of` };
863
+ return slot.text.default;
864
+ }
865
+ const prop = spec.properties.find((p) => p.name === part.text && p.type === "TEXT");
866
+ return typeof prop?.default === "string" ? prop.default : part.name;
867
+ };
868
+ let text;
869
+ const icons = {};
870
+ for (const prop of spec.properties) {
871
+ if (prop.type === "TEXT") {
872
+ const hidden = spec.properties.some((b) => b.type === "BOOLEAN" && b.prop === prop.prop && b.default === false);
873
+ if (hidden && prop.prop) continue;
874
+ if (prop.prop === "children") text = String(prop.default);
875
+ else if (prop.prop) props[prop.prop] = String(prop.default);
876
+ continue;
877
+ }
878
+ const iconPart = spec.parts.find((p) => p.kind === "icon" && p.visible === prop.name);
879
+ if (prop.default === true && !iconPart && prop.prop && props[prop.prop] === void 0 && spec.example?.p?.[prop.prop] === void 0) props[prop.prop] = true;
880
+ }
881
+ for (const part of spec.parts) {
882
+ if (part.kind !== "icon" || !part.swap) continue;
883
+ const shown = part.visible ? spec.properties.find((p) => p.name === part.visible)?.default === true : true;
884
+ if (!shown) continue;
885
+ if (!part.swap.prop) return { ok: false, reason: `the ${part.name} icon has no matching option in code` };
886
+ icons[part.swap.prop] = iconName(variant.slots?.[part.id] ?? part.swap.default);
887
+ }
888
+ let parts;
889
+ const loose = spec.properties.filter((p) => p.type === "TEXT" && !p.prop);
890
+ const frames = children(root.id).filter((p) => p.kind === "frame");
891
+ const compound = text === void 0 && frames.length > 0 && frames.every((f) => spec.parts.some((p) => p.parent === f.id && p.kind === "text" && (p.swap || p.text === f.name)));
892
+ if (compound) {
893
+ parts = [];
894
+ for (const f of frames) {
895
+ const t = spec.parts.find((p) => p.parent === f.id && p.kind === "text");
896
+ const value = textOf(t);
897
+ if (typeof value !== "string") return { ok: false, reason: value.reason };
898
+ parts.push({ component: `${exportName(spec.name)}${exportName(f.name)}`, text: value });
899
+ }
900
+ }
901
+ for (const p of loose) {
902
+ if (p.name === "Value") continue;
903
+ const part = spec.parts.find((x) => x.text === p.name);
904
+ if (compound && part && part.parent !== root.id) continue;
905
+ if (part && /placeholder$/.test(part.id)) {
906
+ props.placeholder = String(p.default);
907
+ continue;
908
+ }
909
+ return { ok: false, reason: `the ${p.name} text has no matching option in code` };
910
+ }
911
+ const example = spec.example;
912
+ const exampleChildren = example?.children?.length ? example.children : void 0;
913
+ return {
914
+ ok: true,
915
+ render: {
916
+ component: exportName(spec.view || spec.fixed || example ? example?.c ?? spec.component ?? spec.name : spec.name),
917
+ props: { ...example?.p ?? {}, ...props },
918
+ ...exampleChildren ? { children: exampleChildren } : {},
919
+ ...text !== void 0 && !exampleChildren ? { text } : {},
920
+ ...parts && !exampleChildren ? { parts } : {},
921
+ ...Object.keys(icons).length ? { icons } : {},
922
+ ...pseudo ? { pseudo } : {},
923
+ ...root.fill ? { width: FIGMA_FILL_WIDTH_TOKEN } : {}
924
+ }
925
+ };
926
+ }
927
+ function referenceImagePath(component, key) {
928
+ const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
929
+ const file = key.split(",").map((kv) => slug(kv)).filter(Boolean).join("__");
930
+ return `${slug(component)}/${file || "default"}.png`;
931
+ }
932
+ function planReferences(file) {
933
+ return file.components.flatMap(
934
+ (spec) => spec.variants.map((v) => ({ component: spec.name, specHash: spec.hash, key: variantKeyOf(v.props), plan: planReference(spec, v, file) }))
935
+ );
936
+ }
937
+
796
938
  // ../core/src/node/git-local.ts
797
939
  import { execFile } from "node:child_process";
798
940
  function git(root, args, opts = {}) {
@@ -838,8 +980,8 @@ async function launch(o = {}) {
838
980
  args: ["--lang=en-US", "--disable-gpu", "--font-render-hinting=none", "--disable-lcd-text", "--force-color-profile=srgb", "--hide-scrollbars", "--disable-skia-runtime-opts", "--disable-renderer-backgrounding"]
839
981
  });
840
982
  }
841
- async function newContext(browser, viewport) {
842
- const ctx = await browser.newContext({ viewport, deviceScaleFactor: 1, reducedMotion: "reduce", colorScheme: "light", locale: "en-US", timezoneId: "UTC", serviceWorkers: "block" });
983
+ async function newContext(browser, viewport, deviceScaleFactor = 1) {
984
+ const ctx = await browser.newContext({ viewport, deviceScaleFactor, reducedMotion: "reduce", colorScheme: "light", locale: "en-US", timezoneId: "UTC", serviceWorkers: "block" });
843
985
  await ctx.addInitScript(INIT_SCRIPT);
844
986
  await ctx.route(
845
987
  /^https?:\/\/(?!127\.0\.0\.1[:/]|localhost[:/])/,
@@ -1272,9 +1414,9 @@ function selectImpact(input) {
1272
1414
  app
1273
1415
  };
1274
1416
  }
1275
- function storyId(title, exportName) {
1417
+ function storyId(title, exportName2) {
1276
1418
  const sanitize = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
1277
- const startCase = exportName.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
1419
+ const startCase = exportName2.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
1278
1420
  return `${sanitize(title)}--${sanitize(startCase)}`;
1279
1421
  }
1280
1422
  function storiesFromSource(files) {
@@ -1788,12 +1930,106 @@ async function runImpact(o) {
1788
1930
  log(`${result.summary} Manifest: ${relative2(process.cwd(), result.manifestPath) || result.manifestPath}`);
1789
1931
  return result;
1790
1932
  }
1933
+
1934
+ // src/references.ts
1935
+ import { existsSync as existsSync4 } from "node:fs";
1936
+ import { mkdir as mkdir4, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
1937
+ import { dirname as dirname3, join as join4 } from "node:path";
1938
+ async function captureFigmaReferences(o) {
1939
+ const log = o.log ?? (() => void 0);
1940
+ const scale = o.scale ?? 2;
1941
+ const brand = o.brand ?? "bridge";
1942
+ const theme = o.theme ?? "light";
1943
+ if (!existsSync4(join4(o.storybook, "index.json"))) throw new Error(`No built Storybook in ${o.storybook}: run npm run build-storybook first.`);
1944
+ const index = JSON.parse(await readFile4(join4(o.storybook, "index.json"), "utf8"));
1945
+ if (!index.entries[FIGMA_REFERENCE_STORY]) throw new Error(`The Storybook build has no ${FIGMA_REFERENCE_STORY} story (packages/react/src/stories/FigmaReference.stories.tsx).`);
1946
+ const specs = parseComponentSpecs(await readFile4(o.specs, "utf8"));
1947
+ const jobs = planReferences(specs).filter((j) => !o.only?.length || o.only.includes(j.component));
1948
+ const manifest = {
1949
+ version: 1,
1950
+ tool: "@bridge-ds/visual",
1951
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1952
+ sha: o.sha,
1953
+ scale,
1954
+ mode: { brand, theme, density: "comfortable" },
1955
+ storyId: FIGMA_REFERENCE_STORY,
1956
+ components: {}
1957
+ };
1958
+ for (const j of jobs) manifest.components[j.component] ??= { specHash: j.specHash, variants: {} };
1959
+ let captured = 0;
1960
+ let skipped = 0;
1961
+ const served = await serveDir(o.storybook);
1962
+ const browser = await launch();
1963
+ try {
1964
+ const ctx = await newContext(browser, { width: 1200, height: 800 }, scale);
1965
+ const page = await newPage(ctx);
1966
+ await page.goto(storyUrl(served.url, FIGMA_REFERENCE_STORY, brand, theme), { waitUntil: "load", timeout: 3e4 });
1967
+ await page.waitForSelector("[data-fidelity-root], [data-fidelity-error]", { state: "attached", timeout: 2e4 });
1968
+ await settle(page, { busy: false });
1969
+ log(`Capturing ${jobs.length} variants at ${scale}x (${brand} ${theme})`);
1970
+ for (const j of jobs) {
1971
+ const variants = manifest.components[j.component].variants;
1972
+ if (!j.plan.ok) {
1973
+ variants[j.key] = { skipped: j.plan.reason };
1974
+ skipped++;
1975
+ continue;
1976
+ }
1977
+ const plan = JSON.stringify(j.plan.render);
1978
+ await page.evaluate(
1979
+ ({ id, plan: plan2 }) => new Promise((resolve2) => {
1980
+ const ch = window.__STORYBOOK_ADDONS_CHANNEL__;
1981
+ const done = () => {
1982
+ clearTimeout(timer);
1983
+ ch.off("storyRendered", done);
1984
+ resolve2();
1985
+ };
1986
+ const timer = setTimeout(done, 1e4);
1987
+ ch.on("storyRendered", done);
1988
+ ch.emit("updateStoryArgs", { storyId: id, updatedArgs: { plan: plan2 } });
1989
+ }),
1990
+ { id: FIGMA_REFERENCE_STORY, plan }
1991
+ );
1992
+ await settle(page, { network: false, quiet: 2, interval: 40, busy: false });
1993
+ const error = await page.locator("[data-fidelity-error]").first().textContent({ timeout: 200 }).catch(() => null);
1994
+ let target = page.locator("[data-fidelity-root] > *").first();
1995
+ if (!error && !await target.count()) {
1996
+ const marked = page.locator("[data-fidelity-target]").first();
1997
+ await marked.waitFor({ state: "visible", timeout: 3e3 }).catch(() => void 0);
1998
+ await settle(page, { network: false, quiet: 2, interval: 40, busy: false });
1999
+ target = marked;
2000
+ }
2001
+ if (error || !await target.count()) {
2002
+ variants[j.key] = { skipped: error ?? "the code example did not render" };
2003
+ skipped++;
2004
+ continue;
2005
+ }
2006
+ const file = referenceImagePath(j.component, j.key);
2007
+ const path = join4(o.out, file);
2008
+ await mkdir4(dirname3(path), { recursive: true });
2009
+ await target.screenshot({ path, omitBackground: true, animations: "disabled", caret: "hide", scale: "device" });
2010
+ const box = await target.boundingBox();
2011
+ variants[j.key] = { file, width: Math.round(box?.width ?? 0), height: Math.round(box?.height ?? 0) };
2012
+ captured++;
2013
+ }
2014
+ await ctx.close();
2015
+ } finally {
2016
+ await browser.close().catch(() => void 0);
2017
+ await served.close();
2018
+ }
2019
+ await mkdir4(o.out, { recursive: true });
2020
+ const manifestPath = join4(o.out, "manifest.json");
2021
+ await writeFile4(manifestPath, `${JSON.stringify(manifest, null, 2)}
2022
+ `);
2023
+ log(`${captured} images, ${skipped} variants skipped. ${manifestPath}`);
2024
+ return { manifest, manifestPath, captured, skipped };
2025
+ }
1791
2026
  export {
1792
2027
  COMMENT_MARKER,
1793
2028
  DEFAULT_ROUTES,
1794
2029
  DEFAULT_TENANTS,
1795
2030
  boxesFromCells,
1796
2031
  boxesFromDiff,
2032
+ captureFigmaReferences,
1797
2033
  changedTokens,
1798
2034
  decodePng,
1799
2035
  diffPngs,
@@ -0,0 +1,22 @@
1
+ import { type FigmaReferenceManifest } from '@bridge-ds/core';
2
+ export interface ReferencesOptions {
3
+ /** Built Storybook folder (storybook-static). */
4
+ storybook: string;
5
+ /** component-specs.json path. */
6
+ specs: string;
7
+ out: string;
8
+ sha: string;
9
+ scale?: number;
10
+ brand?: string;
11
+ theme?: string;
12
+ /** Only these components (names). */
13
+ only?: string[];
14
+ log?: (line: string) => void;
15
+ }
16
+ export interface ReferencesResult {
17
+ manifest: FigmaReferenceManifest;
18
+ manifestPath: string;
19
+ captured: number;
20
+ skipped: number;
21
+ }
22
+ export declare function captureFigmaReferences(o: ReferencesOptions): Promise<ReferencesResult>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridge-ds/visual",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Bridge visual impact analysis: screenshots the stories and app screens a design system change touches, at the base and head refs, and pixel-diffs them into before/after/diff images and a JSON manifest.",
6
6
  "license": "MIT",
@@ -47,7 +47,7 @@
47
47
  "build:package": "node ../../scripts/build-packages.mjs visual"
48
48
  },
49
49
  "dependencies": {
50
- "@bridge-ds/core": "^0.5.0",
50
+ "@bridge-ds/core": "^0.6.0",
51
51
  "pixelmatch": "7.1.0",
52
52
  "playwright-core": "1.63.0",
53
53
  "pngjs": "7.0.0"