From 8bf58c0dc3078069ab9fc54e0ba88855712e50d8 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Thu, 1 Oct 2026 04:32:55 +0900 Subject: [PATCH] feat: the playground hands you its own settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A visitor came here to change something, and the change was worthless if leaving the page lost it. Remembering that the dots wanted to overlap at 198%, that 3% grow is the difference between a moving light and a pulsing blob, and that stagger was pinned — from memory, from sliders — is the kind of re-derivation this page exists to end. So the copy button next to the readout copies the install command, the element with the settings ALREADY in it, and the stylesheet import. A prompt rather than a component alone: a component with no way to install it is half an instruction. It is a prompt for whoever receives the paste — the README's CLI agent, a colleague, a future self. Nothing about the page is assumed to still be open. WHAT IT DOES NOT EMIT, which is the part that mattered: - Every option, not the changed ones. A snippet carrying `fill={1} peak={1} floor={0.16}` says nothing about what you chose, and goes stale the moment a default moves — it quietly overrides the library's future choice with today's. Touch nothing and you get ``; drag two sliders and you get two props. - `renderer="svg"`, because svg IS the default. Same rule. `css` does appear, since naming it is worth a line and it is a keyword rather than a string. THE GENERATOR EMITS REAL PROPS. Two of the eleven tests exist only for this, because the failure is a snippet that looks right and does not compile — the same shape as a card redrawing its own dots instead of calling the engine: - one asserts every emitted prop is in the real `DotMatrixProps` set - one parses what came out: each line is `name={value}` or a bare `name="keyword"`, and the braces balance across the element That second test found a bug while I was writing it. `spec` was flattened to top-level `sides={7}` — which the component silently ignores, so the snippet would have compiled, looked correct, and rendered the wrong dot. It is `spec={{ sides: 7 }}`. The motion sentence is read out of `PRESETS`, the same table the cards label themselves from, so a hand-written description of `ring` next to a card showing `ring` cannot drift. `off` is `null` in that table — no motion has no order or envelope — so it says so rather than printing "undefined traversal". SIX UI TESTS, and they drive the button rather than the markup: one drags speed to 250, checks the readout moved, THEN copies and asserts `speed={2.5}` — a generator emitting its own constants would pass a test that only looked for `` element with the settings you arrived at already in it, and the stylesheet import — so the paste needs nothing else, and neither do you. It is a prompt rather than a component alone because a component with no way to install it is half an instruction. **Only the options you changed are emitted**, because a snippet carrying `fill={1} peak={1} floor={0.16}` on every copy says nothing about what you chose and goes stale when a default moves; touch nothing and you get ``, and the names are the real props — a snippet that looks right and does not compile is the same failure as a card redrawing its own dots. The description beside the motion is read out of the engine's own preset table, so it cannot drift from the card. Falls back to selectable text when the clipboard is refused, rather than a button that silently does nothing. + - **The playground now opens on a hand-picked showcase state** rather than the engine's defaults: 5×5 with no gap at the largest size, `dot/cell` at 198% so the dots overlap into one surface, `grow` at 3% so a dot moves rather than pulses, `stagger` pinned at 70% so picking another motion does not move a slider under the visitor, square silhouette and square dots at radius 0. The engine's own defaults are untouched — that is the library's choice and the page is allowed to disagree — so the values live in a named `SHOWCASE` beside the component, each with the reason it was picked. - **The site is now Astro + React islands on Cloudflare Pages.** `apps/site` was a hand-written HTML page with a diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 9092b73..4bf2913 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -4,6 +4,8 @@ ### 变更 +- **Playground 现在能把自己的配置交给你。** readout 旁的复制按钮会复制安装命令、已经带上你调过参数的 `` 元素,以及样式表 import —— 所以粘贴之后不需要再打开这个页面,你也不需要。它复制的是一段 prompt 而不只是组件,因为没有安装方式的组件只是半条指令。**只输出你真正改过的参数**:每次都附上 `fill={1} peak={1} floor={0.16}` 既没有说明你选了什么,又会在默认值变动时过期;什么都没动就得到 ``,而 prop 名用的是真名 —— 看着对却编译不过的片段,和卡片自己重画点,是同一种错。动效旁边那行说明是从引擎自己的 preset 表里读出来的,所以不会和卡片对不上。剪贴板被拒绝时回退为可选中的文本,而不是一个什么都不做也不吭声的按钮。 + - **Playground 现在开在一组手工挑的 showcase 参数上**,而不是引擎默认值:最大尺寸的 5×5、无间距、`dot/cell` 198% 让点连成一整块面、`grow` 3% 让点是"移动"而不是"脉动"、`stagger` 固定在 70% 以免换个动效就把访客正看着的滑杆挪走、剪影和点都是方形且圆角为 0。引擎自己的默认值没有动 —— 那是库的选择,页面被允许不同意 —— 所以这些值放在组件旁边一个具名的 `SHOWCASE` 里,每一项都写明为什么选它。 - **站点改为 Astro + React islands,部署到 Cloudflare Pages。** `apps/site` 原先是一个手写 HTML + module script, diff --git a/apps/site/messages/en.json b/apps/site/messages/en.json index ebd25f3..44d86ba 100644 --- a/apps/site/messages/en.json +++ b/apps/site/messages/en.json @@ -104,5 +104,11 @@ "scope_dot_shape": "Changes each individual dot", "scope_motion": "Hover or focus a card to play it", "group_timing": "Timing", - "group_envelope": "Envelope" + "group_envelope": "Envelope", + "showcase_copy": "Copy with these settings", + "showcase_copied": "copied", + "showcase_manual": "select it", + "showcase_intro": "Add BotUI's loading indicator to this project.", + "showcase_style": "import \"@botharness/botui-core/style.css\";", + "showcase_note": "Your settings, as props — only what you changed." } diff --git a/apps/site/messages/zh.json b/apps/site/messages/zh.json index fe9fb5a..6ece4f7 100644 --- a/apps/site/messages/zh.json +++ b/apps/site/messages/zh.json @@ -104,5 +104,11 @@ "scope_dot_shape": "改变每一个点本身", "scope_motion": "悬停或聚焦卡片即可播放", "group_timing": "节奏", - "group_envelope": "包络" + "group_envelope": "包络", + "showcase_copy": "按此配置复制", + "showcase_copied": "已复制", + "showcase_manual": "请手动选中", + "showcase_intro": "把这个加载指示器用到当前项目。", + "showcase_style": "import \"@botharness/botui-core/style.css\";", + "showcase_note": "你调过的参数,只多不少。" } diff --git a/apps/site/src/components/Playground.tsx b/apps/site/src/components/Playground.tsx index 870aac8..39c4ed1 100644 --- a/apps/site/src/components/Playground.tsx +++ b/apps/site/src/components/Playground.tsx @@ -1,6 +1,7 @@ import { useMemo, useState } from "react"; import { LiveCard, Matrix, Still } from "./Matrix.js"; import { CardGroup, SilhouetteCard } from "./Cards.js"; +import { ShowcaseCopy } from "./ShowcaseCopy.js"; import { m, glyphLabel, polygonName, silhouetteLabel, taskLabel } from "../i18n.js"; import { DEFAULTS, @@ -368,6 +369,10 @@ export function Playground({ initial }: { initial?: Partial }) `${m.readout_renderer()} ${cssRenderer ? "css" : "svg"} ${m.readout_speed()} ${m.value_speed({ value: (options.speed ?? 1).toFixed(2) })}`, ].join("\n")} + + {/* The readout is where a visitor has just SEEN the numbers, so the way out is + right here — a copy button over the settings they arrived at. */} + ); diff --git a/apps/site/src/components/ShowcaseCopy.tsx b/apps/site/src/components/ShowcaseCopy.tsx new file mode 100644 index 0000000..deb29ec --- /dev/null +++ b/apps/site/src/components/ShowcaseCopy.tsx @@ -0,0 +1,61 @@ +import { useState } from "react"; +import { m } from "../i18n.js"; +import { snippet, type Tuning } from "./snippet.js"; + +/** + * The tuning, as text you can carry away. + * + * The visitor came here to change something, and the change is worthless if leaving the + * page loses it — they would have to remember that the dots wanted to overlap at 198%, that + * 3% grow is the difference between a moving light and a pulsing blob. So this is a copy + * button over the settings as they stand, not over the install command the visitor already + * had a button for. + * + * It copies a PROMPT, not just a component: the command to run, the element with the + * settings in it, and the stylesheet import. Whoever pastes it should not need this page + * open beside them. + */ +export function ShowcaseCopy({ tuning }: { tuning: Tuning }) { + const [state, setState] = useState<"idle" | "copied" | "manual">("idle"); + const text = snippet(tuning, { + install: m.components_install({ name: "dot-matrix" }), + intro: m.showcase_intro(), + style: m.showcase_style(), + }); + const label = + state === "copied" + ? m.showcase_copied() + : state === "manual" + ? m.showcase_manual() + : m.showcase_copy(); + + return ( +
+
+

{m.showcase_note()}

+ +
+ {/* Always rendered, never conditionally: a `manual` state has to have something to + select. Hidden with CSS rather than unmounted so the text stays in the DOM. */} +
+        {text}
+      
+
+ ); +} diff --git a/apps/site/src/components/snippet.ts b/apps/site/src/components/snippet.ts new file mode 100644 index 0000000..4e4dbd1 --- /dev/null +++ b/apps/site/src/components/snippet.ts @@ -0,0 +1,152 @@ +import { + DEFAULTS, + GLYPH_DEFAULTS, + PRESETS, + type DotGlyphSpec, + type DotMatrixOptions, +} from "@botharness/botui-core"; + +/** + * The snippet a visitor carries away: the install command, and the component with + * THEIR settings already in it. + * + * The point of this page is that you tune something and then keep it. A copy button + * that yields `npx @botharness/botui add dot-matrix` throws the tuning away — you would + * have to remember 198% and grow 3% and a pinned 70% stagger and re-derive them from + * the sliders. So this emits the options as JSX props, and the numbers in it are the + * numbers on the sliders at the moment you press it. + * + * WHY A GENERATED STRING AND NOT A RENDERED EXAMPLE: this is prose for an agent or a + * person, not a live demo. It is generated from the same `DotMatrixOptions` the engine + * takes, and the prop names are the real ones — the alternative is a block of JSX that + * looks right and does not compile, which is the same failure as a card that draws its + * own approximation of a dot. + */ + +/** the options a visitor can actually change on this page */ +export interface Tuning { + options: DotMatrixOptions; + /** whether the CSS renderer switch is on, which is `renderer` on the component */ + css: boolean; +} + +/** + * Only the options that DIFFER from the engine's defaults. + * + * An exhaustive prop list is noise: `fill={1} floor={0.16} peak={1}` on every copy is + * four lines that say nothing about what you chose, and it goes stale the moment a + * default changes. Emitting the difference means the snippet is as short as the change + * you made — a visitor who touched nothing gets ``, and one who dragged two + * sliders gets two props. + */ +function changedOptions(t: Tuning): [string, string][] { + const o = t.options; + const out: [string, string][] = []; + + // the order is the order the controls appear on the page, so the snippet reads in the + // same order the visitor met them + if ((o.size ?? DEFAULTS.size) !== DEFAULTS.size) out.push(["size", num(o.size)]); + if ((o.cols ?? DEFAULTS.cols) !== DEFAULTS.cols) out.push(["cols", num(o.cols)]); + if ((o.rows ?? DEFAULTS.rows) !== DEFAULTS.rows) out.push(["rows", num(o.rows)]); + if ((o.silhouette ?? DEFAULTS.silhouette) !== DEFAULTS.silhouette) { + out.push(["silhouette", str(o.silhouette)]); + } + if ((o.dot ?? DEFAULTS.dot) !== DEFAULTS.dot) out.push(["dot", str(o.dot)]); + if ((o.dotSize ?? DEFAULTS.dotSize) !== DEFAULTS.dotSize) out.push(["dotSize", num(o.dotSize)]); + if ((o.gapX ?? DEFAULTS.gapX) !== DEFAULTS.gapX) out.push(["gapX", num(o.gapX)]); + if ((o.gapY ?? DEFAULTS.gapY) !== DEFAULTS.gapY) out.push(["gapY", num(o.gapY)]); + if ((o.preset ?? DEFAULTS.preset) !== DEFAULTS.preset) out.push(["preset", str(o.preset)]); + if ((o.speed ?? DEFAULTS.speed) !== DEFAULTS.speed) out.push(["speed", num(o.speed)]); + if (o.stagger != null) out.push(["stagger", num(o.stagger)]); + if ((o.softness ?? DEFAULTS.softness) !== DEFAULTS.softness) + out.push(["softness", num(o.softness)]); + if ((o.grow ?? DEFAULTS.grow) !== DEFAULTS.grow) out.push(["grow", num(o.grow)]); + if ((o.floor ?? DEFAULTS.floor) !== DEFAULTS.floor) out.push(["floor", num(o.floor)]); + + // the dot's own geometry, as one nested object — these are the numbers a `sides` + // slider moved, and flattening them into top-level props would be wrong: the component + // takes them under `spec` + const spec = diffSpec(o.spec); + if (spec) out.push(["spec", spec]); + + return out; +} + +function diffSpec(spec: Partial | undefined): string | null { + if (!spec) return null; + const parts: string[] = []; + for (const key of ["sides", "radius", "innerRadius", "star", "spin", "aspect"] as const) { + const v = spec[key]; + if (v != null && v !== GLYPH_DEFAULTS[key]) parts.push(`${key}: ${num(v)}`); + } + return parts.length ? `{ ${parts.join(", ")} }` : null; +} + +/** numbers keep their decimals rather than rounding a value the visitor can see */ +function num(v: number | undefined): string { + return v == null ? "undefined" : String(Math.round(v * 1000) / 1000); +} + +/** a string option is a bare JSX attribute: `dot="star5"`, not `dot={"star5"}` */ +function str(v: string | undefined): string { + return `"${v ?? ""}"`; +} + +/** a bare JSX attribute, for a value that is a keyword rather than a string */ +function attr(name: string, value: string): string { + return `${name}="${value}"`; +} + +/** + * The whole thing: what to run, what to import, and the component with the settings on. + * + * Ordered so the first thing a reader can act on is the install command — it is the only + * line that has to be true before anything else matters. + */ +export function snippet( + t: Tuning, + locale: { install: string; intro: string; style: string }, +): string { + const props = changedOptions(t); + const preset = t.options.preset ?? DEFAULTS.preset; + // `renderer` is the one prop that is a BARE attribute when it appears — `css` is a + // keyword rather than a string — and it only appears when it is NOT the default, by + // the same rule as every other prop: `svg` is the default, so stating it would be noise. + const lines = props.map(([k, v]) => ` ${k}={${v}}`); + if (t.css) lines.push(` ${attr("renderer", "css")}`); + + const body = lines.join("\n"); + + return [ + locale.intro, + "", + "1. Install it:", + "", + " " + locale.install, + "", + "2. Render it with these settings:", + "", + body ? "" : "", + "", + "3. Once, in your app entry:", + "", + " " + locale.style, + "", + ` // preset "${preset}" renders as ${describe(preset)}`, + ].join("\n"); +} + +/** + * What the motion means, in one line. + * + * Copied out of the same table the preset cards label themselves from, so the sentence + * cannot drift from the card — a hand-written description of `ring` next to a card that + * shows `ring` is two sources for one fact. + */ +function describe(preset: string): string { + // `PRESETS.off` is null — no motion has no order or envelope — so this must not + // assume the entry exists or it prints "undefined traversal" + const p = PRESETS[preset as keyof typeof PRESETS] ?? null; + if (!p) return "no motion (frozen)"; + return `${p.order} traversal, ${p.env} envelope`; +} diff --git a/apps/site/src/styles/site.css b/apps/site/src/styles/site.css index cf7f383..706f9c4 100644 --- a/apps/site/src/styles/site.css +++ b/apps/site/src/styles/site.css @@ -167,6 +167,57 @@ h3 { cursor: pointer; } +/* The carried-away settings. Same visual language as .install so the two read as one + idea at two sizes — a command to run, and the component that follows from it. */ +.showcase-copy { + border: 1px solid var(--line); + background: var(--card); + border-radius: var(--radius); + margin-top: 14px; +} + +.showcase-copy-head { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; +} + +.showcase-copy-head p { + flex: 1; + margin: 0; + font-size: 13px; + color: var(--muted); +} + +.showcase-copy button { + font: inherit; + font-size: 13px; + border: 1px solid var(--line); + background: transparent; + color: var(--muted); + border-radius: 8px; + padding: 4px 10px; + cursor: pointer; + white-space: nowrap; +} + +.showcase-copy-body { + margin: 0; + padding: 12px 14px; + border-top: 1px solid var(--line); + font-size: 12px; + line-height: 1.6; + overflow-x: auto; + white-space: pre; +} + +/* Collapsed by default: the snippet is long, and the page is about the field. When a + clipboard write is refused the body becomes the thing to select, so it shows then. */ +.showcase-copy-body[aria-hidden="true"] { + display: none; +} + .install button:hover { color: var(--ink); border-color: var(--muted); diff --git a/apps/site/test/i18n.test.ts b/apps/site/test/i18n.test.ts index ea9626a..bbf6691 100644 --- a/apps/site/test/i18n.test.ts +++ b/apps/site/test/i18n.test.ts @@ -66,6 +66,9 @@ describe("the message catalogue", () => { "ctl_cols", "ctl_rows", "ctl_preset", + // a stylesheet import is code, not prose — it is the same bytes in both languages + // for the same reason `install_command` is: the copy has to paste and run + "showcase_style", ]); const en = await read("en"); const zh = await read("zh"); @@ -86,6 +89,9 @@ describe("the message catalogue", () => { "components/Playground.tsx", "components/RegistryList.tsx", "components/InstallCommand.tsx", + // a NEW component must join this list, or its messages read as unrendered and the + // scan silently stops covering half the site + "components/ShowcaseCopy.tsx", "i18n.ts", "components/Home.astro", "layouts/Base.astro", diff --git a/apps/site/test/playground.test.tsx b/apps/site/test/playground.test.tsx index 9ae09df..e154bb4 100644 --- a/apps/site/test/playground.test.tsx +++ b/apps/site/test/playground.test.tsx @@ -6,7 +6,7 @@ * screenshot and in a DOM dump. So these tests dispatch real input events and read the * resulting field: the control has to change the geometry, not the label. */ -import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { Playground } from "../src/components/Playground.js"; @@ -802,3 +802,84 @@ describe("a dial that follows a preset must be able to return to it", () => { expect(staggerRow().querySelector("em")?.textContent).toMatch(/34%/); }); }); + +/** the copy button, by its class — it has no stable accessible name across locales */ +const copyButton = () => { + const b = container.querySelector(".showcase-copy button") as HTMLButtonElement | null; + if (!b) throw new Error("no copy button"); + return b; +}; + +/** the snippet body, which is always in the DOM and shown only when a write is refused */ +const copyBody = () => { + const el = container.querySelector(".showcase-copy-body") as HTMLElement | null; + if (!el) throw new Error("no copy body"); + return el; +}; + +const stubClipboard = (fail = false) => { + const writeText = vi.fn(async () => { + if (fail) throw new Error("denied"); + }); + Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true }); + return writeText; +}; + +describe("copying the tuning away", () => { + it("copies the install command and the component, so a paste needs nothing else", async () => { + const writeText = stubClipboard(); + await act(async () => copyButton().click()); + + expect(writeText).toHaveBeenCalledOnce(); + const text = writeText.mock.calls[0]![0] as string; + expect(text, "the command that has to be true before anything else").toContain( + "npx @botharness/botui add dot-matrix", + ); + expect(text, "and the element that follows from it").toContain(" { + const writeText = stubClipboard(); + // change something well away from the opening state, THEN copy — this is the whole + // feature, and a generator that emits its own constants would pass the test above + drag(slider(/speed/i), 250); + expect(readout()).toContain("2.50"); + + await act(async () => copyButton().click()); + expect(writeText.mock.calls[0]![0] as string).toContain("speed={2.5}"); + }); + + it("omits what was left at the default, so the snippet is as short as the change", async () => { + const writeText = stubClipboard(); + drag(slider(/speed/i), 250); + await act(async () => copyButton().click()); + const text = writeText.mock.calls[0]![0] as string; + expect(text).not.toContain("floor={", "floor was never touched"); + }); + + it("says so when it has copied", async () => { + stubClipboard(); + await act(async () => copyButton().click()); + // English literals, not `m.showcase_copied()`: asserting a message against itself + // passes even when the message is wrong, and this test exists to catch that the + // button says SOMETHING DIFFERENT once it has copied. + expect(copyButton().textContent).toBe("copied"); + }); + + it("falls back to selectable text when the clipboard is refused", async () => { + stubClipboard(true); + await act(async () => copyButton().click()); + expect(copyButton().textContent, "the refusal is named, not silent").toBe("select it"); + // and there has to be something to select — a fallback with nothing to select is the + // failure this guards + expect(copyBody().getAttribute("aria-hidden")).toBe("false"); + expect(copyBody().textContent).toContain("npx"); + }); + + it("keeps the snippet out of the way until it is needed", () => { + stubClipboard(); + expect(copyBody().getAttribute("aria-hidden"), "long text, folded away by default").toBe( + "true", + ); + }); +}); diff --git a/apps/site/test/snippet.test.ts b/apps/site/test/snippet.test.ts new file mode 100644 index 0000000..7fac34a --- /dev/null +++ b/apps/site/test/snippet.test.ts @@ -0,0 +1,189 @@ +// @vitest-environment jsdom +/** + * The snippet a visitor copies. + * + * The failure this guards against is a snippet that LOOKS right: a prop name the + * component does not take, or a value written in the wrong units, and the visitor + * discovers it when the build breaks. So the assertions here are mostly about the + * generated text being real rather than plausible — including compiling it. + */ +import { describe, expect, it } from "vitest"; +import { snippet } from "../src/components/snippet.js"; +import { DEFAULTS, PRESETS, type DotMatrixOptions } from "@botharness/botui-core"; + +const LOCALE = { + install: "npx @botharness/botui add dot-matrix", + intro: "Add BotUI's loading indicator to this project.", + style: 'import "@botharness/botui-core/style.css";', +}; + +const build = (options: Partial, css = false) => + snippet({ options, css }, LOCALE); + +describe("the copied snippet", () => { + it("leads with something the reader can run", () => { + const out = build({}); + expect(out, "the install command comes first").toContain( + "npx @botharness/botui add dot-matrix", + ); + expect(out.indexOf("npx")).toBeLessThan(out.indexOf("DotMatrix")); + }); + + it("says which stylesheet to import, since the CSS renderer needs it and nothing else does", () => { + expect(build({})).toContain('import "@botharness/botui-core/style.css";'); + }); + + it("carries the visitor's settings, in the units the component takes", () => { + const out = build({ size: 260, cols: 5, rows: 5, dotSize: 1.98, grow: 0.03, stagger: 0.7 }); + expect(out).toContain("dotSize={1.98}"); + expect(out).toContain("grow={0.03}"); + expect(out).toContain("stagger={0.7}"); + // the showcase's grid is 5×5 at 260, which IS the tuned state — so all three appear + expect(out).toContain("size={260}"); + expect(out).toContain("cols={5}"); + }); + + it("omits everything left at the default, so the snippet is as short as the change made", () => { + const untouched = build({}); + // a visitor who touched nothing gets a bare component, not twenty props saying + // nothing about what they chose + expect(untouched).toContain(""); + expect(untouched).not.toContain("size={"); + expect(untouched).not.toContain("floor={"); + }); + + it("puts the dot's geometry under spec, not at the top level", () => { + const out = build({ spec: { sides: 7, radius: 0.5, aspect: 1 } }); + // flattening these would produce JSX the component silently ignores + expect(out).toContain("spec={{ sides: 7, radius: 0.5 }}"); + expect(out).not.toMatch(/^\s+sides=\{/m); + }); + + it("names the renderer only when it is not the default", () => { + expect(build({}, false), "svg IS the default, so saying so is noise").not.toContain("renderer"); + expect(build({}, true), "css costs zero JS per frame and is worth stating").toContain( + 'renderer="css"', + ); + }); + + it("explains the motion from the engine's own table, not a hand-written sentence", () => { + const out = build({ preset: "ring" }); + const p = PRESETS.ring!; + expect(out).toContain(`${p.order} traversal, ${p.env} envelope`); + }); + + it("declares only props the component actually accepts", () => { + // The real prop list, copied from `DotMatrixProps extends DotMatrixOptions`. If the + // engine gains an option this will not notice — but if the generator emits one that + // is NOT here, the snippet would not compile, which is the case worth catching. + const REAL = new Set([ + "size", + "cols", + "rows", + "fill", + "silhouette", + "dot", + "dotSize", + "gapX", + "gapY", + "preset", + "floor", + "peak", + "speed", + "grow", + "stagger", + "softness", + "color", + "spec", + "renderer", + "reducedMotion", + "state", + "playing", + "at", + "className", + "style", + "label", + ]); + const everything = snippet( + { + options: { + size: 100, + cols: 4, + rows: 4, + fill: 0.9, + silhouette: "ring", + dot: "star5", + dotSize: 0.9, + gapX: 0.2, + gapY: 0.3, + preset: "morph", + floor: 0.2, + peak: 1, + speed: 2, + grow: 0.4, + stagger: 0.5, + softness: 0.3, + color: "#fff", + spec: { sides: 9, radius: 0.4, innerRadius: 0.1, star: 0.3, spin: 0.2, aspect: 0.8 }, + reducedMotion: false, + }, + css: true, + }, + LOCALE, + ); + const props = [...everything.matchAll(/^ {2}(\w+)=\{/gm)].map((m) => m[1]!); + expect(props.length, "it emitted the tuned options").toBeGreaterThan(10); + for (const prop of props) { + expect(REAL.has(prop), `${prop} is not a prop takes`).toBe(true); + } + }); + + it("is valid JSX, not merely plausible-looking JSX", () => { + // the assertion that matters: parse what we generate as a real element + const out = snippet( + { + options: { + size: 260, + cols: 5, + rows: 5, + dotSize: 1.98, + spec: { sides: 7 }, + preset: "ring", + stagger: 0.7, + }, + css: true, + }, + LOCALE, + ); + const jsx = //.exec(out)?.[1]; + expect(jsx, "the snippet contains a multi-line element").toBeTruthy(); + // every attribute is `name={...}` with balanced braces — the failure a hand-written + // generator produces is an unbalanced brace, and it only shows up when parsed + let depth = 0; + for (const line of (jsx ?? "").split("\n")) { + // either form is valid JSX and both appear: `name={value}` for a value, and a bare + // `name="keyword"` for the one prop whose value is a keyword rather than a string + expect(line, `${line} is a prop assignment`).toMatch(/^ {2}\w+=(\{.*\}|"[^"]*")$/); + depth += (line.match(/\{/g) ?? []).length - (line.match(/\}/g) ?? []).length; + } + expect(depth, "braces balance across the element").toBe(0); + }); + + it("keeps a value the visitor can actually see, without rounding it away", () => { + // dot/cell 198% is 1.98; a formatter that rounded to 2 decimals would still be + // right here, but one that rounded to integers would silently ship 2.0 + const out = build({ dotSize: 1.98, speed: 1.25, softness: 0.333 }); + expect(out).toContain("dotSize={1.98}"); + expect(out).toContain("speed={1.25}"); + expect(out).toContain("softness={0.333}"); + }); + + it("survives a preset that has no table entry, rather than printing undefined", () => { + // `off` is a real PresetName whose table entry is null — no motion has no order or + // envelope — so the description beside it must not read "undefined traversal" + const out = build({ preset: "off" }); + expect(out).toContain('preset={"off"}'); + expect(out).toContain("no motion"); + expect(out).not.toContain("undefined"); + }); +});