/**
* T4 — Op contract tests for the Phase 3a dispatch boundary.
*
* Tests verify: correct DOM mutation, correct RFC 6902 forward patches,
* correct inverse patches (applying them restores the original state),
* and override-set key mapping.
*/
import { describe, it, expect } from "vitest";
import { parseHTML } from "linkedom";
import type { EditOp } from "../types.js";
import { parseMutable, getElementStyles, setElementStyles } from "./model.js";
import { applyOp, validateOp } from "./mutate.js";
import { applyPatchesToDocument, applyOverrideSet } from "./apply-patches.js";
import { pathToKey } from "./patches.js";
import { serializeDocument } from "./serialize.js";
// ─── Fixtures ────────────────────────────────────────────────────────────────
// No trailing semicolons in style attrs — serializeStyleAttr never adds them.
const BASE_HTML = `
Hello World
sub text
`.trim();
function fresh() {
return parseMutable(BASE_HTML);
}
// Full document (BASE_HTML wrapped in ) with NO declarations — the shape
// declareVariable requires (it refuses fragment sources whose synthetic
// is stripped on serialize).
function freshDoc() {
return parseMutable(`${BASE_HTML}`);
}
/** Full HTML fixture with data-composition-variables for B1/B2 tests. */
const VARIABLES_HTML = `
`;
function freshWithVars() {
return parseMutable(VARIABLES_HTML);
}
/** Read the default value for a variable id from the parsed document. */
function readVarDefault(parsed: ReturnType, id: string): unknown {
const raw = parsed.document.documentElement?.getAttribute("data-composition-variables");
if (!raw) return undefined;
const arr = JSON.parse(raw) as Array<{ id: string; default: unknown }>;
return arr.find((v) => v.id === id)?.default;
}
// ─── setStyle ────────────────────────────────────────────────────────────────
describe("setStyle", () => {
it("mutates existing style prop and emits replace patches", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: "hf-title",
styles: { fontSize: "96px" },
});
expect(result.forward).toHaveLength(1);
expect(result.forward[0]).toEqual({
op: "replace",
path: "/elements/hf-title/inlineStyles/fontSize",
value: "96px",
});
expect(result.inverse[0]).toEqual({
op: "replace",
path: "/elements/hf-title/inlineStyles/fontSize",
value: "64px",
});
// DOM mutated
const el = parsed.document.querySelector('[data-hf-id="hf-title"]');
expect(el?.getAttribute("style")).toContain("font-size: 96px");
});
it("adds new style prop and emits add patch", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: "hf-logo",
styles: { opacity: "0.8" },
});
expect(result.forward[0]?.op).toBe("add");
expect(result.inverse[0]?.op).toBe("remove");
});
it("removes style prop when value is null", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: "hf-title",
styles: { color: null },
});
expect(result.forward[0]?.op).toBe("remove");
expect(result.inverse[0]?.op).toBe("add");
expect(result.inverse[0]?.value).toBe("#fff");
});
it("inverse patches restore original state", () => {
const parsed = fresh();
const before = serializeDocument(parsed);
const { inverse } = applyOp(parsed, {
type: "setStyle",
target: "hf-title",
styles: { fontSize: "96px", color: "#f00" },
});
applyPatchesToDocument(parsed, inverse);
expect(serializeDocument(parsed)).toBe(before);
});
it("applies to multiple targets", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: ["hf-title", "hf-span"],
styles: { opacity: "1" },
});
expect(result.forward).toHaveLength(2);
});
it("override-set key maps correctly", () => {
const key = pathToKey("/elements/hf-title/inlineStyles/fontSize");
expect(key).toBe("hf-title.style.fontSize");
});
// Regression: a HYPHENATED (kebab) style key must derive its inverse against
// the camelCase-keyed store, or oldValue is null → undo deletes the prior
// value instead of restoring it, and a removal skips the inverse entirely.
it("derives correct inverse for a kebab style key (change)", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: "hf-title",
styles: { "font-size": "96px" },
});
// inverse restores the prior 64px (replace), not a remove
expect(result.inverse[0]).toEqual({
op: "replace",
path: "/elements/hf-title/inlineStyles/fontSize",
value: "64px",
});
});
it("emits the inverse for a kebab style removal (no DOM/patch desync)", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setStyle",
target: "hf-title",
styles: { "font-size": null },
});
// removal must be recorded (forward remove + inverse add restoring 64px)
expect(result.forward[0]?.op).toBe("remove");
expect(result.inverse[0]).toEqual({
op: "add",
path: "/elements/hf-title/inlineStyles/fontSize",
value: "64px",
});
const el = parsed.document.querySelector('[data-hf-id="hf-title"]');
expect(el?.getAttribute("style") ?? "").not.toContain("font-size");
});
});
// ─── setText ─────────────────────────────────────────────────────────────────
describe("setText", () => {
it("updates text content and emits replace patch", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "setText",
target: "hf-title",
value: "Goodbye World",
});
expect(result.forward[0]).toEqual({
op: "replace",
path: "/elements/hf-title/text",
value: "Goodbye World",
});
const el = parsed.document.querySelector('[data-hf-id="hf-title"]');
// text node should contain new value
expect(el?.textContent).toContain("Goodbye World");
});
it("inverse patches restore original text", () => {
const parsed = fresh();
const before = serializeDocument(parsed);
const { inverse } = applyOp(parsed, {
type: "setText",
target: "hf-title",
value: "Changed",
});
applyPatchesToDocument(parsed, inverse);
expect(serializeDocument(parsed)).toBe(before);
});
it("creates text node when element has no existing text node", () => {
const parsed = parseMutable(
'
',
);
const result = applyOp(parsed, { type: "setText", target: "hf-empty", value: "Added" });
const el = parsed.document.querySelector('[data-hf-id="hf-empty"]');
expect(el?.textContent).toBe("Added");
expect(result.forward[0]?.op).toBe("replace");
expect(result.forward[0]?.value).toBe("Added");
});
it("matches legacy single-child text targeting", () => {
const parsed = parseMutable(
'',
);
const result = applyOp(parsed, { type: "setText", target: "hf-target", value: "New" });
expect(serializeDocument(parsed)).toContain(
'',
);
expect(result.inverse[0]?.value).toBe("Old");
});
it("preserves parent text when the legacy target is a single child", () => {
const parsed = parseMutable(
'
',
);
});
it("keeps non-HTML single children out of the child text shortcut", () => {
const parsed = parseMutable(
'',
);
applyOp(parsed, { type: "setText", target: "hf-target", value: "New" });
const html = serializeDocument(parsed);
expect(html).toContain('New");
});
// A text edit never rewrites code or CSS: on a ",
});
const saved = parseHTML(serializeDocument(parsed)).document;
expect(saved.querySelectorAll("script").length).toBe(0);
expect(saved.querySelector("textarea")?.textContent).toContain("window.pwned=1");
});
it("override-set key maps correctly", () => {
expect(pathToKey("/elements/hf-title/text")).toBe("hf-title.text");
});
// A ` ` line break is a void element, not the element's text target. It
// must not make the heading read as empty (→ non-editable) nor be corrupted
// by setText. See getOwnText / setOwnText in model.ts.
describe(" line-break leaves", () => {
const brDoc = () =>
parseMutable(
'
Centrifugal Force
',
);
it("reads a -split heading as editable text (newline-joined), not empty", () => {
const parsed = brDoc();
// The inverse patch value is the pre-edit text — proves getOwnText read
// the heading as "Centrifugal\nForce" rather than "" (which surfaced as
// `text: null` → "not editable" in the studio panel).
const { inverse } = applyOp(parsed, { type: "setText", target: "hf-br", value: "x" });
expect(inverse[0]).toMatchObject({ value: "Centrifugal\nForce" });
});
it("preserves the when setting text (no corruption)", () => {
const parsed = brDoc();
applyOp(parsed, { type: "setText", target: "hf-br", value: "Centripetal\nForce" });
const html = serializeDocument(parsed);
expect(html).toContain("Centripetal");
expect(html).toContain("Force");
expect(html).toContain(" must stay empty — never gains a text child.
const br = parsed.document.querySelector('[data-hf-id="hf-br"] br');
expect(br?.textContent).toBe("");
});
it("drops the line break when the new text has no newline", () => {
const parsed = brDoc();
applyOp(parsed, { type: "setText", target: "hf-br", value: "Centrifugal Force" });
const h1 = parsed.document.querySelector('[data-hf-id="hf-br"]');
expect(h1?.querySelector("br")).toBeNull();
expect(h1?.textContent).toBe("Centrifugal Force");
});
it("reuses the existing node so an in-place edit round-trips exactly", () => {
const parsed = parseMutable(
'
',
});
expect(result.meta?.newId).toBeTruthy();
const newId = result.meta!.newId!;
const el = parsed.document.querySelector(`[data-hf-id="${newId}"]`);
expect(el).not.toBeNull();
expect(el?.tagName.toLowerCase()).toBe("p");
// Inserted at index 0 → first child of hf-stage
const stage = parsed.document.querySelector('[data-hf-id="hf-stage"]');
expect(stage?.firstElementChild?.getAttribute("data-hf-id")).toBe(newId);
});
it("insert at index >= childCount appends to parent", () => {
const parsed = fresh();
const stage = parsed.document.querySelector('[data-hf-id="hf-stage"]');
const countBefore = stage ? Array.from(stage.children).length : 0;
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 9999,
html: 'tail',
});
const newId = result.meta!.newId!;
const stageAfter = parsed.document.querySelector('[data-hf-id="hf-stage"]');
expect(stageAfter?.lastElementChild?.getAttribute("data-hf-id")).toBe(newId);
expect(Array.from(stageAfter?.children ?? []).length).toBe(countBefore + 1);
});
it("minted id is unique vs all existing doc ids", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 0,
html: '
content
',
});
const newId = result.meta!.newId!;
// Must not collide with any pre-existing id
const existingIds = ["hf-stage", "hf-title", "hf-logo", "hf-sub", "hf-span"];
expect(existingIds).not.toContain(newId);
// Must appear exactly once in the document
const all = Array.from(parsed.document.querySelectorAll(`[data-hf-id="${newId}"]`));
expect(all).toHaveLength(1);
});
it("content-collision with existing element yields a distinct rehashed id", () => {
// Insert a fragment with identical content to an existing element → dup-rehash must yield a distinct id
const parsed = fresh();
// hf-logo is
// Insert the same HTML without the data-hf-id so mintHfId runs fresh
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 0,
html: '',
});
const newId = result.meta!.newId!;
expect(newId).not.toBe("hf-logo");
expect(newId.startsWith("hf-")).toBe(true);
const el = parsed.document.querySelector(`[data-hf-id="${newId}"]`);
expect(el).not.toBeNull();
});
it("nested fragment: all new nodes get unique ids; root id returned", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 0,
html: '
ab
',
});
const rootId = result.meta!.newId!;
const root = parsed.document.querySelector(`[data-hf-id="${rootId}"]`);
expect(root).not.toBeNull();
// All children must have data-hf-id
const children = root ? Array.from(root.querySelectorAll("*")) : [];
for (const child of children) {
expect(child.getAttribute("data-hf-id")).toBeTruthy();
}
// All ids must be distinct
const allIds = [rootId, ...children.map((c) => c.getAttribute("data-hf-id") as string)];
expect(new Set(allIds).size).toBe(allIds.length);
});
it("forward patch is patchAdd; inverse patch is patchRemove — symmetry with removeElement", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-sub",
index: 0,
html: 'em text',
});
expect(result.forward).toHaveLength(1);
expect(result.inverse).toHaveLength(1);
expect(result.forward[0]?.op).toBe("add");
expect(result.inverse[0]?.op).toBe("remove");
const newId = result.meta!.newId!;
expect(result.forward[0]?.path).toBe(`/elements/${newId}`);
expect(result.inverse[0]?.path).toBe(`/elements/${newId}`);
});
it("applying inverse patch removes the added element (undo)", () => {
const parsed = fresh();
const { inverse, meta } = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 0,
html: '
undo me
',
});
const newId = meta!.newId!;
expect(parsed.document.querySelector(`[data-hf-id="${newId}"]`)).not.toBeNull();
applyPatchesToDocument(parsed, inverse);
expect(parsed.document.querySelector(`[data-hf-id="${newId}"]`)).toBeNull();
});
it("add → undo → redo: element returns with the same id (id stability)", () => {
const parsed = fresh();
// add
const { forward, inverse, meta } = applyOp(parsed, {
type: "addElement",
parent: "hf-stage",
index: 1,
html: 'redo',
});
const newId = meta!.newId!;
// undo
applyPatchesToDocument(parsed, inverse);
expect(parsed.document.querySelector(`[data-hf-id="${newId}"]`)).toBeNull();
// redo (replay forward patches)
applyPatchesToDocument(parsed, forward);
const restored = parsed.document.querySelector(`[data-hf-id="${newId}"]`);
expect(restored).not.toBeNull();
expect(restored?.getAttribute("data-hf-id")).toBe(newId);
});
it("parent: null inserts at document body root level", () => {
// Use a simple fragment doc
const parsed = parseMutable(
'',
);
const result = applyOp(parsed, {
type: "addElement",
parent: null,
index: 1,
html: '',
});
const newId = result.meta!.newId!;
const el = parsed.document.querySelector(`[data-hf-id="${newId}"]`);
expect(el).not.toBeNull();
expect(el?.parentElement?.tagName.toLowerCase()).toBe("body");
});
it("serialize round-trip: addElement survives serialize()", () => {
const parsed = fresh();
const result = applyOp(parsed, {
type: "addElement",
parent: "hf-sub",
index: 0,
html: 'bold',
});
const newId = result.meta!.newId!;
const serialized = serializeDocument(parsed);
expect(serialized).toContain(`data-hf-id="${newId}"`);
expect(serialized).toContain("bold");
});
// ─── validateOp ─────────────────────────────────────────────────────────────
it("validateOp: missing parent → E_TARGET_NOT_FOUND", () => {
const parsed = fresh();
const r = validateOp(parsed, {
type: "addElement",
parent: "hf-nonexistent",
index: 0,
html: "