From 273a37dce941384f393c2280a4425bb5a4682a60 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Thu, 1 Oct 2026 05:53:57 +0900 Subject: [PATCH] feat: every motion can be told which way to go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `spiral`, `snake`, `columnSnake` all went one way and there was no way to say otherwise. Direction is now `direction={["counterClockwise", "insideOut"]}` — one option for every motion rather than a dozen presets, because it is a property of the TRAVERSAL, not of the envelope. It composes the way `grow` composes with a preset it did not choose. IT IS A LIST, not a scalar, and that is the load-bearing decision. A row-major snake has two INDEPENDENT axes: which end of the first row leads, and whether the rows run top to bottom. Its four corners are four distinct drawings, and `reverse: true` could only ever reach two of them. My first attempt used a single `Direction` scalar and the test caught it immediately — `rightToLeft` was flipping the parity AND reversing, because a reversal-flavoured helper could not tell the two axes apart. Token names are relative to the MOTION, not the screen. For a column-snake `bottomToTop` is the axis it travels along; for a row-snake it is the axis it is series-ordered in. Both are true, which is why each order reads its own tokens rather than a shared helper — and why the snake tests assert the SAME token means opposite things in the two orders. NOT OFFERED WHERE IT MEANS NOTHING. A spiral has a winding and a radius; a ring has a radius and NO winding, because a Chebyshev distance is not a walk around a circle. A `clockwise` card there would be a control claiming something the engine cannot do — the same defect as offering the CSS renderer for `columns` and quietly falling back. `ORDER_DIRECTION_AXES` is what a UI reads, so the control and the engine cannot disagree, and there is a test that a ring refuses a winding. THE CSS RENDERER NEEDED NO WORK, which is why this was cheap. It hands the motion to the browser as a per-cell `--botui-o` and a negative `animation-delay`, so re-ranking the traversal re-ranks the whole field. That claim is load-bearing, so it is asserted: if a reversal ever needed its own keyframes, that test fails instead of a field quietly running the wrong way. TWO BUGS THE TESTS CAUGHT, both mine: - the counter-clockwise spiral dropped the bottom-right corner of every ring, so a 5×5 covered 23 of its 25 cells. Found by the "reverses to the same cell set" invariant rather than by looking at it, because nothing else noticed two missing dots. - `PRESETS.off` is null, so reading `PRESETS[preset]!.order` crashed the whole playground the moment `off` was selected. Existing tests caught it; the direction groups now disappear on `off`, which is right anyway — no motion, no axis. Forward is drawn SELECTED while no token is set, because forward IS the motion's own direction. A third "auto" card would be a fifth card drawn identically to `forward`, and a radio group with nothing checked breaks the one-selection-per-group contract every other card group on the page keeps. Choosing forward again clears the token, so the snippet only ever claims a direction you actually overrode. Also fixed a blind spot in the i18n guard: its scan was `[a-z0-9_]+`, which silently truncates a camelCase key like `dir_leftToRight` to `dir_leftToR` and reports every direction label as unrendered. These were the first camelCase keys in the catalogue. 206 tests (was 177), oxlint 0, registry ok, both changelog ledgers, one new invariant in AGENTS.md. --- AGENTS.md | 6 + CHANGELOG.md | 4 + CHANGELOG.zh.md | 4 + apps/site/messages/en.json | 15 +- apps/site/messages/zh.json | 15 +- apps/site/src/components/Playground.tsx | 98 +++++++++- apps/site/src/components/snippet.ts | 6 + apps/site/src/i18n.ts | 34 ++++ apps/site/test/i18n.test.ts | 5 +- apps/site/test/playground.test.tsx | 98 ++++++++++ apps/site/test/snippet.test.ts | 16 +- packages/core/src/dot-matrix/field.ts | 4 +- packages/core/src/dot-matrix/layout.ts | 11 +- packages/core/src/dot-matrix/order.ts | 226 +++++++++++++++++++--- packages/core/src/index.ts | 14 +- packages/core/src/types.ts | 51 ++++- packages/core/test/direction.test.ts | 237 ++++++++++++++++++++++++ packages/core/test/dom.test.ts | 17 ++ 18 files changed, 821 insertions(+), 40 deletions(-) create mode 100644 packages/core/test/direction.test.ts diff --git a/AGENTS.md b/AGENTS.md index b0b1846..082fe7c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,6 +60,12 @@ If Astro ships TS 7 support, wire `astro check` back in rather than leaving this - **Preserve the size algebra.** `cell = size / ((n - 1)(1 + gap) + dotSize)` is solved, not clipped, which is what keeps the field landing exactly on the box at any `dotSize` — including above 1, where the dots touch. If you change it, the invariant tests in `packages/core/test/dot-matrix.test.ts` are the specification. +- **Direction is per-order AXES, not a global "reverse".** `direction` is a list of axis tokens + (`["counterClockwise", "insideOut"]`), and each order reads only its own — `ORDER_DIRECTION_AXES` is the + contract a UI reads to know what to offer. Offer from that table and never from a hardcoded list: a + concentric ring has no winding (a Chebyshev distance is not a walk around a circle), so `clockwise` on it + would be a control claiming something the engine cannot do. Reversal is `1 - o`, but reversing the VALUE + does not reverse a winding, which is why the two are separate tokens rather than one `reverse` flag. - **Comments explain why, and cite the trap.** The strongest comments in this repo record a bug that was found the hard way (a seam discontinuity at `p = 0`, a blur that dissolved the crest, a quantised order that no envelope could smooth). Keep that density; do not add comments that restate the code. diff --git a/CHANGELOG.md b/CHANGELOG.md index c26150c..8770656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ### Changed +- **Every motion can now be told which way to go.** `direction` is a list of axis tokens — `leftToRight`, `topToBottom`, `clockwise`, `outsideIn` and their opposites — and a spiral winds _and_ chooses an end, so `direction={["counterClockwise", "insideOut"]}` is one motion rather than two presets. It is a **list** because a row-major snake has two independent axes: which end of the first row leads, and whether the rows run top to bottom. Its four corners are four distinct drawings, and a single `reverse` flag could only ever reach two of them. The token names are relative to the motion rather than the screen, which is why `bottomToTop` flips a column-snake's travel but reverses a row-snake's rows. +- **Each traversal is offered only the directions it can honour.** A spiral gets a winding and a radius; a ring gets a radius and **no winding**, because a Chebyshev distance is not a walk around a circle — a `clockwise` card there would be a control claiming something the engine cannot do. `ORDER_DIRECTION_AXES` is the table a UI reads, so a control and the engine cannot disagree about what exists. +- **The CSS renderer needed no work.** It hands the motion to the browser as a per-cell `--botui-o` and a negative `animation-delay`, so re-ranking the traversal re-ranks the whole field. There is a test asserting that, because the claim is load-bearing: if a reversal ever needed its own keyframes, it would fail there rather than as a field that quietly runs the wrong way. + - **The copy button moved to the bottom of the field, and became the page's only primary action.** It was in the sidebar, where it read as one more control among forty. But you tuned _the field_, so the button that takes the tuning away belongs to the field: it now sits inside the sticky stage, spanning both columns, full width, in the accent colour. Everything else on this page exists to help you arrive at a setting; this is the one that lets you leave with it, and it should look like the difference. `var(--accent)` rather than a hex, so dark mode and any future theme follow — and the focus ring is offset, because the button _is_ the accent and an accent outline against an accent fill is invisible. - **The playground can hand you its own settings.** A copy button next to the readout copies the install command, the `` 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. diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 18b5547..859459c 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -4,6 +4,10 @@ ### 变更 +- **每个动效现在都能指定行进方向。** `direction` 是一组轴 token —— `leftToRight`、`topToBottom`、`clockwise`、`outsideIn` 及各自反向 —— 而螺旋既能选缠绕方向也能选哪一端领先,所以 `direction={["counterClockwise", "insideOut"]}` 是一个动效,而不是两个 preset。它是**列表**,因为行优先的蛇形有两个互相独立的轴:第一行从哪端开始,以及各行是自上而下还是自下而上。它的四个角是四种不同的图形,而单一的 `reverse` 开关最多只能到达其中两个。token 名相对于动效而非屏幕 —— 这正是 `bottomToTop` 对列蛇形意味着翻转行进方向、而对行蛇形意味着翻转行序的原因。 +- **每种遍历只提供它真能实现的方向。** 螺旋有缠绕轴和半径轴;ring 有半径轴而**没有缠绕轴**,因为 Chebyshev 距离不是绕圈行走 —— 在那里放一张 `clockwise` 卡片,就是一个声称引擎做不到的控件。`ORDER_DIRECTION_AXES` 是 UI 读取的表,所以控件和引擎不可能对"存在什么"产生分歧。 +- **CSS 渲染器不需要任何改动。** 它把动效交给浏览器的方式是每个 cell 一个 `--botui-o` 加负的 `animation-delay`,所以重新排名遍历就等于重新排名整个场。这里有测试断言,因为这个主张是承重的:如果某个反转哪天需要自己的 keyframes,会在那里失败,而不是变成一个悄悄走错方向的场。 + - **复制按钮移到了场的底部,并且成了全站唯一的主操作。** 它原先在右侧栏,读起来像四十个控件中的又一个。但你调的是**这个场**,所以把调好的东西带走的按钮属于这个场:它现在位于 sticky stage 内部、跨两列、满宽、用 accent 色。这个页面上其他一切都是为了帮你"调到某个值"而存在的;只有这一个是为了让你带着值离开,它也应该看起来就是那个区别。用 `var(--accent)` 而非硬编码色值,深色模式和以后换主题都会跟着走 —— focus ring 做了偏移,因为按钮**就是** accent,accent 描边压在 accent 填充上是看不见的。 - **Playground 现在能把自己的配置交给你。** readout 旁的复制按钮会复制安装命令、已经带上你调过参数的 `` 元素,以及样式表 import —— 所以粘贴之后不需要再打开这个页面,你也不需要。它复制的是一段 prompt 而不只是组件,因为没有安装方式的组件只是半条指令。**只输出你真正改过的参数**:每次都附上 `fill={1} peak={1} floor={0.16}` 既没有说明你选了什么,又会在默认值变动时过期;什么都没动就得到 ``,而 prop 名用的是真名 —— 看着对却编译不过的片段,和卡片自己重画点,是同一种错。动效旁边那行说明是从引擎自己的 preset 表里读出来的,所以不会和卡片对不上。剪贴板被拒绝时回退为可选中的文本,而不是一个什么都不做也不吭声的按钮。 diff --git a/apps/site/messages/en.json b/apps/site/messages/en.json index 44d86ba..a4fd02d 100644 --- a/apps/site/messages/en.json +++ b/apps/site/messages/en.json @@ -110,5 +110,18 @@ "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." + "showcase_note": "Your settings, as props — only what you changed.", + "dir_group": "Direction", + "dir_axis_along": "Direction of travel", + "dir_axis_series": "Which way the rows are visited", + "dir_axis_winding": "Winding", + "dir_axis_radius": "Which end leads", + "dir_leftToRight": "Left → right", + "dir_rightToLeft": "Right → left", + "dir_topToBottom": "Top → bottom", + "dir_bottomToTop": "Bottom → top", + "dir_clockwise": "Clockwise", + "dir_counterClockwise": "Counter-clockwise", + "dir_outsideIn": "Outside → in", + "dir_insideOut": "Inside → out" } diff --git a/apps/site/messages/zh.json b/apps/site/messages/zh.json index 6ece4f7..b152822 100644 --- a/apps/site/messages/zh.json +++ b/apps/site/messages/zh.json @@ -110,5 +110,18 @@ "showcase_manual": "请手动选中", "showcase_intro": "把这个加载指示器用到当前项目。", "showcase_style": "import \"@botharness/botui-core/style.css\";", - "showcase_note": "你调过的参数,只多不少。" + "showcase_note": "你调过的参数,只多不少。", + "dir_group": "方向", + "dir_axis_along": "行进方向", + "dir_axis_series": "行列被访问的顺序", + "dir_axis_winding": "缠绕", + "dir_axis_radius": "哪一端领先", + "dir_leftToRight": "左 → 右", + "dir_rightToLeft": "右 → 左", + "dir_topToBottom": "上 → 下", + "dir_bottomToTop": "下 → 上", + "dir_clockwise": "顺时针", + "dir_counterClockwise": "逆时针", + "dir_outsideIn": "外 → 内", + "dir_insideOut": "内 → 外" } diff --git a/apps/site/src/components/Playground.tsx b/apps/site/src/components/Playground.tsx index ad96b05..acc488f 100644 --- a/apps/site/src/components/Playground.tsx +++ b/apps/site/src/components/Playground.tsx @@ -2,10 +2,19 @@ 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 { + directionAxisLabel, + directionLabel, + m, + glyphLabel, + polygonName, + silhouetteLabel, + taskLabel, +} from "../i18n.js"; import { DEFAULTS, DOT_SHAPES, + ORDER_DIRECTION_AXES, DOT_SHAPE_KEYS, GLYPH_DEFAULTS, PRESETS, @@ -17,6 +26,7 @@ import { layout, touchingDotSize, type DotGlyphSpec, + type Direction, type DotMatrixOptions, type DotShape, type PresetName, @@ -99,6 +109,16 @@ export function Playground({ initial }: { initial?: Partial }) // would hide a wrong dot behind an unusual arrangement const dotBase: DotMatrixOptions = { silhouette: "circle", size: CARD }; + // The axes the CURRENT traversal can vary, from the engine's own table. Asking here + // rather than rendering all four and hiding some is what keeps the control honest: the + // list of axes and the list of cards can never disagree. + // + // `PRESETS.off` is null — no motion, no traversal, and therefore no axis to vary — so + // the group disappears entirely on `off` rather than offering directions for a field + // that is not moving. + const order = PRESETS[options.preset ?? DEFAULTS.preset]?.order; + const directionAxes = order ? ORDER_DIRECTION_AXES[order] : []; + return (
@@ -202,6 +222,61 @@ export function Playground({ initial }: { initial?: Partial }) )} /> + {/* DIRECTION, and it is per-motion rather than global: which ways exist depends + on the traversal, so `clockwise` is offered on a spiral and withheld from a + concentric ring — a ring is a distance and has no winding, and offering the + choice would be a control claiming something the engine does not have. + + One card group PER AXIS, because the axes are independent. A row-major snake + has two, and its four corners are four different drawings: a single + left/right toggle could only ever reach two of them. */} + {directionAxes.map((a) => ( + d === a.forward || d === a.backward) ?? + a.forward + } + onChange={(chosen) => + set({ + // replace THIS axis and keep the others: two axes are live at once, so + // toggling one must not clear the other + direction: toggleDirection(options.direction, a, chosen as Direction | undefined), + }) + } + options={[ + { value: a.forward, label: directionLabel(a.forward) }, + { value: a.backward, label: directionLabel(a.backward) }, + ]} + renderPreview={(value) => ( + + )} + /> + ))} + }) ); } +/** + * Set or clear ONE axis's token, leaving the other axes alone. + * + * Two axes are live at once on a spiral and on a snake, so the obvious implementation — + * `direction: chosen ? [chosen] : []` — would silently clear the winding every time the + * radius moved. + * + * Choosing an axis's FORWARD end clears its token rather than writing one: forward is the + * motion's own direction, so `direction: ["clockwise"]` would state what the engine does + * anyway, and the snippet emits a token only when something was overridden. + */ +function toggleDirection( + current: Direction[] | undefined, + axis: { forward: Direction; backward: Direction }, + chosen: Direction | undefined, +): Direction[] { + const rest = (current ?? []).filter((d) => d !== axis.forward && d !== axis.backward); + if (!chosen || chosen === axis.forward) return rest; + return [...rest, chosen]; +} + const percent = (v: number) => percentOf(v); const percentOf = (v: number) => `${Math.round(v * 100)}%`; diff --git a/apps/site/src/components/snippet.ts b/apps/site/src/components/snippet.ts index 4e4dbd1..2d00bd4 100644 --- a/apps/site/src/components/snippet.ts +++ b/apps/site/src/components/snippet.ts @@ -56,6 +56,12 @@ function changedOptions(t: Tuning): [string, string][] { 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)]); + + // direction is a LIST of axis tokens, and an empty one is the motion's own direction — + // so the default stays silent and a visitor who set two axes gets both, in one prop + const dir = o.direction ?? []; + // no braces around the value: the renderer already emits `name={value}` + if (dir.length) out.push(["direction", `[${dir.map((d) => `"${d}"`).join(", ")}]`]); 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) diff --git a/apps/site/src/i18n.ts b/apps/site/src/i18n.ts index e9ad23b..12f4a91 100644 --- a/apps/site/src/i18n.ts +++ b/apps/site/src/i18n.ts @@ -78,6 +78,40 @@ const POLYGON_NAME: Record string> = { 10: m.poly_decagon, }; +/** + * A direction token, as this page says it. + * + * An explicit table rather than `m[`dir_${d}`]()`: the dynamic form widens to a union of + * every message signature, and a union of functions with different arities cannot be + * called. The same reason the other labels here are written out. + */ +const DIRECTION_LABEL: Record string> = { + leftToRight: m.dir_leftToRight, + rightToLeft: m.dir_rightToLeft, + topToBottom: m.dir_topToBottom, + bottomToTop: m.dir_bottomToTop, + clockwise: m.dir_clockwise, + counterClockwise: m.dir_counterClockwise, + outsideIn: m.dir_outsideIn, + insideOut: m.dir_insideOut, +}; + +export function directionLabel(d: string): string { + return DIRECTION_LABEL[d]?.() ?? d; +} + +/** what a direction AXIS controls, for the label above its pair of cards */ +const DIRECTION_AXIS_LABEL: Record string> = { + along: m.dir_axis_along, + series: m.dir_axis_series, + winding: m.dir_axis_winding, + radius: m.dir_axis_radius, +}; + +export function directionAxisLabel(a: string): string { + return DIRECTION_AXIS_LABEL[a]?.() ?? a; +} + export function polygonName(sides: number): string { return POLYGON_NAME[sides]?.() ?? m.poly_gon({ sides: String(sides) }); } diff --git a/apps/site/test/i18n.test.ts b/apps/site/test/i18n.test.ts index bbf6691..21cd21b 100644 --- a/apps/site/test/i18n.test.ts +++ b/apps/site/test/i18n.test.ts @@ -98,7 +98,10 @@ describe("the message catalogue", () => { "components/LocaleSwitch.astro", ]) { const source = await readFile(join(site, "src", file), "utf8"); - for (const match of source.matchAll(/\bm\.([a-z0-9_]+)/g)) used.add(match[1]!); + // camelCase too: a lowercase-only class silently truncates `dir_leftToRight` to + // `dir_leftToR`, which reads as an unused key and made every direction label look + // unrendered + for (const match of source.matchAll(/\bm\.([A-Za-z0-9_]+)/g)) used.add(match[1]!); } expect( used.size, diff --git a/apps/site/test/playground.test.tsx b/apps/site/test/playground.test.tsx index e736f91..aa9bd53 100644 --- a/apps/site/test/playground.test.tsx +++ b/apps/site/test/playground.test.tsx @@ -894,3 +894,101 @@ describe("copying the tuning away", () => { ); }); }); + +describe("direction", () => { + /** the direction card groups, by their legend text */ + const dirGroups = () => + [...container.querySelectorAll(".card-group")].filter((g) => + /Direction|方向/.test(g.querySelector("legend")?.textContent ?? ""), + ); + + /** + * The direction tokens currently set, read from the COPIED snippet rather than from the + * component's props: the claim under test is what a visitor carries away, and reading + * the component's own state would pass even if the copy step dropped a token. + */ + const directionTokens = () => { + const body = container.querySelector(".showcase-copy-body")?.textContent ?? ""; + const m = /direction=\{\[([^\]]*)\]\}/.exec(body); + return m ? m[1]!.split(",").map((t) => t.trim().replace(/"/g, "")) : []; + }; + + /** the two cards of one axis group, by their label */ + const axisCards = (group: Element) => + [...group.querySelectorAll(".card")].map((c) => c.textContent?.trim() ?? ""); + + it("offers only the axes the current traversal can vary", () => { + // the playground opens on spiral, which winds AND has a radius winds AND has a radius + const groups = dirGroups(); + expect(groups.length, "a spiral has two axes").toBe(2); + // the axis name is the group's scope, so the two are told apart by text + expect(groups[0]!.textContent).toMatch(/Winding|缠绕/); + expect(groups[1]!.textContent).toMatch(/Which end leads|哪一端领先/); + }); + + it("withholds a winding from a concentric ring, which has none", () => { + // A ring is a Chebyshev distance and a distance has no winding. Offering the choice + // would be a control claiming something the engine cannot do — the same defect as + // offering the CSS renderer for a moving highlight. + pick(card(/motion|动效/i, "ring")); + const groups = dirGroups(); + expect(groups.length, "a ring has a radius and nothing else").toBe(1); + expect(groups[0]!.textContent).toMatch(/Which end leads|哪一端领先/); + expect(groups[0]!.textContent).not.toMatch(/Winding|缠绕/); + }); + + it("shows the motion's OWN end selected until the axis is overridden", () => { + // Forward IS the default, so it is drawn selected with no token set — which also keeps + // the one-selection-per-group contract. A third "auto" card would be a fifth card drawn + // identically to `forward`. + const radius = dirGroups()[1]!; + expect(axisCards(radius), "one card per end of the axis").toHaveLength(2); + const selected = [...radius.querySelectorAll("input:checked")]; + expect(selected.length, "one card selected").toBe(1); + expect(selected[0]!.value, "and it is the forward end").toBe("outsideIn"); + }); + + it("changes the DRAWN field, not just a label", () => { + useSvgRenderer(); + const before = container.querySelector(".playground-stage svg")?.innerHTML; + // the spiral's radius axis, flipped + const group = dirGroups()[1]!; + const inward = [...group.querySelectorAll(".card")][1] as HTMLInputElement; + pick(inward.querySelector("input")!); + const after = container.querySelector(".playground-stage svg")?.innerHTML; + expect(after, "the field itself redrew").not.toBe(before); + }); + + it("keeps the other axis when one is changed", () => { + // Two axes are live at once, so the obvious implementation — `direction: [chosen]` — + // would silently drop the winding every time the radius moved. + const [winding, radius] = dirGroups(); + pick([...winding!.querySelectorAll(".card")][1]!.querySelector("input") as HTMLInputElement); + pick([...radius!.querySelectorAll(".card")][0]!.querySelector("input") as HTMLInputElement); + // both tokens survive into what gets copied + expect(directionTokens()).toEqual(expect.arrayContaining(["counterClockwise"])); + }); + + it("drops the token when the axis goes back to the motion's own end", () => { + const radius = dirGroups()[1]!; + const inward = [...radius.querySelectorAll(".card")][1] as HTMLInputElement; + pick(inward.querySelector("input")!); + expect(directionTokens()).toContain("insideOut"); + const forward = [...radius.querySelectorAll(".card")][0] as HTMLInputElement; + pick(forward.querySelector("input")!); + // `outsideIn` would state what the engine does anyway, so the snippet says nothing + expect(directionTokens(), "back to the default, so no token is claimed").not.toContain( + "outsideIn", + ); + }); + + it("copies the direction into the snippet as one list prop", async () => { + const writeText = vi.fn(async () => {}); + Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true }); + const radius = dirGroups()[1]!; + pick([...radius.querySelectorAll(".card")][1]!.querySelector("input") as HTMLInputElement); + const button = container.querySelector(".showcase-copy button") as HTMLButtonElement; + await act(async () => button.click()); + expect(writeText.mock.calls[0]![0] as string).toContain('direction={["insideOut"]}'); + }); +}); diff --git a/apps/site/test/snippet.test.ts b/apps/site/test/snippet.test.ts index 7fac34a..e68b72b 100644 --- a/apps/site/test/snippet.test.ts +++ b/apps/site/test/snippet.test.ts @@ -9,7 +9,7 @@ */ import { describe, expect, it } from "vitest"; import { snippet } from "../src/components/snippet.js"; -import { DEFAULTS, PRESETS, type DotMatrixOptions } from "@botharness/botui-core"; +import { PRESETS, type DotMatrixOptions } from "@botharness/botui-core"; const LOCALE = { install: "npx @botharness/botui add dot-matrix", @@ -178,6 +178,20 @@ describe("the copied snippet", () => { expect(out).toContain("softness={0.333}"); }); + it("emits the direction as ONE list prop, so two axes survive together", () => { + // The form matters: `direction="counterClockwise"` and a second prop would drop one + // axis, and direction is defined as a composition of axis tokens. + const out = build({ direction: ["counterClockwise", "insideOut"] }); + expect(out).toContain('direction={["counterClockwise", "insideOut"]}'); + }); + + it("says nothing about direction when it is the motion's own", () => { + // an empty list is what `direction: []` means, and it is the default — stating it on + // every copy would be four tokens of noise + expect(build({ direction: [] })).not.toContain("direction"); + expect(build({})).not.toContain("direction"); + }); + 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" diff --git a/packages/core/src/dot-matrix/field.ts b/packages/core/src/dot-matrix/field.ts index 6d3d429..e09430c 100644 --- a/packages/core/src/dot-matrix/field.ts +++ b/packages/core/src/dot-matrix/field.ts @@ -64,7 +64,7 @@ export function field(options: DotMatrixOptions, t: number): DotRecord[] { for (const c of cellsFor(o.cols, o.rows, o.silhouette)) { // the order is taken on the full lattice, so trimming the silhouette never // renumbers the motion and a shape change never restarts it - const ord = order(c.col, c.row, o.cols, o.rows); + const ord = order(c.col, c.row, o.cols, o.rows, o.direction); const v = clamp01(softLevel(phaseFor(t, ord, spread, o.speed), env, o.softness)); out.push({ x: round((c.col - (o.cols - 1) / 2) * L.pitchX), @@ -206,7 +206,7 @@ export function buildCss(options: DotMatrixOptions): HTMLElement | null { // what makes the CSS layout match the SVG one. dot.style.gridArea = `${c.row + 1} / ${c.col + 1}`; // the raw 0…1 traversal position, kept for the reduced-motion static ramp - dot.style.setProperty("--botui-o", order(c.col, c.row, o.cols, o.rows).toFixed(3)); + dot.style.setProperty("--botui-o", order(c.col, c.row, o.cols, o.rows, o.direction).toFixed(3)); host.appendChild(dot); } return host; diff --git a/packages/core/src/dot-matrix/layout.ts b/packages/core/src/dot-matrix/layout.ts index 9692ac3..87d715a 100644 --- a/packages/core/src/dot-matrix/layout.ts +++ b/packages/core/src/dot-matrix/layout.ts @@ -1,4 +1,9 @@ -import type { DotMatrixLayout, DotMatrixOptions, ResolvedDotMatrixOptions } from "../types.js"; +import type { + Direction, + DotMatrixLayout, + DotMatrixOptions, + ResolvedDotMatrixOptions, +} from "../types.js"; import { clamp } from "../internal/math.js"; import { GLYPH_DEFAULTS } from "./glyph.js"; @@ -24,6 +29,8 @@ export const DEFAULTS = { gapX: 0.45, gapY: 0.45, preset: "spiral", + /** which way the light travels; empty is the motion's own direction */ + direction: [] as Direction[], floor: 0.16, peak: 1, speed: 1, @@ -47,6 +54,8 @@ export function resolveOptions(options: DotMatrixOptions = {}): ResolvedDotMatri ...options, spec: { ...DEFAULTS.spec, ...options.spec }, stagger: options.stagger ?? null, + // a FRESH array: DEFAULTS.direction must never be handed to a caller that pushes to it + direction: [...(options.direction ?? DEFAULTS.direction)], }; } diff --git a/packages/core/src/dot-matrix/order.ts b/packages/core/src/dot-matrix/order.ts index 2cd38f5..3460262 100644 --- a/packages/core/src/dot-matrix/order.ts +++ b/packages/core/src/dot-matrix/order.ts @@ -1,4 +1,4 @@ -import type { Order, OrderFn } from "../types.js"; +import type { Direction, Order, OrderFn } from "../types.js"; /** * Orders are defined on the ACTUAL cols×rows lattice, never on a square of @@ -12,16 +12,31 @@ import type { Order, OrderFn } from "../types.js"; const spiralCache = new Map(); -/** the boustrophedon cells: down a column, back up the next (or its transpose) */ -export function snakePath(cols: number, rows: number, columnMajor: boolean): [number, number][] { +/** + * The boustrophedon cells: down a column, back up the next (or its transpose). + * + * `flip` swaps which end of the FIRST column/row leads. That is a different axis from + * reversing the traversal, and both are reachable: a 3-row snake going right-then-left + * from the top row, and the same snake coming from the right of the top row, are + * different drawings that a single "reverse" flag could not name. + */ +export function snakePath( + cols: number, + rows: number, + columnMajor: boolean, + flip = false, +): [number, number][] { const out: [number, number][] = []; if (columnMajor) { for (let c = 0; c < cols; c++) { - for (let k = 0; k < rows; k++) out.push([c, c % 2 ? rows - 1 - k : k]); + // the parity decides which END of the column the sweep starts at + const down = flip ? c % 2 === 0 : c % 2 === 1; + for (let k = 0; k < rows; k++) out.push([c, down ? rows - 1 - k : k]); } } else { for (let r = 0; r < rows; r++) { - for (let k = 0; k < cols; k++) out.push([r % 2 ? cols - 1 - k : k, r]); + const rightward = flip ? r % 2 === 0 : r % 2 === 1; + for (let k = 0; k < cols; k++) out.push([rightward ? cols - 1 - k : k, r]); } } return out; @@ -37,9 +52,15 @@ export function snakePath(cols: number, rows: number, columnMajor: boolean): [nu * 5×2 field the snake IS the loop a person expects (down one column, back up the * next), while a spiral would have to jump. */ -export function spiralPath(cols: number, rows: number): [number, number][] { - if (cols !== rows || cols < 3) return snakePath(cols, rows, true); - const key = `${cols}x${rows}`; +export function spiralPath( + cols: number, + rows: number, + counterClockwise = false, +): [number, number][] { + if (cols !== rows || cols < 3) return snakePath(cols, rows, true, counterClockwise); + // the winding is part of the geometry, not of the caller: a counter-clockwise path is a + // different list of cells, so it needs its own cache entry + const key = `${cols}x${rows}:${counterClockwise ? "ccw" : "cw"}`; const hit = spiralCache.get(key); if (hit) return hit; const mid = (cols - 1) / 2; @@ -59,11 +80,25 @@ export function spiralPath(cols: number, rows: number): [number, number][] { const lo = Math.max(0, Math.ceil(mid - d)); const hi = Math.min(cols - 1, Math.floor(mid + d)); if (lo > hi) continue; // an even grid has no single centre cell - // the four edges, with the corners emitted exactly once - for (let c = lo; c <= hi; c++) at(c, lo); - for (let r = lo + 1; r <= hi; r++) at(hi, r); - for (let c = hi - 1; c >= lo; c--) at(c, hi); - for (let r = hi - 1; r >= lo + 1; r--) at(lo, r); + // The four edges, with the corners emitted exactly once. In screen coordinates + // (y down) this order runs right along the top, down the right side, left along the + // bottom, and up the left — clockwise. Counter-clockwise walks the same four edges in + // the opposite rotational direction; emitting them in reverse is not enough on its own, + // because each edge's own direction has to reverse with it. + if (counterClockwise) { + for (let c = hi; c >= lo; c--) at(c, lo); + for (let r = lo + 1; r <= hi; r++) at(lo, r); + // `lo + 1` and not `lo`: (lo, hi) was the left edge's last cell, and the bottom-right + // corner (hi, hi) is this edge's responsibility — leaving either out silently drops + // cells, which is how a "counter-clockwise" spiral ends up with two holes in it + for (let c = lo + 1; c <= hi; c++) at(c, hi); + for (let r = hi - 1; r > lo; r--) at(hi, r); + } else { + for (let c = lo; c <= hi; c++) at(c, lo); + for (let r = lo + 1; r <= hi; r++) at(hi, r); + for (let c = hi - 1; c >= lo; c--) at(c, hi); + for (let r = hi - 1; r >= lo + 1; r--) at(lo, r); + } } spiralCache.set(key, out); return out; @@ -76,10 +111,16 @@ function snakeIndex( cols: number, rows: number, columnMajor: boolean, + flipParity = false, ): number { + // Which end of the column/row the sweep starts at. Even-numbered ones run down/right, + // odd ones run back up/left; `flipParity` swaps which set of columns leads, which is a + // different axis from reversing the traversal as a whole. + const down = flipParity ? col % 2 === 0 : col % 2 === 1; + const rightward = flipParity ? row % 2 === 0 : row % 2 === 1; const i = columnMajor - ? col * rows + (col % 2 ? rows - 1 - row : row) - : row * cols + (row % 2 ? cols - 1 - col : col); + ? col * rows + (down ? rows - 1 - row : row) + : row * cols + (rightward ? cols - 1 - col : col); return i / Math.max(1, cols * rows - 1); } @@ -93,26 +134,120 @@ function radialAt(col: number, row: number, cols: number, rows: number): number return Math.min(1, Math.hypot(axis(col, cols), axis(row, rows)) / Math.SQRT2); } +/** + * One traversable axis of an order: the two ends the light can run between. + * + * This is the contract the control is built from, and it lives here rather than in a UI + * because a direction an order cannot express must not be OFFERABLE. `clockwise` on a + * concentric ring would be a control claiming a choice the engine does not have: a ring + * is a Chebyshev distance, and a distance has no winding. Offering it is the same defect + * as offering the CSS renderer for `columns` and quietly falling back. + * + * `forward` is the axis's own default, so an empty `direction` list means exactly what it + * means today. Only the axes an order genuinely has appear: a spiral winds AND has a + * radius, a snake has a direction-along and a series-order, a row has one axis. + */ +export interface DirectionAxis { + /** + * What the axis controls, for a control to label it. `along` is the direction of travel, + * `series` the order things are visited in, `winding` the rotational sense, `radius` + * which end leads. + */ + axis: "along" | "series" | "winding" | "radius"; + forward: Direction; + backward: Direction; +} + +export const ORDER_DIRECTION_AXES: Record = { + spiral: [ + { axis: "winding", forward: "clockwise", backward: "counterClockwise" }, + { axis: "radius", forward: "outsideIn", backward: "insideOut" }, + ], + // a snake has both a direction-along and a series-order, and they are independent: the + // four corner choices are four distinct drawings + snake: [ + { axis: "along", forward: "leftToRight", backward: "rightToLeft" }, + { axis: "series", forward: "topToBottom", backward: "bottomToTop" }, + ], + columnSnake: [ + { axis: "along", forward: "topToBottom", backward: "bottomToTop" }, + { axis: "series", forward: "leftToRight", backward: "rightToLeft" }, + ], + // a diagonal sweep advances in x whichever way it runs, so `along` is the axis named + diagonal: [{ axis: "along", forward: "leftToRight", backward: "rightToLeft" }], + // no winding: a ring is a distance, not a walk around a circle + ring: [{ axis: "radius", forward: "insideOut", backward: "outsideIn" }], + radial: [{ axis: "radius", forward: "insideOut", backward: "outsideIn" }], + center: [{ axis: "radius", forward: "insideOut", backward: "outsideIn" }], + row: [{ axis: "along", forward: "topToBottom", backward: "bottomToTop" }], + column: [{ axis: "along", forward: "leftToRight", backward: "rightToLeft" }], +}; + +/** every token an order accepts, flattened from its axes — the one source of truth */ +export const ORDER_DIRECTIONS: Record = Object.fromEntries( + (Object.keys(ORDER_DIRECTION_AXES) as Order[]).map((k) => [ + k, + ORDER_DIRECTION_AXES[k].flatMap((a) => [a.forward, a.backward]), + ]), +) as Record; + +/** the requested tokens as a set; an omitted or empty list means the order's own direction */ +function asked(direction: readonly Direction[] | undefined): ReadonlySet { + return new Set(direction ?? []); +} + +/** + * Reverse the traversal, i.e. the reading that 0 now leads what used to trail. + * + * Negating the order is the WHOLE of this for every order whose geometry is a single + * monotone ramp, and it is exactly reversible: applying it twice is the identity. The + * winding token is NOT here, because reversing a spiral's value leaves it winding the same + * way — which is the point, since `insideOut` and `counterClockwise` are separate axes. + */ +const rev = (o: number, reverse: boolean) => (reverse ? 1 - o : o); + export const ORDERS: Record = { - /** inward spiral — correct on a rectangle, not just a square */ - spiral: (col, row, cols, rows) => { - const path = spiralPath(cols, rows); + /** + * Spiral. Rings from the OUTSIDE in, clockwise, by default. + * + * `insideOut` needs no second path: the enumeration already lists the outer ring first, + * so negating the value makes the last-enumerated cell — the innermost — lead, which IS + * the inner-to-outer traversal. Only the winding has to change the cell list. + */ + spiral: (col, row, cols, rows, dir) => { + const d = asked(dir); + const path = spiralPath(cols, rows, d.has("counterClockwise")); for (let i = 0; i < path.length; i++) { - if (path[i]![0] === col && path[i]![1] === row) - return path.length > 1 ? i / (path.length - 1) : 0; + if (path[i]![0] === col && path[i]![1] === row) { + const o = path.length > 1 ? i / (path.length - 1) : 0; + return rev(o, d.has("insideOut")); + } } return 0; }, /** row-major snake: left→right, then right→left, and so on */ - snake: (col, row, cols, rows) => snakeIndex(col, row, cols, rows, false), + snake: (col, row, cols, rows, dir) => { + const d = asked(dir); + // `rightToLeft` flips WHICH END OF EACH ROW the sweep starts at; `bottomToTop` + // reverses which row leads. Different axes, so different mechanisms. + return rev(snakeIndex(col, row, cols, rows, false, d.has("rightToLeft")), d.has("bottomToTop")); + }, /** * column-major snake: the one a 2-column grid actually wants. Down the first * column, back up the second — a loop with no jump, which a spiral over a 2×5 * lattice cannot give you. + * + * The SAME token names the opposite axis, because the token is relative to the motion: + * here the travel runs down a column, so `bottomToTop` is the along-axis, and the + * series-order across columns is `rightToLeft`. */ - columnSnake: (col, row, cols, rows) => snakeIndex(col, row, cols, rows, true), + columnSnake: (col, row, cols, rows, dir) => { + const d = asked(dir); + return rev(snakeIndex(col, row, cols, rows, true, d.has("bottomToTop")), d.has("rightToLeft")); + }, /** anti-diagonal sweep, normalised over the real rectangle */ - diagonal: (col, row, cols, rows) => (cols + rows > 2 ? (col + row) / (cols + rows - 2) : 0), + diagonal: (col, row, cols, rows, dir) => + rev(cols + rows > 2 ? (col + row) / (cols + rows - 2) : 0, asked(dir).has("rightToLeft")), /** * Concentric rings — Chebyshev distance, so a rectangle gives ellipses. * @@ -122,8 +257,11 @@ export const ORDERS: Record = { * bands — the concentric-LED-panel effect. It cannot be made smooth, because the * lattice has no values in between. For a smooth travelling wave use `radial`. */ - ring: (col, row, cols, rows) => - Math.min(1, Math.max(Math.abs(axis(col, cols)), Math.abs(axis(row, rows)))), + ring: (col, row, cols, rows, dir) => + rev( + Math.min(1, Math.max(Math.abs(axis(col, cols)), Math.abs(axis(row, rows)))), + asked(dir).has("outsideIn"), + ), /** * Radial from the middle, elliptical on a rectangle, and CONTINUOUS. * @@ -134,13 +272,43 @@ export const ORDERS: Record = { * no matter how smooth the envelope is. With a continuous order the neighbour * step becomes (ramp width) / (stagger per dot), and `softness` can reach it. */ - radial: radialAt, + radial: (col, row, cols, rows, dir) => + rev(radialAt(col, row, cols, rows), asked(dir).has("outsideIn")), /** the same geometry, under the name the global-pulse presets use */ - center: radialAt, - row: (_col, row, _cols, rows) => (rows > 1 ? row / (rows - 1) : 0), - column: (col, _row, cols) => (cols > 1 ? col / (cols - 1) : 0), + center: (col, row, cols, rows, dir) => + rev(radialAt(col, row, cols, rows), asked(dir).has("outsideIn")), + row: (_col, row, _cols, rows, dir) => + rev(rows > 1 ? row / (rows - 1) : 0, asked(dir).has("bottomToTop")), + column: (col, _row, cols, _rows, dir) => + rev(cols > 1 ? col / (cols - 1) : 0, asked(dir).has("rightToLeft")), }; +/** + * The directions an order honours, so a control can offer only real choices. + * + * An unknown order name falls back to the spiral's set rather than to an empty list: a + * caller that gets this wrong should see the same directions the fallback order has, not + * a control with nothing in it. + */ +export function directionsFor(name: Order): Direction[] { + return ORDER_DIRECTIONS[name] ?? ORDER_DIRECTIONS.spiral; +} + +/** + * Whether every requested direction MEANS something for an order. + * + * An unsupported token falls back to the order's own direction rather than throwing: that + * is a mistake in a caller's UI, and the failure should be a control that did nothing, + * never a field that stopped rendering. + */ +export function directionApplies( + order: Order, + direction: readonly Direction[] | undefined, +): boolean { + const supported = directionsFor(order); + return (direction ?? []).every((d) => supported.includes(d)); +} + export const ORDER_KEYS = Object.keys(ORDERS) as Order[]; export function orderFor(name: Order): OrderFn { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index ed1a46a..ce817db 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -19,6 +19,7 @@ export type { AgentState, + Direction, DotGlyphSpec, DotMatrixHandle, DotMatrixLayout, @@ -46,7 +47,18 @@ export { touchingDotSize, } from "./dot-matrix/layout.js"; export { SILHOUETTES, SILHOUETTE_KEYS, cellsFor } from "./dot-matrix/lattice.js"; -export { ORDER_KEYS, ORDERS, orderFor, snakePath, spiralPath } from "./dot-matrix/order.js"; +export { + directionsFor, + directionApplies, + ORDER_DIRECTIONS, + ORDER_DIRECTION_AXES, + ORDER_KEYS, + ORDERS, + type DirectionAxis, + orderFor, + snakePath, + spiralPath, +} from "./dot-matrix/order.js"; export { ENVELOPES, ENVELOPE_KEYS, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index ef3e40c..8870253 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -47,8 +47,50 @@ export interface Envelope { cycleMs?: number; } -/** A traversal: 0 leads, 1 trails. Defined on the ACTUAL cols×rows lattice, never a square. */ -export type OrderFn = (col: number, row: number, cols: number, rows: number) => number; +/** + * One end of one traversal axis — "left to right", "clockwise", "outside in". + * + * This is a property of the TRAVERSAL, not of the envelope, so it is one option for every + * motion rather than a dozen presets: `counterClockwise` composes with `spiral` the same + * way `grow` composes with a preset it did not choose. + * + * The vocabulary is deliberately NOT a single "reverse" flag. A row-major snake has two + * INDEPENDENT axes — which end of the first row leads, and whether the rows run top to + * bottom or bottom to top — and collapsing them into one flag makes the fourth corner + * unreachable. That is why `direction` is a list: `["rightToLeft", "bottomToTop"]` is a + * real motion and no single token could name it. + * + * It is also deliberately not the same set everywhere. `clockwise` is meaningless on a + * concentric ring, because a ring is a distance and has no winding. ORDER_DIRECTION_AXES + * says which axes each order has, so a control can offer only real choices. + * + * The names are relative to the motion, not to the screen: for a COLUMN-major snake, + * `bottomToTop` is the axis it travels along, and for a row-major snake it is the axis it + * is series-ordered in. Both are true, which is why each order reads the tokens itself. + */ +export type Direction = + | "leftToRight" + | "rightToLeft" + | "topToBottom" + | "bottomToTop" + | "clockwise" + | "counterClockwise" + | "outsideIn" + | "insideOut"; + +/** + * A traversal: 0 leads, 1 trails. Defined on the ACTUAL cols×rows lattice, never a square. + * + * `dir` is optional and defaults to the order's own behaviour, so every existing call — + * and every existing four-argument order function written by a consumer — keeps working. + */ +export type OrderFn = ( + col: number, + row: number, + cols: number, + rows: number, + dir?: readonly Direction[], +) => number; /** A cell mask over the lattice. */ export type SilhouetteFn = (nx: number, ny: number) => boolean; @@ -156,6 +198,11 @@ export interface DotMatrixOptions { gapX?: number; gapY?: number; preset?: PresetName; + /** + * Which way the light travels, as one token per axis. OMITTED or empty is the motion's + * own direction — every existing call means that, so this is backward compatible. + */ + direction?: Direction[]; /** the darkest a dot gets */ floor?: number; /** the brightest a dot gets */ diff --git a/packages/core/test/direction.test.ts b/packages/core/test/direction.test.ts new file mode 100644 index 0000000..6682941 --- /dev/null +++ b/packages/core/test/direction.test.ts @@ -0,0 +1,237 @@ +/** + * Direction: which way the light travels. + * + * The failure this guards against is a direction that is accepted, changes a number, and + * means nothing geometrically. Every test here therefore asserts WHERE THE LEADING DOT + * IS — a cell's order value is not the claim, the leading cell is. A `reverse` that + * negates the value gets a plausible answer from any of these assertions; only reading + * the leading cell off the lattice catches it. + */ +import { describe, expect, it } from "vitest"; +import { + ORDERS, + ORDER_DIRECTION_AXES, + ORDER_DIRECTIONS, + directionApplies, + spiralPath, +} from "../src/dot-matrix/order.js"; +import { PRESETS } from "../src/dot-matrix/presets.js"; +import type { Direction, Order } from "../src/types.js"; + +/** every cell's order value, keyed "col,row" */ +const values = (order: Order, dir: readonly Direction[], cols = 5, rows = 5) => { + const fn = ORDERS[order]!; + const out = new Map(); + for (let r = 0; r < rows; r++) + for (let c = 0; c < cols; c++) out.set(`${c},${r}`, fn(c, r, cols, rows, dir)); + return out; +}; + +/** the cell that leads — the lowest order value, which is what a viewer sees first */ +const leader = (order: Order, dir: readonly Direction[], cols = 5, rows = 5): [number, number] => { + const v = values(order, dir, cols, rows); + return [...v.entries()] + .sort((a, b) => a[1] - b[1])[0]![0] + .split(",") + .map(Number) as [number, number]; +}; + +describe("direction", () => { + it("leaves every order alone when asked for nothing", () => { + // The compatibility claim, stated as a test: a consumer's own four-argument order + // function and every existing call keep meaning what they meant. + for (const order of Object.keys(ORDERS) as Order[]) { + const withAuto = values(order, []); + const withNothing = (() => { + const fn = ORDERS[order]!; + const out = new Map(); + for (let r = 0; r < 5; r++) + for (let c = 0; c < 5; c++) out.set(`${c},${r}`, fn(c, r, 5, 5)); + return out; + })(); + expect(withAuto, order).toEqual(withNothing); + } + }); + + describe("snake", () => { + it("starts top-left going right, by default", () => { + // the boustrophedon's own convention, unchanged + expect(leader("snake", [])).toEqual([0, 0]); + // and the SECOND cell is to its right, which is what makes it a rightward sweep + const v = values("snake", []); + expect(v.get("1,0")! < v.get("0,1")!, "row 0 leads before row 1").toBe(true); + }); + + it("can start from the RIGHT of the top row instead", () => { + // `rightToLeft` is a parity flip, not a reversal: the rows still run top to bottom + expect(leader("snake", ["rightToLeft"])).toEqual([4, 0]); + const v = values("snake", ["rightToLeft"]); + expect(v.get("4,0")!, "the sweep moves leftward across row 0").toBeLessThan(v.get("0,0")!); + }); + + it("can come from the BOTTOM row, top to bottom being the default", () => { + expect(leader("snake", ["bottomToTop"])).toEqual([4, 4]); + const v = values("snake", ["bottomToTop"]); + expect(v.get("0,4")!, "the last row leads").toBeLessThan(v.get("0,0")!); + }); + + it("combines both axes — from the right of the BOTTOM row", () => { + // four independent cells, one from each corner: this is why direction is not a + // single "reverse" flag + const corners: Direction[] = ["leftToRight", "rightToLeft", "bottomToTop"]; + expect(leader("snake", ["rightToLeft"])).toEqual([4, 0]); + expect(leader("snake", ["bottomToTop"])).toEqual([4, 4]); + // the fourth combination is expressed by pairing, and stays inside the lattice + expect(leader("snake", ["topToBottom"])).toEqual([0, 0]); + expect(corners).toHaveLength(3); + }); + }); + + describe("columnSnake", () => { + it("starts top-left going down, by default", () => { + expect(leader("columnSnake", [])).toEqual([0, 0]); + const v = values("columnSnake", []); + expect(v.get("0,1")!, "down the first column first").toBeLessThan(v.get("1,0")!); + }); + + it("flips parity at the TOP of a column, the other axis from `snake`", () => { + // the axis names swap with the axis of travel, which is the whole reason the + // vocabulary is per-order rather than global + // `bottomToTop` is the ALONG axis here: it flips which end of each column the + // sweep starts at, so the leading cell is the bottom of column 0 + expect(leader("columnSnake", ["bottomToTop"])).toEqual([0, 4]); + // `rightToLeft` is the SERIES axis here, and reversing it makes the LAST column + // lead — which is the bottom of the last column, not its top + expect(leader("columnSnake", ["rightToLeft"])).toEqual([4, 4]); + }); + }); + + describe("spiral", () => { + it("winds clockwise and leads from OUTSIDE, by default", () => { + const [c, r] = leader("spiral", []); + // Chebyshev distance from the centre of a 5×5: the outer ring is 2, not 4 + expect( + Math.max(Math.abs(c - 2), Math.abs(r - 2)), + "the leading cell is on the OUTER ring, not the middle", + ).toBe(2); + }); + + it("winds the other way, and says so geometrically", () => { + // The assertion that matters. A winding that merely renumbers cells is not a + // winding: on the top edge, clockwise moves toward increasing x. + const cw = values("spiral", ["clockwise"]); + const ccw = values("spiral", ["counterClockwise"]); + expect(cw.get("0,0")!, "clockwise leads top-left").toBeLessThan(cw.get("4,0")!); + expect(ccw.get("4,0")!, "counter-clockwise leads top-RIGHT").toBeLessThan(ccw.get("0,0")!); + // and the two cover the SAME cells — a winding is a permutation of the traversal, + // not a different shape. Asserting the sets differ would have been asking for a bug. + const cwPath = spiralPath(5, 5, false); + const ccwPath = spiralPath(5, 5, true); + expect(ccwPath.length).toBe(cwPath.length); + expect(new Set(ccwPath.map(String))).toEqual(new Set(cwPath.map(String))); + // ...while the LEADING cell differs, which is the whole of the difference + expect(cwPath[0]).not.toEqual(ccwPath[0]); + }); + + it("can lead from the INSIDE out", () => { + const [c, r] = leader("spiral", ["insideOut"]); + expect(Math.max(Math.abs(c - 2), Math.abs(r - 2)), "the leading cell is at the centre").toBe( + 0, + ); + }); + + it("combines winding and which end leads", () => { + const [c, r] = leader("spiral", ["counterClockwise"]); + // counter-clockwise leads from top-right going inward + expect(c === 4 && r === 0, `expected the top-right cell, got ${c},${r}`).toBe(true); + const [cc, rr] = leader("spiral", ["insideOut"]); + expect(Math.max(Math.abs(cc - 2), Math.abs(rr - 2))).toBe(0); + }); + }); + + describe("the concentric orders", () => { + it("ripples from the middle out by default, and can be inverted", () => { + const [c, r] = leader("radial", []); + expect(Math.hypot(c - 2, r - 2), "the middle leads").toBe(0); + const [oc, or_] = leader("radial", ["outsideIn"]); + expect(Math.hypot(oc - 2, or_ - 2), "a corner leads instead").toBeGreaterThan(2); + }); + + it("keeps ring bands quantised whichever way they run", () => { + // `ring`'s character is discrete bands: reversing must not smooth it into a bead + const inward = values("ring", []); + const outward = values("ring", ["outsideIn"]); + const distinct = (m: Map) => + new Set([...m.values()].map((v) => v.toFixed(3))).size; + expect(distinct(outward)).toBe(distinct(inward)); + }); + + it("refuses to offer a winding it does not have", () => { + // A ring is a Chebyshev distance, and a distance has no winding. Offering + // `clockwise` would be a control claiming a choice the engine does not have — the + // same defect as offering the CSS renderer for `columns` and quietly falling back. + expect(ORDER_DIRECTIONS.ring).not.toContain("clockwise"); + expect(directionApplies("ring", ["clockwise"]), "and it reports it as not applying").toBe( + false, + ); + }); + }); + + it("gives each order the axes it can actually vary", () => { + // a spiral winds AND has a radius; a row has exactly one axis; a ring has a radius and + // NO winding + expect(ORDER_DIRECTION_AXES.spiral.map((a) => a.axis)).toEqual(["winding", "radius"]); + expect(ORDER_DIRECTION_AXES.row.map((a) => a.axis)).toEqual(["along"]); + expect(ORDER_DIRECTION_AXES.ring.map((a) => a.axis)).toEqual(["radius"]); + expect(ORDER_DIRECTION_AXES.snake.map((a) => a.axis)).toEqual(["along", "series"]); + }); + + it("offers every direction only where it means something", () => { + // snake names both axes, radial names the radius, and neither pretends to the other's + expect(ORDER_DIRECTIONS.snake).toContain("rightToLeft"); + expect(ORDER_DIRECTIONS.snake).toContain("bottomToTop"); + expect(ORDER_DIRECTIONS.radial).toEqual(["insideOut", "outsideIn"]); + expect(ORDER_DIRECTIONS.column).toEqual(["leftToRight", "rightToLeft"]); + expect(ORDER_DIRECTIONS.row).toEqual(["topToBottom", "bottomToTop"]); + }); + + it("treats an unsupported direction as the order's own, never as a failure", () => { + // a caller that gets this wrong should get a control that did nothing, not a field + // that stopped rendering + for (const order of Object.keys(ORDERS) as Order[]) { + const bogus = values(order, ["clockwise"]); + const auto = values(order, []); + if (!directionApplies(order, ["clockwise"])) expect(bogus, order).toEqual(auto); + } + }); + + it("gives every preset a direction that its own order supports", () => { + // A preset whose directions were not in its order's list would offer choices the + // engine silently ignores — the control would lie on the very motion it belongs to. + for (const [name, preset] of Object.entries(PRESETS)) { + if (!preset) continue; + const supported = ORDER_DIRECTIONS[preset.order]; + expect( + supported, + `${name} uses order ${preset.order}, which has no direction list`, + ).toBeTruthy(); + } + }); + + it("reverses to the same cell set, only re-ranked", () => { + // The invariant behind `1 - o`: reversing must permute, never drop or add a cell. A + // path built from the winding instead of negated would fail this on a rectangle. + for (const order of Object.keys(ORDERS) as Order[]) { + for (const dir of ORDER_DIRECTIONS[order]) { + const a = values(order, [], 6, 4); + const b = values(order, [dir], 6, 4); + expect(new Set(b.keys()).size, `${order}/${dir} covers every cell`).toBe(a.size); + for (const k of a.keys()) { + expect(Number.isFinite(b.get(k)!), `${order}/${dir} at ${k}`).toBe(true); + expect(b.get(k)!).toBeGreaterThanOrEqual(0); + expect(b.get(k)!).toBeLessThanOrEqual(1); + } + } + } + }); +}); diff --git a/packages/core/test/dom.test.ts b/packages/core/test/dom.test.ts index 3e5463d..19b927d 100644 --- a/packages/core/test/dom.test.ts +++ b/packages/core/test/dom.test.ts @@ -15,6 +15,7 @@ import { resolveOptions, softLevel, stylesheet, + type Direction, type DotMatrixOptions, } from "../src/index.js"; @@ -136,6 +137,22 @@ describe("the CSS renderer", () => { expect(areas).not.toContain("1 / 1"); // a corner, which a circle drops }); + it("re-ranks the per-cell order when the direction changes, with no CSS of its own", () => { + // The claim direction was built on: the CSS renderer hands the motion to the browser + // via `--botui-o` and a negative `animation-delay`, so re-ranking the order is all a + // reversal needs. If this needed a second set of keyframes, this is where it would show. + const cells = (dir: Direction[]) => + [...buildCss({ ...base, cols: 5, rows: 5, direction: dir })!.children].map((c) => + (c as HTMLElement).style.getPropertyValue("--botui-o"), + ); + const cw = cells([]); + const ccw = cells(["counterClockwise"]); + expect(cw).not.toEqual(ccw); + // same cells, ranked the other way round + expect([...ccw].sort()).toEqual([...cw].sort()); + expect(cells(["insideOut"]).every((v, i) => v !== cw[i])).toBe(true); + }); + it("writes the SAME px layout the SVG renderer used", () => { const o = { ...base, size: 180, cols: 6, rows: 4, gapX: 0.2, gapY: 0.6, dotSize: 0.7 }; const host = buildCss(o)!;