Skip to content
118 changes: 118 additions & 0 deletions packages/core/src/runtime/editing/captionTransform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// `caption-transform`: reads and moves caption words, on a wrapper so the word's own tweens keep running.
import { MAX_DESCRIBE_HANDLES, type EditingRect } from "../editingElement";
import { captionWordSpans, isCaptionIndex, isRecord } from "./captionWords";

export interface CaptionTransform {
x: number;
y: number;
scale: number;
rotation: number;
}

/** `set` writes those parts and keeps the rest; without it the word is only read. */
export interface CaptionTransformEntry {
group: number;
word: number;
set?: Partial<CaptionTransform>;
}
export type CaptionTransformParams = { entries: CaptionTransformEntry[] };

/** The wrapper's transform after any write, and the word's box; null for a word the frame lacks. */
export type CaptionWordState = { transform: CaptionTransform; rect: EditingRect } | null;

const REST: CaptionTransform = { x: 0, y: 0, scale: 1, rotation: 0 };
const PARTS = new Set(Object.keys(REST));
/** Largest |x|, |y|, scale or rotation a caption word's transform may hold, in either direction. */
export const MAX_CAPTION_TRANSFORM = 100_000;

const isBounded = (value: unknown): value is number =>
Number.isFinite(value) && Math.abs(value as number) <= MAX_CAPTION_TRANSFORM;

function transformPart(set: unknown): Partial<CaptionTransform> | null {
if (!isRecord(set)) return null;
const valid = Object.entries(set).every(([key, v]) => PARTS.has(key) && isBounded(v));
return valid ? (set as Partial<CaptionTransform>) : null;
}

function entry(value: unknown): CaptionTransformEntry | null {
if (!isRecord(value)) return null;
const { group, word, set, ...rest } = value;
if (Object.keys(rest).length || !isCaptionIndex(group) || !isCaptionIndex(word)) return null;
if (!("set" in value)) return { group, word };
const part = transformPart(set);
return part ? { group, word, set: part } : null;
}

export function captionTransformParams(params: unknown): CaptionTransformParams | null {
if (!isRecord(params) || Object.keys(params).join() !== "entries") return null;
const { entries } = params;
if (!Array.isArray(entries) || !entries.length || entries.length > MAX_DESCRIBE_HANDLES)
return null;
const parsed = entries.map(entry);
return parsed.includes(null) ? null : { entries: parsed as CaptionTransformEntry[] };
}

type Gsap = {
getProperty?: (el: Element, prop: string) => number;
set?: (el: Element, props: Record<string, number>) => void;
};
const frameGsap = () => (window as unknown as { gsap?: Gsap }).gsap;

const CSS_PARTS: Array<[keyof CaptionTransform, RegExp]> = [
["x", /translate\(([^,]+)px,\s*[^)]+px\)/],
["y", /translate\([^,]+px,\s*([^)]+)px\)/],
["scale", /scale\(([^)]+)\)/],
["rotation", /rotate\(([^)]+)deg\)/],
];

/** GSAP keeps transforms in its own cache, so read through it when the page has it. */
function readTransform(el: HTMLElement): CaptionTransform {
const gsap = frameGsap();
const read = { ...REST };
for (const [part, pattern] of CSS_PARTS) {
if (gsap?.getProperty) read[part] = gsap.getProperty(el, part) || REST[part];
else {
const match = (el.style.transform || "").match(pattern);
if (match) read[part] = parseFloat(match[1]!);
}
}
return read;
}

function writeTransform(el: HTMLElement, { x, y, scale, rotation }: CaptionTransform): void {
const gsap = frameGsap();
if (gsap?.set) gsap.set(el, { x, y, scale, rotation });
else
el.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px) rotate(${rotation.toFixed(1)}deg) scale(${scale.toFixed(3)})`;
}

function wrapperOf(word: HTMLElement): HTMLElement {
if (word.dataset.captionWrapper === "true") return word;
const parent = word.parentElement;
if (parent?.dataset.captionWrapper === "true") return parent;
const wrapper = document.createElement("span");
wrapper.style.display = "inline-block";
wrapper.dataset.captionWrapper = "true";
word.parentNode?.insertBefore(wrapper, word);
wrapper.appendChild(word);
return wrapper;
}

function wordAt(group: number, word: number): HTMLElement | null {
const el = document.querySelectorAll<HTMLElement>(".caption-group")[group];
return el ? (captionWordSpans(el)[word] ?? null) : null;
}

export function captionTransform({ entries }: CaptionTransformParams): {
words: CaptionWordState[];
} {
const words = entries.map(({ group, word, set }) => {
const el = wordAt(group, word);
if (!el) return null;
const wrapper = wrapperOf(el);
if (set) writeTransform(wrapper, { ...readTransform(wrapper), ...set });
const { left, top, width, height } = el.getBoundingClientRect();
return { transform: readTransform(wrapper), rect: { x: left, y: top, width, height } };
});
return { words };
}
59 changes: 59 additions & 0 deletions packages/core/src/runtime/editing/captionWords.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { afterEach, expect, it } from "vitest";
import { captionWords } from "./captionWords";
import { captionTransform } from "./captionTransform";

afterEach(() => {
document.body.innerHTML = "";
Reflect.deleteProperty(window, "gsap");
});

it("splits a plain-text group into word spans and boxes only visible groups' words", () => {
document.body.innerHTML = `<div class="caption-group">Hello big world</div>
<div class="caption-group" style="opacity: 0"><span>hidden</span></div>
<div class="caption-group"><span>one</span><span>two</span></div>`;
const { boxes } = captionWords({ words: [2, 1, 5] });
expect(boxes.map(({ group, word }) => [group, word])).toEqual([
[0, 0],
[0, 1],
[2, 0],
[2, 1],
]);
const [first, , third] = document.querySelectorAll(".caption-group");
expect([...first!.children].map((s) => s.textContent)).toEqual(["Hello ", "big ", "world "]);
expect(third!.innerHTML).toBe("<span>one</span><span>two</span>");
});

it("moves a word on a wrapper with a CSS transform, keeping the parts it was not given", () => {
document.body.innerHTML = `<div class="caption-group"><span>a</span><span>b</span></div>`;
const moved = captionTransform({ entries: [{ group: 0, word: 1, set: { x: 3, rotation: 9 } }] });
expect(moved.words[0]!.transform).toEqual({ x: 3, y: 0, scale: 1, rotation: 9 });
const b = document.querySelectorAll("span:not([data-caption-wrapper])")[1]!;
expect((b.parentElement as HTMLElement).style.transform).toBe(
"translate(3.0px, 0.0px) rotate(9.0deg) scale(1.000)",
);
const again = captionTransform({ entries: [{ group: 0, word: 1, set: { y: 4 } }] });
expect(again.words[0]!.transform).toEqual({ x: 3, y: 4, scale: 1, rotation: 9 });
expect(document.querySelectorAll("[data-caption-wrapper]")).toHaveLength(1);
expect(
captionTransform({
entries: [
{ group: 0, word: 2 },
{ group: 1, word: 0 },
],
}).words,
).toEqual([null, null]);
});

it("moves a word through the page's GSAP when it has one", () => {
const props = new WeakMap<Element, Record<string, number>>();
Reflect.set(window, "gsap", {
getProperty: (el: Element, prop: string) => props.get(el)?.[prop] ?? 0,
set: (el: Element, values: Record<string, number>) => props.set(el, values),
});
document.body.innerHTML = `<div class="caption-group"><span>a</span></div>`;
const { words } = captionTransform({ entries: [{ group: 0, word: 0, set: { scale: 2 } }] });
expect(words[0]!.transform).toEqual({ x: 0, y: 0, scale: 2, rotation: 0 });
const wrapper = document.querySelector<HTMLElement>("[data-caption-wrapper]")!;
expect(props.get(wrapper)).toEqual({ x: 0, y: 0, scale: 2, rotation: 0 });
expect(wrapper.style.transform).toBe("");
});
89 changes: 89 additions & 0 deletions packages/core/src/runtime/editing/captionWords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// `caption-words`: the caption editor's word boxes, read where the words live.
import { MAX_QUERY_MATCHES, type EditingRect } from "../editingElement";

const MAX_CAPTION_WORDS = 100_000;

export const isRecord = (value: unknown): value is Record<string, unknown> =>
Object.prototype.toString.call(value) === "[object Object]";

/** Word `word` of the `group`-th `.caption-group`, both counted from 0. */
export interface CaptionWordBox {
group: number;
word: number;
/** `getBoundingClientRect()` of the word, in the frame's CSS pixels. */
rect: EditingRect;
}

/** `words[i]` is how many words Studio's model has in the i-th `.caption-group`. */
export type CaptionWordsParams = { words: number[] };

export const isCaptionIndex = (value: unknown): value is number =>
Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) < MAX_CAPTION_WORDS;

export function captionWordsParams(params: unknown): CaptionWordsParams | null {
if (!isRecord(params) || Object.keys(params).join() !== "words") return null;
const { words } = params;
if (!Array.isArray(words) || words.length > MAX_CAPTION_WORDS) return null;
return words.every(isCaptionIndex) ? { words } : null;
}

/** A group's word spans in order: a wrapped word is the span inside its wrapper. */
export function captionWordSpans(group: HTMLElement): HTMLElement[] {
const spans: HTMLElement[] = [];
for (const child of group.children) {
const el = child as HTMLElement;
if (el.dataset.captionWrapper === "true") {
const inner = el.querySelector<HTMLElement>(":scope > span");
if (inner) spans.push(inner);
} else if (el.tagName === "SPAN") {
spans.push(el);
}
}
return spans;
}

function splitIntoSpans(text: string, replace: (fragment: DocumentFragment) => void) {
const fragment = document.createDocumentFragment();
const spans = text
.split(/\s+/)
.filter(Boolean)
.map((word) => {
const span = document.createElement("span");
span.textContent = word + " ";
span.style.display = "inline";
return fragment.appendChild(span);
});
replace(fragment);
return spans;
}

/** A group written as plain text becomes one span per word, so each word can be picked. */
function splitGroupText(group: HTMLElement): HTMLElement[] {
const text = group.childNodes[0];
if (text?.nodeType === Node.TEXT_NODE) {
return splitIntoSpans(text.textContent || "", (f) => group.replaceChild(f, text));
}
const single = group.querySelector<HTMLElement>(":scope > span");
if (!single?.textContent?.trim()) return [];
return splitIntoSpans(single.textContent, (f) => single.replaceWith(f));
}

/** Boxes of the words in visible groups, up to MAX_QUERY_MATCHES. */
export function captionWords({ words }: CaptionWordsParams): { boxes: CaptionWordBox[] } {
const groups = document.querySelectorAll<HTMLElement>(".caption-group");
const boxes: CaptionWordBox[] = [];
words.forEach((count, group) => {
const el = groups[group];
if (!el) return;
const computed = window.getComputedStyle(el);
if (parseFloat(computed.opacity) <= 0.01 || computed.visibility === "hidden") return;
let spans = captionWordSpans(el);
if (spans.length === 0 && el.textContent?.trim()) spans = splitGroupText(el);
for (let word = 0; word < Math.min(count, spans.length); word++) {
if (boxes.length >= MAX_QUERY_MATCHES) return;
const { left, top, width, height } = spans[word]!.getBoundingClientRect();
boxes.push({ group, word, rect: { x: left, y: top, width, height } });
}
});
return { boxes };
}
24 changes: 24 additions & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ describe("installEditingAgent", () => {
"console-errors",
"watch-keys",
"restore-attributes",
"caption-words",
"caption-transform",
],
},
});
Expand Down Expand Up @@ -402,6 +404,28 @@ describe("installEditingAgent", () => {
"invalid-params",
],
),
...[{}, { words: 3 }, { words: [-1] }, { words: [1.5] }, { words: [100_000] }].map(
(params, index) => [
{ v: 1, id: 190 + index, kind: "caption-words", params },
190 + index,
"invalid-params",
],
),
...[
{ entries: [] },
{ entries: Array(257).fill({ group: 0, word: 0 }) },
{ entries: [{ group: -1, word: 0 }] },
{ entries: [{ group: 0, word: 0, extra: 1 }] },
{ entries: [{ group: 0, word: 0, set: { x: 100_001 } }] },
{ entries: [{ group: 0, word: 0, set: { x: Infinity } }] },
{ entries: [{ group: 0, word: 0, set: { x: undefined } }] },
{ entries: [{ group: 0, word: 0, set: { skew: 1 } }] },
{ entries: [{ group: 0, word: 0, set: [] }] },
].map((params, index) => [
{ v: 1, id: 200 + index, kind: "caption-transform", params },
200 + index,
"invalid-params",
]),
])("rejects %j with a typed error", async (request, id, code) => {
const setLoopStart = vi.fn();
window.__hf = { setLoopStart };
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import {
import { MAX_QUERY_MATCHES } from "./editingElement";
import { matchCombo, parseCombo, type Combo } from "../keyCombo";
import { shouldIgnorePlaybackShortcutTarget } from "../typingTarget";
import { captionWords } from "./editing/captionWords";
import { captionTransform } from "./editing/captionTransform";

type Handlers = {
[K in EditingRequestKind]: (
Expand Down Expand Up @@ -190,6 +192,8 @@ const HANDLERS: Handlers = {
},
"watch-keys": ({ combos }, port) => watchKeys(port, combos),
"restore-attributes": (params) => restoreAttributes(params),
"caption-words": captionWords,
"caption-transform": captionTransform,
};

function serve(port: MessagePort): void {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ describe("createEditingPortClient", () => {
"console-errors",
"watch-keys",
"restore-attributes",
"caption-words",
"caption-transform",
],
});
} finally {
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ import type { EditingLayer } from "./editingLayers";
import type { RuntimeTimelineMessage } from "./types";
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
import { parseCombo } from "../keyCombo";
import {
captionWordsParams,
type CaptionWordBox,
type CaptionWordsParams,
} from "./editing/captionWords";
import {
captionTransformParams,
type CaptionTransformParams,
type CaptionWordState,
} from "./editing/captionTransform";

export {
buildStableSelector,
Expand Down Expand Up @@ -61,6 +71,7 @@ export {
type ElementTransformSnapshot,
} from "./editingGeometry";
export type { EditingGestureStart } from "./editingGestureStart";
export { MAX_CAPTION_TRANSFORM } from "./editing/captionTransform";
export {
compositionPoint,
coversComposition,
Expand Down Expand Up @@ -111,6 +122,8 @@ export const EDITING_REQUEST_KINDS = [
"console-errors",
"watch-keys",
"restore-attributes",
"caption-words",
"caption-transform",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];

Expand Down Expand Up @@ -220,6 +233,9 @@ export interface EditingRequests {
* keyups to this port; an empty list stops. */
"watch-keys": { params: { combos: string[] }; result: { watching: number } };
"restore-attributes": { params: RestoreAttributesParams; result: { applied: boolean } };
/** Boxes of the words of visible caption groups; a group written as plain text is split into word spans. */
"caption-words": { params: CaptionWordsParams; result: { boxes: CaptionWordBox[] } };
"caption-transform": { params: CaptionTransformParams; result: { words: CaptionWordState[] } };
}
export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
Expand Down Expand Up @@ -407,6 +423,8 @@ const PARAM_PARSERS: {
hasKeys(params, "from") && isOffset(params.from) ? { from: params.from } : null,
"watch-keys": comboList,
"restore-attributes": parseRestoreAttributes,
"caption-words": captionWordsParams,
"caption-transform": captionTransformParams,
};

/** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
Expand Down
Loading
Loading