Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): a text edited in place shows its caret in a scaled preview (#4875)
Miguel Ángele205207583df
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 28fb97023a..6642ce5e9b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -848,6 +848,8 @@ jobs:packages/studio/data/projects/studio-opencp -R packages/studio/tests/e2e/fixtures/fade-handles \packages/studio/data/projects/fade-handles+ cp -R packages/studio/tests/e2e/fixtures/inline-text-caret \+ packages/studio/data/projects/inline-text-caret- name: Read the base branch's work-count ceilings# A ceiling may not disappear, or rise without a new reason, against the branch this PR merges into.if: github.event_name == 'pull_request'@@ -973,6 +975,24 @@ jobs:fiSTUDIO_URL="http://localhost:5316/#project/fade-handles" \node packages/studio/tests/e2e/fade-handles.mjs+ - name: Measure the caret of a text edited in place+ if: success() || failure()+ run: |+ set -euo pipefail+ NODE_ENV=production bun run --cwd packages/studio dev -- --port 5317 --strictPort &+ SERVER_PID=$!+ trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT+ for i in $(seq 1 60); do+ if curl -sf "http://localhost:5317/" >/dev/null 2>&1; then break; fi+ sleep 1+ done+ if ! curl -sf "http://localhost:5317/" >/dev/null 2>&1; then+ echo "FAIL: studio dev server did not start on port 5317"+ exit 1+ fi+ STUDIO_URL="http://localhost:5317/#project/inline-text-caret" \+ EVIDENCE_DIR=/tmp/inline-text-caret \+ node packages/studio/tests/e2e/inline-text-caret.mjs- name: Upload gate evidence# The gate's whole output is machine-readable evidence, and a red run is# exactly when someone needs to read it. Keep it on failure too.@@ -983,6 +1003,7 @@ jobs:path: |/tmp/timeline-gate-*.json/tmp/studio-open-counts.json+ /tmp/inline-text-caret/*.pngif-no-files-found: error# Manual editing accuracy in the built Studio, gated against the base branch's baseline.json.diff --git a/packages/studio-server/src/helpers/fileVersion.test.ts b/packages/studio-server/src/helpers/fileVersion.test.tsindex bd3236f33f..d6c6d0e7a8 100644--- a/packages/studio-server/src/helpers/fileVersion.test.ts+++ b/packages/studio-server/src/helpers/fileVersion.test.ts@@ -132,6 +132,18 @@ describe("file versions and write receipts", () => {expect(identifyFileWrite("/project/index.html", restored)).not.toHaveProperty("from");});+ it("names what a write replaced only from the bytes it overwrote, never from its caller", () => {+ const version = fileContentVersion("<h1>Forged</h1>");+ recordFileWriteReceipt("/project/index.html", {+ path: "index.html",+ version,+ writeToken: "agent",+ // @ts-expect-error a receipt's `from` is derived, not given+ from: fileContentVersion("<h1>Title</h1>"),+ });+ expect(identifyFileWrite("/project/index.html", version)).not.toHaveProperty("from");+ });+it("labels a repeat of earlier bytes with the newest token, not the spent one", () => {const version = fileContentVersion("same bytes");const older = { path: "index.html", version, writeToken: "write-older" };diff --git a/packages/studio-server/src/helpers/fileVersion.ts b/packages/studio-server/src/helpers/fileVersion.tsindex e06e3b02eb..f4ebedc68e 100644--- a/packages/studio-server/src/helpers/fileVersion.ts+++ b/packages/studio-server/src/helpers/fileVersion.ts@@ -60,8 +60,16 @@ export function onFileOverwritten(listener: OverwriteListener): () => void {export function recordFileWriteReceipt(filePath: string,- { overwrote, ...receipt }: FileWriteReceipt & { overwrote?: string | Uint8Array },+ {+ overwrote,+ path,+ version,+ writeToken,+ }: Omit<FileWriteReceipt, "from"> & {+ overwrote?: string | Uint8Array;+ },): void {+ const receipt = { path, version, writeToken };const absPath = realFilePath(filePath);if (overwrote !== undefined)for (const listener of overwriteListeners) listener(absPath, receipt.version, overwrote);diff --git a/packages/studio/src/components/editor/InlineTextCaret.test.tsx b/packages/studio/src/components/editor/InlineTextCaret.test.tsxnew file mode 100644index 0000000000..a1b8aa08e9--- /dev/null+++ b/packages/studio/src/components/editor/InlineTextCaret.test.tsx@@ -0,0 +1,150 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanupMounted, trackedRoot } from "../ui/mountHost.testHelpers";+import { CARET_PX, InlineTextCaret } from "./InlineTextCaret";+import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(() => {+ // Unmount before clearing the body: the caret is portaled there, so clearing first orphans React's node.+ cleanupMounted();+ document.body.innerHTML = "";+ vi.restoreAllMocks();+});++/** A frame showing the composition at a quarter of its width, from 100,50 on Studio's screen. */+function fakeFrame() {+ const iframe = document.body.appendChild(document.createElement("iframe"));+ iframe.getBoundingClientRect = () =>+ ({ left: 100, top: 50, width: window.innerWidth / 4 }) as DOMRect;+ return iframe;+}++/** A text open for editing in a fake frame shown at a quarter of the composition's width, its caret after "Ti". */+function scene() {+ document.body.innerHTML = `<h1 contenteditable="true" style="color: rgb(250, 250, 250)">Title</h1>`;+ const element = document.body.firstElementChild as HTMLElement;+ const iframe = fakeFrame();+ vi.spyOn(Range.prototype, "getClientRects").mockReturnValue([+ { left: 400, top: 200, height: 120 },+ ] as unknown as DOMRectList);+ element.focus();+ const text = element.firstChild as Text;+ window.getSelection()!.collapse(text, 2);+ const session: InlineTextEditSession = {+ element,+ original: "Title",+ outline: "",+ outlineOffset: "",+ };+ return { element, iframe, session, text };+}++function render(session: InlineTextEditSession | null, iframe: HTMLIFrameElement | null) {+ const root = trackedRoot(document.body.appendChild(document.createElement("div")));+ act(() => root.render(<InlineTextCaret session={session} iframe={iframe} />));+ return { root, caret: () => document.querySelector<HTMLElement>("[data-inline-text-caret]") };+}++const fire = (target: EventTarget, type: string) =>+ act(() => void target.dispatchEvent(new Event(type)));++describe("InlineTextCaret", () => {+ it("draws a 2 px caret on Studio's screen where the composition's caret stands, in the text's colour", () => {+ const { iframe, session } = scene();+ const caret = render(session, iframe).caret();+ expect(caret).not.toBeNull();+ expect(caret!.style.left).toBe(`${100 + 400 / 4 - CARET_PX / 2}px`);+ expect(caret!.style.top).toBe(`${50 + 200 / 4}px`);+ expect(caret!.style.height).toBe(`${120 / 4}px`);+ expect(caret!.style.width).toBe(`${CARET_PX}px`);+ expect(caret!.style.background).toBe("rgb(250, 250, 250)");+ });++ it("follows a pan or zoom of the preview, which moves the iframe with no event", async () => {+ const { iframe, session } = scene();+ const caret = render(session, iframe).caret;+ iframe.getBoundingClientRect = () =>+ ({ left: 140, top: 50, width: window.innerWidth / 4 }) as DOMRect;+ await act(() => new Promise((done) => requestAnimationFrame(() => done(undefined))));+ expect(caret()!.style.left).toBe(`${140 + 400 / 4 - CARET_PX / 2}px`);+ });++ it("after End at a soft wrap the caret stands at the earlier line's end; after Home, at the next line's start", () => {+ const { element, iframe, session } = scene();+ // A collapsed range at a wrap point has the next line's box; the character before it ends the earlier line.+ vi.spyOn(Range.prototype, "getClientRects").mockImplementation(function (this: Range) {+ return (this.collapsed+ ? [{ left: 0, top: 320, height: 120 }]+ : [{ left: 300, right: 400, top: 200, height: 120 }]) as unknown as DOMRectList;+ });+ const caret = render(session, iframe).caret;+ const press = (key: string) => {+ act(() => void element.dispatchEvent(new KeyboardEvent("keydown", { key })));+ fire(document, "selectionchange");+ };+ press("End");+ expect([caret()!.style.left, caret()!.style.top]).toEqual([+ `${100 + 400 / 4 - CARET_PX / 2}px`,+ `${50 + 200 / 4}px`,+ ]);+ press("Shift");+ expect(caret()!.style.top, "a modifier alone keeps the side").toBe(`${50 + 200 / 4}px`);+ press("Home");+ expect([caret()!.style.left, caret()!.style.top]).toEqual([+ `${100 - CARET_PX / 2}px`,+ `${50 + 320 / 4}px`,+ ]);+ });++ it("shows no caret while a range is selected, and again once the selection collapses", () => {+ const { iframe, session, text } = scene();+ const { caret } = render(session, iframe);+ act(() => window.getSelection()!.setBaseAndExtent(text, 0, text, 3));+ fire(document, "selectionchange");+ expect(caret()).toBeNull();+ act(() => window.getSelection()!.collapse(text, 3));+ fire(document, "selectionchange");+ expect(caret()).not.toBeNull();+ });++ it("shows no caret while an input method composes, nor once the text loses focus", () => {+ const { element, iframe, session } = scene();+ const { caret } = render(session, iframe);+ fire(element, "compositionstart");+ expect(caret()).toBeNull();+ fire(element, "compositionend");+ expect(caret()).not.toBeNull();+ act(() => element.blur());+ fire(element, "blur");+ expect(caret()).toBeNull();+ });++ it("hides the browser's own caret while it draws one, and gives it back after", () => {+ const { element, iframe, session } = scene();+ element.style.caretColor = "red";+ const { root } = render(session, iframe);+ expect(element.style.caretColor).toBe("transparent");+ act(() => root.render(<InlineTextCaret session={null} iframe={iframe} />));+ expect(element.style.caretColor).toBe("red");+ });++ it("stands at the end of a bold word when the caret is past it, where no box of its own is drawn", () => {+ document.body.innerHTML = `<h1 contenteditable="true">Go <strong>bold</strong></h1>`;+ const element = document.body.firstElementChild as HTMLElement;+ const iframe = fakeFrame();+ vi.spyOn(Range.prototype, "getClientRects").mockImplementation(function (this: Range) {+ const rects = this.collapsed ? [] : [{ left: 300, right: 500, top: 200, height: 120 }];+ return rects as unknown as DOMRectList;+ });+ element.focus();+ window.getSelection()!.collapse(element, element.childNodes.length);+ const session = { element, original: "", outline: "", outlineOffset: "" };+ const caret = render(session, iframe).caret();+ expect(caret!.style.left).toBe(`${100 + 500 / 4 - CARET_PX / 2}px`);+ expect(caret!.style.top).toBe(`${50 + 200 / 4}px`);+ });+});diff --git a/packages/studio/src/components/editor/InlineTextCaret.tsx b/packages/studio/src/components/editor/InlineTextCaret.tsxnew file mode 100644index 0000000000..5c1dc0f811--- /dev/null+++ b/packages/studio/src/components/editor/InlineTextCaret.tsx@@ -0,0 +1,211 @@+import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";++/** The drawn caret's width on screen, whatever the preview's scale. */+export const CARET_PX = 2;++interface CaretPlacement {+ left: number;+ top: number;+ height: number;+ color: string;+}++/**+ * The caret of a text edited in place, drawn at screen size: the preview is scaled, so the browser's 1 px caret+ * shrinks below a pixel. This one follows the real selection; the browser's own is transparent meanwhile.+ */+export function InlineTextCaret({+ session,+ iframe,+}: {+ session: InlineTextEditSession | null;+ iframe: HTMLIFrameElement | null;+}) {+ const [placement, setPlacement] = useState<CaretPlacement | null>(null);+ const element = session?.element ?? null;++ useEffect(() => {+ if (!element || !iframe) {+ setPlacement(null);+ return;+ }+ const doc = element.ownerDocument;+ const view = doc.defaultView;+ const studio = iframe.ownerDocument.defaultView;+ const color = caretColorOf(element);+ const ownCaret = element.style.caretColor;+ element.style.caretColor = "transparent";+ let composing = false;+ let side: CaretSide = "after";+ const update = () =>+ setPlacement(composing ? null : placeAtCaret(element, iframe, color, side));+ // The DOM has no side for a soft-wrap point (one line's end is the next one's start): the key that moved there+ // says which, as CodeMirror and ProseMirror keep it.+ const onKey = ({ key }: KeyboardEvent) => {+ if (!MODIFIERS.has(key)) side = SIDE_OF_KEY[key] ?? "after";+ };+ const onPress = () => void (side = "after");+ const composition = (on: boolean) => () => {+ composing = on;+ update();+ };+ const start = composition(true);+ const end = composition(false);+ // The preview moves by transforms (the player's scale, a pan or zoom of the stage) that fire no event: the iframe's+ // box is checked each frame and a move re-places the caret.+ let box = "";+ let frame = 0;+ const follow = () => {+ const { left, top, width, height } = iframe.getBoundingClientRect();+ const now = `${left},${top},${width},${height}`;+ if (now !== box) {+ box = now;+ update();+ }+ frame = studio?.requestAnimationFrame(follow) ?? 0;+ };+ doc.addEventListener("selectionchange", update);+ element.addEventListener("keydown", onKey);+ element.addEventListener("pointerdown", onPress);+ element.addEventListener("input", update);+ element.addEventListener("focus", update);+ element.addEventListener("blur", update);+ element.addEventListener("compositionstart", start);+ element.addEventListener("compositionend", end);+ view?.addEventListener("resize", update);+ view?.addEventListener("scroll", update, true);+ follow();+ return () => {+ studio?.cancelAnimationFrame(frame);+ doc.removeEventListener("selectionchange", update);+ element.removeEventListener("keydown", onKey);+ element.removeEventListener("pointerdown", onPress);+ element.removeEventListener("input", update);+ element.removeEventListener("focus", update);+ element.removeEventListener("blur", update);+ element.removeEventListener("compositionstart", start);+ element.removeEventListener("compositionend", end);+ view?.removeEventListener("resize", update);+ view?.removeEventListener("scroll", update, true);+ element.style.caretColor = ownCaret;+ };+ }, [element, iframe]);++ if (!placement || !iframe) return null;+ // On Studio's body: a transformed ancestor in the canvas would make `fixed` relative to itself, not the viewport.+ return createPortal(+ <div+ // Keyed on where it stands, so each move starts the blink lit, as the system caret does.+ key={`${placement.left},${placement.top}`}+ data-inline-text-caret="true"+ aria-hidden="true"+ className="hf-inline-text-caret pointer-events-none fixed z-200"+ style={{+ left: placement.left,+ top: placement.top,+ width: CARET_PX,+ height: placement.height,+ background: placement.color,+ }}+ />,+ iframe.ownerDocument.body,+ );+}++/** The colour the browser would draw its caret in: `caret-color`, or the text's colour when that is `auto`. */+function caretColorOf(element: HTMLElement): string {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ if (!style) return "currentColor";+ return style.caretColor && style.caretColor !== "auto" ? style.caretColor : style.color;+}++type CaretSide = "before" | "after";+const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta"]);+// Only End leaves Chrome's own caret at the earlier line's end; an arrow onto a wrap point lands on the next line.+const SIDE_OF_KEY: Record<string, CaretSide> = { End: "before" };++/** Where the caret stands on Studio's screen, or null when there is none to draw: a range selected, the text not+ * focused, or the selection outside it. */++function placeAtCaret(+ element: HTMLElement,+ iframe: HTMLIFrameElement,+ color: string,+ side: CaretSide,+): CaretPlacement | null {+ const view = element.ownerDocument.defaultView;+ const range = view ? caretRange(element, view) : null;+ if (!view || !range) return null;+ const rect = (side === "before" && endOfCharBefore(range)) || caretRect(range, element, view);+ const box = iframe.getBoundingClientRect();+ const scale = view.innerWidth ? box.width / view.innerWidth : 1;+ return {+ left: box.left + rect.left * scale - CARET_PX / 2,+ top: box.top + rect.top * scale,+ height: rect.height * scale,+ color,+ };+}++/** The collapsed range's box on its line. A caret between two nodes has none, so it stands beside them; an empty+ * text has neither, so it stands at the text's start, one line tall. */+function caretRect(range: Range, element: HTMLElement, view: Window) {+ const last = [...range.getClientRects()].reverse().find((rect) => rect.height > 0);+ if (last) return { left: last.left, top: last.top, height: last.height };+ const beside = besideNode(range);+ if (beside) return beside;+ const style = view.getComputedStyle(element);+ const box = element.getBoundingClientRect();+ const fontSize = Number.parseFloat(style.fontSize) || 16;+ const line = Number.parseFloat(style.lineHeight) || fontSize * 1.2;+ return {+ left: box.left + (Number.parseFloat(style.paddingLeft) || 0),+ top: box.top + (Number.parseFloat(style.paddingTop) || 0),+ height: line,+ };+}++function caretRange(element: HTMLElement, view: Window): Range | null {+ const doc = element.ownerDocument;+ const selection = view.getSelection();+ if (!selection || selection.rangeCount === 0 || !selection.isCollapsed) return null;+ if (!doc.hasFocus() || !element.contains(doc.activeElement)) return null;+ const range = selection.getRangeAt(0);+ return element.contains(range.startContainer) ? range : null;+}++/** The right edge of the character just before a collapsed range in a text node: where a caret that came from+ * before a soft-wrap point stands, at the end of the earlier line. */+function endOfCharBefore({ startContainer: at, startOffset: offset }: Range) {+ if (at.nodeType !== Node.TEXT_NODE || offset === 0) return null;+ const char = at.ownerDocument!.createRange();+ // An emoji's second half alone has no box: take the whole pair.+ const low = /[\uDC00-\uDFFF]/.test((at as Text).data[offset - 1] ?? "");+ char.setStart(at, offset - (low && offset > 1 ? 2 : 1));+ char.setEnd(at, offset);+ // A trailing space at a wrap has a box on each line; the earlier line's comes first.+ const rect = [...char.getClientRects()].find((each) => each.height > 0);+ return rect ? { left: rect.right, top: rect.top, height: rect.height } : null;+}++/** At an element boundary: the end of the node before, or the start of the node after (a line break's own line). */+function besideNode(range: Range) {+ const [before, after] = neighbours(range);+ const node = before && before.nodeName !== "BR" ? before : (after ?? before);+ if (!node) return null;+ const around = range.cloneRange();+ around.selectNode(node);+ const rects = [...around.getClientRects()].filter((rect) => rect.height > 0);+ const end = node === before;+ const rect = end ? rects.at(-1) : rects[0];+ return rect ? { left: end ? rect.right : rect.left, top: rect.top, height: rect.height } : null;+}++/** The nodes either side of a collapsed range; an empty text node is a boundary too, between its siblings. */+function neighbours({ startContainer: at, startOffset: offset }: Range) {+ return at.nodeType === Node.TEXT_NODE+ ? [at.previousSibling, at.nextSibling]+ : [at.childNodes[offset - 1] ?? null, at.childNodes[offset] ?? null];+}diff --git a/packages/studio/src/components/editor/InlineTextToolbar.test.tsx b/packages/studio/src/components/editor/InlineTextToolbar.test.tsxindex b9b6f44eed..4d74cbe30e 100644--- a/packages/studio/src/components/editor/InlineTextToolbar.test.tsx+++ b/packages/studio/src/components/editor/InlineTextToolbar.test.tsx@@ -1,14 +1,16 @@// @vitest-environment happy-domimport React, { act } from "react";-import { createRoot } from "react-dom/client";import { afterEach, describe, expect, it } from "vitest";+import { cleanupMounted, trackedRoot } from "../ui/mountHost.testHelpers";import { InlineTextToolbar, swatchBackground } from "./InlineTextToolbar";import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;afterEach(() => {+ // Unmount before clearing the body: the bar is portaled there, so clearing first orphans React's node.+ cleanupMounted();document.body.innerHTML = "";});@@ -33,7 +35,7 @@ function scene(html: string) {function render(session: InlineTextEditSession | null, iframe: HTMLIFrameElement | null) {const host = document.createElement("div");document.body.append(host);- const root = createRoot(host);+ const root = trackedRoot(host);act(() => root.render(<InlineTextToolbar session={session} iframe={iframe} />));return { host, root, rerender: () => act(() => root.render(<div />)) };}@@ -49,8 +51,21 @@ function selectAll(element: HTMLElement) {});}+function selectAt(element: HTMLElement, top: number) {+ const range = document.createRange();+ range.selectNodeContents(element);+ range.getBoundingClientRect = () =>+ ({ left: 20, top, width: 100, height: 10 }) as unknown as DOMRect;+ const selection = document.getSelection()!;+ act(() => {+ selection.removeAllRanges();+ selection.addRange(range);+ document.dispatchEvent(new Event("selectionchange"));+ });+}+function toolbarIn(host: HTMLElement): HTMLElement | null {- return host.querySelector<HTMLElement>('[data-inline-text-toolbar="true"]');+ return host.ownerDocument.querySelector<HTMLElement>('[data-inline-text-toolbar="true"]');}function renderSelected(html = "hello world") {@@ -120,7 +135,7 @@ describe("InlineTextToolbar", () => {// these are the handlers that would deselect the element.const host = document.createElement("div");document.body.append(host);- const root = createRoot(host);+ const root = trackedRoot(host);act(() =>root.render(<div@@ -152,7 +167,7 @@ describe("InlineTextToolbar", () => {const { host } = render(session, iframe);selectAll(element);- const input = host.querySelector<HTMLInputElement>('input[type="color"]')!;+ const input = host.ownerDocument.querySelector<HTMLInputElement>('input[type="color"]')!;expect(input.className).toContain("w-full");expect(input.className).toContain("h-full");expect(input.className).toContain("min-w-0");@@ -161,14 +176,14 @@ describe("InlineTextToolbar", () => {it("styles the selected characters when a control is used", () => {const { element, host } = renderSelected();- act(() => host.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!.click());+ act(() => host.ownerDocument.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!.click());expect(element.innerHTML).toBe('<span style="font-weight: 700">hello world</span>');});it("ignores a click when the selection disappeared before React hid the toolbar", () => {const { element, host } = renderSelected();- const bold = host.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!;+ const bold = host.ownerDocument.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!;expect(() => {act(() => {@@ -185,8 +200,12 @@ describe("InlineTextToolbar", () => {selectAll(element);- expect(host.querySelector('[aria-label="Italic"]')?.getAttribute("aria-pressed")).toBe("true");- expect(host.querySelector('[aria-label="Bold"]')?.getAttribute("aria-pressed")).toBe("false");+ expect(+ host.ownerDocument.querySelector('[aria-label="Italic"]')?.getAttribute("aria-pressed"),+ ).toBe("true");+ expect(+ host.ownerDocument.querySelector('[aria-label="Bold"]')?.getAttribute("aria-pressed"),+ ).toBe("false");});it("turns a style back off when the control is used again", () => {@@ -194,7 +213,7 @@ describe("InlineTextToolbar", () => {const { host } = render(session, iframe);selectAll(element);- act(() => host.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!.click());+ act(() => host.ownerDocument.querySelector<HTMLButtonElement>('[aria-label="Bold"]')!.click());expect(element.innerHTML).toBe("words");});@@ -202,16 +221,7 @@ describe("InlineTextToolbar", () => {it("places itself over the selection, mapped out of the scaled composition", () => {const { element, session, iframe } = scene("hello world");const { host } = render(session, iframe);- const range = document.createRange();- range.selectNodeContents(element);- range.getBoundingClientRect = () =>- ({ left: 20, top: 40, width: 100, height: 10 }) as unknown as DOMRect;- const selection = document.getSelection()!;- act(() => {- selection.removeAllRanges();- selection.addRange(range);- document.dispatchEvent(new Event("selectionchange"));- });+ selectAt(element, 40);const toolbar = toolbarIn(host)!;// Frame at 100,50; scale 400/innerWidth; centre of the range, above it.@@ -223,16 +233,7 @@ describe("InlineTextToolbar", () => {const { element, session, iframe } = scene("hello world");iframe.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400 }) as DOMRect;const { host } = render(session, iframe);- const range = document.createRange();- range.selectNodeContents(element);- range.getBoundingClientRect = () =>- ({ left: 20, top: 0, width: 100, height: 10 }) as unknown as DOMRect;- const selection = document.getSelection()!;- act(() => {- selection.removeAllRanges();- selection.addRange(range);- document.dispatchEvent(new Event("selectionchange"));- });+ selectAt(element, 0);const toolbar = toolbarIn(host)!;const scale = 400 / window.innerWidth;@@ -271,7 +272,9 @@ describe("InlineTextToolbar", () => {selectAll(element);- expect(host.querySelector<HTMLInputElement>('input[type="color"]')?.value).toBe("#ff0000");+ expect(host.ownerDocument.querySelector<HTMLInputElement>('input[type="color"]')?.value).toBe(+ "#ff0000",+ );});});diff --git a/packages/studio/src/components/editor/InlineTextToolbar.tsx b/packages/studio/src/components/editor/InlineTextToolbar.tsxindex edf3c0bbf0..cc8f895490 100644--- a/packages/studio/src/components/editor/InlineTextToolbar.tsx+++ b/packages/studio/src/components/editor/InlineTextToolbar.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useState } from "react";+import { createPortal } from "react-dom";import { applyInlineStyle } from "./inlineTextStyleRange";import { readInlineStyle, readInlineStyleSpread } from "./inlineTextStyleRead";import { parseCssColor, toHexColor } from "./colorValue";@@ -69,10 +70,10 @@ export function InlineTextToolbar({[session, refresh],);- if (!placement) return null;+ if (!placement || !iframe) return null;const styles = placement.styles;- return (+ return createPortal(<divdata-inline-text-toolbar="true"role="toolbar"@@ -89,8 +90,8 @@ export function InlineTextToolbar({// The default, because a press anywhere in Studio moves the focus, and// moving it out of the text collapses the selection being styled.//- // The propagation, because this renders inside the canvas overlay: a- // press that reaches the canvas is read as a click on the composition,+ // The propagation, because React bubbles it through the canvas overlay+ // that renders this bar: a press that reaches the canvas is read as a click on the composition,// which deselects the element and commits the edit out from under the// button that was just pressed.onPointerDown={swallow}@@ -147,7 +148,8 @@ export function InlineTextToolbar({on={styles["text-decoration-line"] === "underline"}onToggle={(on) => apply({ "text-decoration-line": on ? "underline" : null })}/>- </div>+ </div>,+ iframe.ownerDocument.body,);}diff --git a/packages/studio/src/components/editor/domEditInlineText.ts b/packages/studio/src/components/editor/domEditInlineText.tsindex 56c8eab6e7..efc8c59048 100644--- a/packages/studio/src/components/editor/domEditInlineText.ts+++ b/packages/studio/src/components/editor/domEditInlineText.ts@@ -54,18 +54,20 @@ export function canEditElementTextInline(element: HTMLElement | null): boolean {}function hasOnlyFormattingChildren(element: HTMLElement): boolean {- const HTMLElementClass = element.ownerDocument.defaultView?.HTMLElement;- if (!HTMLElementClass) return false;for (const child of Array.from(element.children)) {if (!isRichTextFormattingTag(child.tagName)) return false;- if (!(child instanceof HTMLElementClass)) return false;+ if (!isHtmlFromAnyWindow(child)) return false;// Formatting nests, and a structural child hidden inside a span is still// structural.- if (!hasOnlyFormattingChildren(child)) return false;+ if (!hasOnlyFormattingChildren(child as HTMLElement)) return false;}return true;}+function isHtmlFromAnyWindow(node: Element): boolean {+ return node.namespaceURI === "http://www.w3.org/1999/xhtml";+}+/** Where and when a press landed, for recognising the next one as a pair. */export interface PressMark {x: number;diff --git a/packages/studio/src/components/editor/domEditInlineTextElement.test.ts b/packages/studio/src/components/editor/domEditInlineTextElement.test.tsindex c43ab7c807..ed90d0da90 100644--- a/packages/studio/src/components/editor/domEditInlineTextElement.test.ts+++ b/packages/studio/src/components/editor/domEditInlineTextElement.test.ts@@ -30,6 +30,13 @@ describe("canEditElementTextInline", () => {expect(canEditElementTextInline(element)).toBe(true);});+ it("opens styled copy whose formatting comes from another window", () => {+ const element = mount("<h1>a <strong>bold</strong></h1>");+ // happy-dom shares classes across windows; drop this window's HTMLElement as a foreign realm would.+ Object.setPrototypeOf(element.firstElementChild, Element.prototype);+ expect(canEditElementTextInline(element)).toBe(true);+ });+it("keeps out an element with a structural child, which the panel edits field by field", () => {expect(canEditElementTextInline(mount("<div><h1>a</h1><p>b</p></div>"))).toBe(false);});diff --git a/packages/studio/src/components/editor/useInlineTextEditing.tsx b/packages/studio/src/components/editor/useInlineTextEditing.tsxindex e52ef29c40..08cdf00728 100644--- a/packages/studio/src/components/editor/useInlineTextEditing.tsx+++ b/packages/studio/src/components/editor/useInlineTextEditing.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, type ReactNode, type RefObject } from "react";+import { InlineTextCaret } from "./InlineTextCaret";import { InlineTextToolbar } from "./InlineTextToolbar";import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";import { useInlineTextEdit } from "../../hooks/useInlineTextEdit";@@ -110,10 +111,16 @@ export function useInlineTextEditing(return {editing: inlineText.session !== null,toolbar: (- <InlineTextToolbar- session={inlineText.session}- iframe={actions?.previewIframeRef?.current ?? null}- />+ <>+ <InlineTextToolbar+ session={inlineText.session}+ iframe={actions?.previewIframeRef?.current ?? null}+ />+ <InlineTextCaret+ session={inlineText.session}+ iframe={actions?.previewIframeRef?.current ?? null}+ />+ </>),handleKeyDown,startFromPress: (event) => {diff --git a/packages/studio/src/components/ui/Menu.test.tsx b/packages/studio/src/components/ui/Menu.test.tsxindex 7c042264d7..c6c9ce8d10 100644--- a/packages/studio/src/components/ui/Menu.test.tsx+++ b/packages/studio/src/components/ui/Menu.test.tsx@@ -3,7 +3,6 @@import { readFileSync } from "node:fs";import path from "node:path";import React, { act, useState } from "react";-import { createRoot, type Root } from "react-dom/client";import { compile } from "tailwindcss";import { afterEach, beforeAll, describe, expect, it } from "vitest";import { loadStylesheet, STYLES_DIR } from "../../styles/styleSources";@@ -11,27 +10,11 @@ import { ContextMenu, Menu, MenuItem, MenuRadioGroup, MenuRadioItem, MenuSeparatimport { Popover } from "./Popover";import { isTypingTarget } from "../../utils/typingTarget";import { shouldIgnorePlaybackShortcutTarget } from "../../player/lib/playbackShortcuts";+import { cleanupMounted, mountHost as render } from "./mountHost.testHelpers";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-let mounted: { root: Root; host: HTMLElement } | null = null;--function render(element: React.ReactElement): HTMLElement {- const host = document.createElement("div");- document.body.append(host);- const root = createRoot(host);- mounted = { root, host };- act(() => root.render(element));- return host;-}--afterEach(() => {- if (!mounted) return;- const { root, host } = mounted;- mounted = null;- act(() => root.unmount());- host.remove();-});+afterEach(cleanupMounted);/** Base UI moves focus into the popup one task after open, not synchronously. */async function settle(): Promise<void> {@@ -310,9 +293,7 @@ describe("Popover", () => {renderOpen(false);await settle();expect(one("[role=dialog]", "popup").querySelector("svg")).toBeNull();- act(() => mounted?.root.unmount());- mounted?.host.remove();- mounted = null;+ cleanupMounted();renderOpen(true);await settle();diff --git a/packages/studio/src/components/ui/mountHost.testHelpers.ts b/packages/studio/src/components/ui/mountHost.testHelpers.tsindex 2c10d4adc3..6f647d359d 100644--- a/packages/studio/src/components/ui/mountHost.testHelpers.ts+++ b/packages/studio/src/components/ui/mountHost.testHelpers.ts@@ -4,6 +4,13 @@ import { createRoot, type Root } from "react-dom/client";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let mounted: { root: Root; host: HTMLElement } | null = null;+const tracked: Root[] = [];++export function trackedRoot(host: HTMLElement): Root {+ const root = createRoot(host);+ tracked.push(root);+ return root;+}/** Renders into a fresh host attached to the body; `cleanupMounted` tears it down. */export function mountHost(element: ReactElement): HTMLElement {@@ -16,6 +23,7 @@ export function mountHost(element: ReactElement): HTMLElement {}export function cleanupMounted(): void {+ act(() => tracked.splice(0).forEach((root) => root.unmount()));if (!mounted) return;const { root, host } = mounted;mounted = null;diff --git a/packages/studio/src/components/ui/valueControls.test.tsx b/packages/studio/src/components/ui/valueControls.test.tsxindex a15b040a78..75b3cc0112 100644--- a/packages/studio/src/components/ui/valueControls.test.tsx+++ b/packages/studio/src/components/ui/valueControls.test.tsx@@ -4,7 +4,6 @@ import { createRequire } from "node:module";import { readFileSync } from "node:fs";import path from "node:path";import React, { act } from "react";-import { createRoot, type Root } from "react-dom/client";import { compile } from "tailwindcss";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -21,33 +20,15 @@ import { Toggle } from "./Toggle";import { isTypingTarget } from "../../utils/typingTarget";import { shouldIgnorePlaybackShortcutTarget } from "../../player/lib/playbackShortcuts";import { __resetDesignInputThrottle, trackDesignInput } from "../../utils/designInputTracking";+import { cleanupMounted, mountHost as render } from "./mountHost.testHelpers";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-let mounted: { root: Root; host: HTMLElement } | null = null;--function render(element: React.ReactElement): HTMLElement {- const host = document.createElement("div");- document.body.append(host);- const root = createRoot(host);- mounted = { root, host };- act(() => root.render(element));- return host;-}--function unmount() {- if (!mounted) return;- const { root, host } = mounted;- mounted = null;- act(() => root.unmount());- host.remove();-}-beforeEach(() => {trackStudioEvent.mockReset();__resetDesignInputThrottle();});-afterEach(unmount);+afterEach(cleanupMounted);/** Base UI moves focus a task later than React renders; happy-dom is no faster. */const settle = () => act(async () => void (await new Promise((r) => setTimeout(r, 0))));diff --git a/packages/studio/src/styles/components.css b/packages/studio/src/styles/components.cssindex 7e643fd93b..72af960356 100644--- a/packages/studio/src/styles/components.css+++ b/packages/studio/src/styles/components.css@@ -517,6 +517,23 @@transition: transform 160ms ease;}+/* The caret of a text edited in place (InlineTextCaret): lit half the time, like the system caret */+.hf-inline-text-caret {+ animation: hf-inline-text-caret-blink 1.06s step-end infinite;+}++@keyframes hf-inline-text-caret-blink {+ 50% {+ opacity: 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .hf-inline-text-caret {+ animation: none;+ }+}+/* Toast enter/exit (StudioToast) */@keyframes hf-toast-in {from {diff --git a/packages/studio/tests/e2e/fixtures/inline-text-caret/hyperframes.json b/packages/studio/tests/e2e/fixtures/inline-text-caret/hyperframes.jsonnew file mode 100644index 0000000000..c4816b5eaa--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/inline-text-caret/hyperframes.json@@ -0,0 +1,8 @@+{+ "$schema": "https://hyperframes.heygen.com/schema/hyperframes.json",+ "paths": {+ "blocks": "compositions",+ "components": "compositions/components",+ "assets": "assets"+ }+}diff --git a/packages/studio/tests/e2e/fixtures/inline-text-caret/index.html b/packages/studio/tests/e2e/fixtures/inline-text-caret/index.htmlnew file mode 100644index 0000000000..353b5ddaf2--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/inline-text-caret/index.html@@ -0,0 +1,59 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=1920, height=1080" />+ <style>+ body {+ margin: 0;+ background: #0b0b0b;+ color: #fafafa;+ font-family: sans-serif;+ }+ #title {+ position: absolute;+ left: 160px;+ top: 160px;+ margin: 0;+ font-size: 160px;+ line-height: 1.1;+ }+ #mixed {+ position: absolute;+ left: 1200px;+ top: 160px;+ margin: 0;+ font-size: 96px;+ }+ #body {+ position: absolute;+ left: 160px;+ top: 520px;+ width: 900px;+ margin: 0;+ font-size: 72px;+ line-height: 1.2;+ }+ </style>+ </head>+ <body>+ <!-- A one-line title, a title ending in bold, and a paragraph that wraps onto three lines, each edited in place -->+ <div+ id="root"+ data-composition-id="main"+ data-start="0"+ data-duration="6"+ data-width="1920"+ data-height="1080"+ data-no-timeline+ >+ <h1 id="title" class="clip" data-start="0" data-duration="6" data-track-index="0">Title</h1>+ <h2 id="mixed" class="clip" data-start="0" data-duration="6" data-track-index="2">+ Go <strong>bold</strong>+ </h2>+ <p id="body" class="clip" data-start="0" data-duration="6" data-track-index="1">+ The quick brown fox jumps over the lazy dog and keeps on running far away+ </p>+ </div>+ </body>+</html>diff --git a/packages/studio/tests/e2e/inline-text-caret.mjs b/packages/studio/tests/e2e/inline-text-caret.mjsnew file mode 100644index 0000000000..19e1f01525--- /dev/null+++ b/packages/studio/tests/e2e/inline-text-caret.mjs@@ -0,0 +1,292 @@+#!/usr/bin/env node+// A text edited in place shows a caret on screen: the preview is drawn scaled, so the browser's own caret shrinks+// below a pixel. Layout, focus and media queries only exist in a real browser, so this measures it in Chrome.+import { mkdirSync } from "node:fs";+import { join } from "node:path";+import { launchStudioChrome } from "./chrome-executable.mjs";++const STUDIO_URL = process.env.STUDIO_URL;+const EVIDENCE_DIR = process.env.EVIDENCE_DIR;+const NEAR_PX = 1.5;++if (!STUDIO_URL) {+ console.error("STUDIO_URL is required and must point at the inline-text-caret fixture");+ process.exit(2);+}+if (EVIDENCE_DIR) mkdirSync(EVIDENCE_DIR, { recursive: true });+const { browser } = await launchStudioChrome();+const failures = [];+const evidence = {};+const check = (ok, what) => ok || failures.push(what);+const pause = (ms) => new Promise((done) => setTimeout(done, ms));++/** The drawn caret's box on screen, and the box the preview's own selection maps to there. */+async function read(page) {+ // A selection change is told to listeners a task later.+ await pause(150);+ const seen = await page.evaluate(() => {+ const frame = document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe");+ const doc = frame.contentDocument;+ const selection = doc.getSelection();+ const rects = selection.rangeCount ? [...selection.getRangeAt(0).getClientRects()] : [];+ const caret = document.querySelector("[data-inline-text-caret]");+ return {+ editing: doc.querySelector("[contenteditable]") !== null,+ collapsed: selection.isCollapsed,+ box: frame.getBoundingClientRect().toJSON(),+ scale: frame.getBoundingClientRect().width / frame.contentWindow.innerWidth,+ at: rects.at(-1)?.toJSON() ?? null,+ drawn: caret && {+ box: caret.getBoundingClientRect().toJSON(),+ animation: getComputedStyle(caret).animationName,+ },+ };+ });+ const { box, scale, at, drawn } = seen;+ return {+ editing: seen.editing,+ collapsed: seen.collapsed,+ caret: drawn && {+ left: drawn.box.left,+ top: drawn.box.top,+ width: drawn.box.width,+ height: drawn.box.height,+ },+ animation: drawn ? drawn.animation : null,+ expected: at && {+ left: box.left + at.left * scale,+ top: box.top + at.top * scale,+ height: at.height * scale,+ },+ };+}++/** The character before the caret, on Studio's screen: its right edge is where a line's end stands. */+const charBefore = (page) =>+ page.evaluate(() => {+ const frame = document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe");+ const box = frame.getBoundingClientRect();+ const scale = box.width / frame.contentWindow.innerWidth;+ const { anchorNode, anchorOffset } = frame.contentDocument.getSelection();+ const range = frame.contentDocument.createRange();+ range.setStart(anchorNode, anchorOffset - 1);+ range.setEnd(anchorNode, anchorOffset);+ const rect = [...range.getClientRects()][0];+ return { right: box.left + rect.right * scale, top: box.top + rect.top * scale };+ });++/** Where an element of the composition stands on Studio's screen. */+const onScreen = (page, selector) =>+ page.evaluate((selector) => {+ const frame = document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe");+ const box = frame.getBoundingClientRect();+ const scale = box.width / frame.contentWindow.innerWidth;+ const rect = frame.contentDocument.querySelector(selector).getBoundingClientRect();+ return {+ x: box.left + rect.left * scale,+ y: box.top + rect.top * scale,+ w: rect.width * scale,+ h: rect.height * scale,+ };+ }, selector);++// One press selects the element and Enter opens its text with the caret at the end: Studio's dependable way in, where+// a double press has to survive the canvas' gesture machinery.+/** Presses the text open, by a press and Enter or by a double press, and says whether its caret came. */+async function tryOpen(page, selector, xFraction, clickCount) {+ const at = await onScreen(page, selector);+ await page.mouse.click(at.x + at.w * xFraction, at.y + at.h / 2, { clickCount });+ await pause(600);+ if (clickCount === 1) await page.keyboard.press("Enter");+ for (let i = 0; i < 30; i++) if ((await read(page)).caret) return true;+ return false;+}++// A press can land while the last commit still reloads the preview: twice by press and Enter, then a double press.+async function openEdit(page, selector, xFraction = 0.5) {+ for (const clickCount of [1, 1, 2]) {+ if (await tryOpen(page, selector, xFraction, clickCount)) return;+ await shot(page, `not-opened-${selector.slice(1)}`);+ await page.keyboard.press("Escape");+ await pause(500);+ }+}++const shot = (page, name) =>+ EVIDENCE_DIR ? page.screenshot({ path: join(EVIDENCE_DIR, `${name}.png`) }) : null;++/** Holds every key but the last, presses the last, and lets go in reverse. */+async function chord(page, keys) {+ const held = keys.slice(0, -1);+ for (const each of held) await page.keyboard.down(each);+ await page.keyboard.press(keys.at(-1));+ for (const each of held.reverse()) await page.keyboard.up(each);+}++const spot = (caret) => (caret ? `${caret.left},${caret.top}` : "none");++/** Presses `keys` and reads once the caret has moved, or after 2 s. */+async function key(page, ...keys) {+ const was = spot((await read(page)).caret);+ await chord(page, keys);+ const deadline = Date.now() + 2000;+ let now = await read(page);+ while (Date.now() < deadline && spot(now.caret) === was) now = await read(page);+ return now;+}++const standsOnSelection = ({ caret, expected }) =>+ Boolean(caret && expected) &&+ Math.abs(caret.left + caret.width / 2 - expected.left) <= NEAR_PX &&+ Math.abs(caret.top - expected.top) <= NEAR_PX;++try {+ const page = await browser.newPage();+ await page.setViewport({ width: 1440, height: 900 });+ await page.emulateMediaFeatures([{ name: "prefers-reduced-motion", value: "no-preference" }]);+ await page.goto(STUDIO_URL, { waitUntil: "domcontentloaded" });+ await page.waitForFunction(+ () =>+ document+ .querySelector("hyperframes-player")+ ?.shadowRoot?.querySelector("iframe")+ ?.contentDocument?.querySelector("#body"),+ { timeout: 60_000 },+ );+ await pause(1000);++ await openEdit(page, "#title");+ evidence.opened = await read(page);+ check(evidence.opened.editing, "a press and Enter open the Title for editing");+ check(+ evidence.opened.caret?.width === 2,+ `the caret is 2 px wide on screen: ${evidence.opened.caret?.width}`,+ );+ check(+ evidence.opened.caret?.height > 8,+ `the caret is a line tall on screen: ${evidence.opened.caret?.height}`,+ );+ check(standsOnSelection(evidence.opened), "the caret stands where the selection is");+ check(evidence.opened.animation === "hf-inline-text-caret-blink", "the caret blinks");++ await page.keyboard.type("!");+ evidence.typed = await read(page);+ check(evidence.typed.caret?.left > evidence.opened.caret?.left, "typing moves the caret on");+ check(standsOnSelection(evidence.typed), "after typing, the caret stands where the selection is");++ await page.keyboard.down("Shift");+ await page.keyboard.press("ArrowLeft");+ await page.keyboard.up("Shift");+ evidence.selecting = await read(page);+ check(!evidence.selecting.caret, "no caret while a range is selected");+ // The style bar shows for a range; it is fixed too, so a transformed canvas would put it off the text.+ evidence.toolbar = await page.evaluate(() =>+ document.querySelector("[data-inline-text-toolbar]")?.getBoundingClientRect().toJSON(),+ );+ const picked = await onScreen(page, "#title");+ check(+ evidence.toolbar &&+ evidence.toolbar.right > picked.x &&+ evidence.toolbar.left < picked.x + picked.w &&+ Math.abs(evidence.toolbar.bottom - picked.y) < 120,+ `the style bar stands by the selected text: ${JSON.stringify(evidence.toolbar)} for ${JSON.stringify(picked)}`,+ );+ await page.keyboard.press("ArrowRight");+ evidence.collapsedAgain = await read(page);+ check(+ standsOnSelection(evidence.collapsedAgain),+ "an arrow key collapses the range and the caret is back",+ );+ // The player rescales the iframe by a transform, which the iframe's own size never shows.+ await page.setViewport({ width: 1200, height: 800 });+ await pause(500);+ evidence.resized = await read(page);+ check(+ standsOnSelection(evidence.resized),+ "after the window resizes, the caret stands where the selection is",+ );+ await page.setViewport({ width: 1440, height: 900 });+ await pause(500);+ await page.keyboard.press("Escape");+ await pause(500);+ check(!(await read(page)).caret, "no caret once the edit ends");++ // Enter puts the caret after the last child; past a <strong> that is an element boundary, which has no box.+ await openEdit(page, "#mixed", 0.1);+ evidence.boundary = await read(page);+ const bold = await onScreen(page, "#mixed strong");+ check(+ Math.abs(+ evidence.boundary.caret?.left + evidence.boundary.caret?.width / 2 - (bold.x + bold.w),+ ) <= NEAR_PX,+ `past a bold word the caret stands at its end: ${evidence.boundary.caret?.left} for ${bold.x + bold.w}`,+ );+ await page.keyboard.press("Escape");+ await pause(500);++ // The paragraph wraps onto three lines. End's spot at a soft wrap is also the next line's start: the caret keeps the+ // side End gave it and stands at the end of the first line, after its last character.+ await openEdit(page, "#body");+ // Enter opens it with the caret at the end; Ctrl+Home takes it to the first line.+ const lineStart = await key(page, "Control", "Home");+ evidence.lineEnd = await key(page, "End");+ const lastChar = await charBefore(page);+ check(+ Math.abs(evidence.lineEnd.caret?.top - lineStart.caret?.top) <= NEAR_PX &&+ Math.abs(evidence.lineEnd.caret?.left + evidence.lineEnd.caret?.width / 2 - lastChar.right) <=+ NEAR_PX,+ `End keeps the caret at its line's end: ${JSON.stringify(evidence.lineEnd.caret)} for ${JSON.stringify(lastChar)}`,+ );+ evidence.nextLine = await key(page, "ArrowDown");+ check(+ evidence.nextLine.caret?.top > evidence.lineEnd.caret?.top,+ "ArrowDown moves the caret down a line",+ );+ check(+ standsOnSelection(evidence.nextLine),+ "on the next line the caret stands where the selection is",+ );+ // Shift+Enter at the text's end opens an empty line, which has no box either: the caret stands at its start.+ await key(page, "Control", "End");+ evidence.emptyLine = await key(page, "Shift", "Enter");+ const body = await onScreen(page, "#body");+ check(+ evidence.emptyLine.caret?.top > evidence.nextLine.caret?.top &&+ Math.abs(evidence.emptyLine.caret?.left + evidence.emptyLine.caret?.width / 2 - body.x) <=+ NEAR_PX,+ `on an empty line the caret stands at its start: ${JSON.stringify(evidence.emptyLine.caret)} for ${body.x}`,+ );++ await page.emulateMediaFeatures([{ name: "prefers-reduced-motion", value: "reduce" }]);+ evidence.reduced = await read(page);+ check(evidence.reduced.animation === "none", "under reduced motion the caret does not blink");+ if (EVIDENCE_DIR)+ await page.screenshot({ path: join(EVIDENCE_DIR, "inline-text-caret-multiline.png") });+ await page.keyboard.press("Escape");+ await pause(500);++ await openEdit(page, "#title");+ const { caret } = await read(page);+ if (EVIDENCE_DIR && caret) {+ const clip = { x: caret.left - 80, y: caret.top - 16, width: 160, height: caret.height + 32 };+ await page.screenshot({ path: join(EVIDENCE_DIR, "after-caret.png"), clip });+ // What the preview showed without this change: the browser's own caret, the drawn one hidden.+ await page.evaluate(() => {+ document.querySelector("[data-inline-text-caret]").style.visibility = "hidden";+ const frame = document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe");+ frame.contentDocument.querySelector("#title").style.caretColor = "";+ });+ await page.screenshot({ path: join(EVIDENCE_DIR, "before-caret.png"), clip });+ await page.screenshot({ path: join(EVIDENCE_DIR, "inline-text-caret-title.png") });+ }+ await page.evaluate(() =>+ document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe").blur(),+ );+ await page.mouse.click(5, 5);+ await pause(500);+ check(!(await read(page)).caret, "no caret once the text loses focus");+} finally {+ await browser.close();+}+console.log(JSON.stringify({ evidence, failures }, null, 2));+if (failures.length > 0) process.exit(1);