mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(studio): timeline clips from the preview keep numeric fields, and drops write them as numbers (#8438)
* fix(studio): keep a preview frame's clip timing and track numeric Clips from a preview frame's timeline message or runtime snapshot are kept only when start and duration are finite numbers and track is a whole number. Asset drop, file drop, paste and duplicate write data-track-index as a whole number, and paste checks a clip's markup for running code after its root tag takes the new start and track. * fix(studio): write a dropped asset's start and duration as finite numbers buildTimelineAssetInsertHtml writes data-start and data-duration through formatTimelineAttributeNumber, with a non-finite or non-number value written as 0, so a store row's timing cannot add text to the tag.
This commit is contained in:
@@ -250,6 +250,20 @@ describe("pasteTimelineClips", () => {
|
||||
expect(ids).toEqual(["sfx-23"]);
|
||||
});
|
||||
|
||||
it("writes a whole-number track when the copied or the live clips' tracks are not numbers", () => {
|
||||
const textTrack = '0" onload="x' as unknown as number;
|
||||
const live = [
|
||||
{ ...liveElement(5, 0, 1), authoredTrack: "$' onclick=\"y" as unknown as number },
|
||||
];
|
||||
for (const saved of [false, true]) {
|
||||
const copied = { ...clip("sfx-23", 21.61, 0.57, 132), track: textTrack, saved };
|
||||
const { content } = pasteTimelineClips(ROOT, [copied], 40, live);
|
||||
expect(content).toMatch(/<audio id="sfx-23"[^>]* data-track-index="0"/);
|
||||
expect(content).not.toContain("onload");
|
||||
expect(content).not.toContain("onclick");
|
||||
}
|
||||
});
|
||||
|
||||
it("reports the furthest clip end across the whole batch as requiredEnd, not just the last clip's", () => {
|
||||
// The batch is placed in order sfx-23, sfx-24, sfx-25, but sfx-24 ends up
|
||||
// the furthest forward once offsets are applied; requiredEnd must track
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "../utils/clipboardPayload";
|
||||
import { carryLook, renamedIds } from "../utils/clipboardLook";
|
||||
import { collectHtmlIds } from "../utils/studioHelpers";
|
||||
import { insertTimelineAssetIntoSource } from "../utils/timelineAssetDrop";
|
||||
import { insertTimelineAssetIntoSource, writtenTrackIndex } from "../utils/timelineAssetDrop";
|
||||
import { extendRootDurationInSource } from "../utils/rootDuration";
|
||||
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
|
||||
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
|
||||
@@ -158,16 +158,20 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl
|
||||
return maxTrack + 1;
|
||||
}
|
||||
|
||||
/** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here,
|
||||
* inside the edit, or the server stamps them on the next preview load, behind undo's back.
|
||||
* DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */
|
||||
function remintHfIds(html: string, parser: DOMParser, taken: Set<string>, saved = false): string {
|
||||
const doc = parser.parseFromString(html, "text/html");
|
||||
function refuseRunningCode(doc: Document, saved = false): void {
|
||||
if (!saved && unsafeMarkup(doc.documentElement).length > 0) {
|
||||
throw new Error(
|
||||
"Couldn't paste: the copied element runs code (a script, an event handler or a script link)",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here,
|
||||
* inside the edit, or the server stamps them on the next preview load, behind undo's back.
|
||||
* DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */
|
||||
function remintHfIds(html: string, parser: DOMParser, taken: Set<string>, saved = false): string {
|
||||
const doc = parser.parseFromString(html, "text/html");
|
||||
refuseRunningCode(doc, saved);
|
||||
const root = doc.body.firstElementChild;
|
||||
if (!root) {
|
||||
// A tag the HTML parser hoists out of <body> (title/meta/style/base/link)
|
||||
@@ -219,7 +223,7 @@ export function pasteTimelineClips(
|
||||
const groupMinStart = Math.min(...clips.map((c) => c.start));
|
||||
let existingIds = collectHtmlIds(content);
|
||||
const taken: PlacedClip[] = liveElements.map((el) => ({
|
||||
track: el.authoredTrack ?? el.track,
|
||||
track: writtenTrackIndex(el.authoredTrack ?? el.track),
|
||||
start: el.start,
|
||||
duration: el.duration,
|
||||
}));
|
||||
@@ -234,7 +238,7 @@ export function pasteTimelineClips(
|
||||
existingIds = existingIds.concat(collectHtmlIds(deduped));
|
||||
const newStart = anchorTime + (clip.start - groupMinStart);
|
||||
const newTrack = resolveFreeTrack(
|
||||
{ track: clip.track, start: newStart, duration: clip.duration },
|
||||
{ track: writtenTrackIndex(clip.track), start: newStart, duration: clip.duration },
|
||||
taken,
|
||||
);
|
||||
taken.push({ track: newTrack, start: newStart, duration: clip.duration });
|
||||
@@ -249,6 +253,7 @@ export function pasteTimelineClips(
|
||||
.replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`)
|
||||
.replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
|
||||
const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
|
||||
refuseRunningCode(domParser.parseFromString(withPatched, "text/html"), clip.saved);
|
||||
result = insertTimelineAssetIntoSource(result, withPatched);
|
||||
if (fromThisFile) {
|
||||
const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { pasteTimelineClips } from "./useClipboard";
|
||||
|
||||
const checked = vi.hoisted(() => [] as string[]);
|
||||
vi.mock("@hyperframes/core/html-attr-safety", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@hyperframes/core/html-attr-safety")>();
|
||||
return {
|
||||
...actual,
|
||||
unsafeMarkup: (root: Element) => {
|
||||
checked.push(root.outerHTML);
|
||||
return actual.unsafeMarkup(root);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const ROOT = '<div data-composition-id="main" data-start="0" data-duration="10"></div>';
|
||||
|
||||
describe("pasteTimelineClips code check", () => {
|
||||
it("checks the clip markup after its root tag takes the new start and track", () => {
|
||||
const copied = {
|
||||
html: '<audio id="sfx" src="a.mp3" data-start="7.8" data-duration="1" data-track-index="9"></audio>',
|
||||
start: 7.8,
|
||||
duration: 1,
|
||||
track: 9,
|
||||
};
|
||||
pasteTimelineClips(ROOT, [copied], 40, [
|
||||
{ id: "x", tag: "p", start: 40, duration: 1, track: 9 },
|
||||
]);
|
||||
expect(checked.some((markup) => /data-start="40"[^>]*data-track-index="10"/.test(markup))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -188,6 +188,55 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("writes a whole-number track on asset and file drops when a row's track is not a number", async () => {
|
||||
const title = rowClip("title", 0, 10);
|
||||
const textTrack = { ...title, authoredTrack: '0" onload="x' as unknown as number };
|
||||
const dropOnto = async (
|
||||
drop: (getDrop: ReturnType<typeof renderDropHook>) => Promise<unknown>,
|
||||
) => {
|
||||
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
|
||||
const uploadProjectFiles = vi.fn().mockResolvedValue(["one.png"]);
|
||||
const getDrop = renderDropHook(
|
||||
rowSource([title]),
|
||||
writeProjectFile,
|
||||
[textTrack],
|
||||
undefined,
|
||||
uploadProjectFiles,
|
||||
);
|
||||
await act(async () => {
|
||||
await drop(getDrop);
|
||||
});
|
||||
return writtenClip(writeProjectFile.mock.calls[0][1] as string, "img");
|
||||
};
|
||||
const placement = { start: 12, track: 0 };
|
||||
for (const img of [
|
||||
await dropOnto((getDrop) => getDrop()("pic.png", placement, 3)),
|
||||
await dropOnto((getDrop) => getDrop.file()([new File(["one"], "one.png")], placement)),
|
||||
]) {
|
||||
expect(img).toContain('data-track-index="0"');
|
||||
expect(img).not.toContain("onload");
|
||||
}
|
||||
});
|
||||
|
||||
it("writes a numeric start and duration on an asset drop when a row's timing is not a number", async () => {
|
||||
const title = rowClip("title", 0, 10);
|
||||
const rows = [
|
||||
{ ...title, start: '0" onload="x' as unknown as number },
|
||||
{ ...title, duration: '10" onclick="y' as unknown as number },
|
||||
{ ...title, duration: Number.POSITIVE_INFINITY },
|
||||
];
|
||||
for (const row of rows) {
|
||||
const writeProjectFile = vi.fn().mockResolvedValue(undefined);
|
||||
const getDrop = renderDropHook(rowSource([title]), writeProjectFile, [row]);
|
||||
await act(async () => {
|
||||
await getDrop()("pic.png", { start: 2, track: 0 }, 3);
|
||||
});
|
||||
const img = writtenClip(writeProjectFile.mock.calls[0][1] as string, "img");
|
||||
expect(img).toMatch(/ data-start="-?\d+(\.\d+)?" data-duration="3" /);
|
||||
expect(img).not.toMatch(/onload|onclick|Infinity|NaN/);
|
||||
}
|
||||
});
|
||||
|
||||
// Drops two files (3 s images by default) onto `clips`; returns each written clip's start and track.
|
||||
async function twoFileDrop(
|
||||
clips: TimelineElement[],
|
||||
|
||||
@@ -9,6 +9,7 @@ import { resolveDropTrack } from "../utils/timelineDropTrackInsert";
|
||||
import {
|
||||
buildTimelineAssetId,
|
||||
buildTimelineAssetInsertHtml,
|
||||
writtenTrackIndex,
|
||||
buildTimelineFileDropPlacements,
|
||||
fitTimelineAssetGeometry,
|
||||
getTimelineAssetKind,
|
||||
@@ -152,7 +153,7 @@ export function useTimelineAssetDropOps({
|
||||
duration: normalizedDuration,
|
||||
},
|
||||
});
|
||||
track = resolved.track;
|
||||
track = writtenTrackIndex(resolved.track);
|
||||
start = resolved.start;
|
||||
return extendRootDurationInSource(
|
||||
insertTimelineAssetIntoSource(
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { usePlayerStore } from "../store/playerStore";
|
||||
import { createTimelineElementFromManifestClip } from "../lib/timelineDOM";
|
||||
import type { ClipManifestClip } from "../lib/playbackTypes";
|
||||
import { createPreviewMessageHandler, type ClipManifestMessage } from "./previewMessageRouter";
|
||||
import { detachedFakeIframe, serveEditingRequests } from "./timelinePlayerTestHarness";
|
||||
|
||||
const closers: Array<() => void> = [];
|
||||
afterEach(() => {
|
||||
closers.splice(0).forEach((close) => close());
|
||||
usePlayerStore.getState().reset();
|
||||
});
|
||||
|
||||
const clip = (fields: Record<string, unknown>) => ({
|
||||
id: "good",
|
||||
label: "good",
|
||||
kind: "element",
|
||||
tagName: "div",
|
||||
start: 1,
|
||||
duration: 2,
|
||||
track: 3,
|
||||
...fields,
|
||||
});
|
||||
|
||||
const CLIPS = [
|
||||
clip({}),
|
||||
clip({ id: "text-track", track: '0" onload="x' }),
|
||||
clip({ id: "fraction-track", track: 1.5 }),
|
||||
clip({ id: "nan-start", start: Number.NaN }),
|
||||
clip({ id: "endless", duration: Number.POSITIVE_INFINITY }),
|
||||
clip({ id: "text-start", start: "1" }),
|
||||
clip({ id: "text-rate", playbackRate: "2" }),
|
||||
clip({ id: "endless-media-start", playbackStart: Number.POSITIVE_INFINITY }),
|
||||
];
|
||||
|
||||
/** Turns the clip list into store rows the way Studio's timeline sync does. */
|
||||
function storeClips(message: ClipManifestMessage): void {
|
||||
const rows = message.clips.map((item: ClipManifestClip, fallbackIndex) =>
|
||||
createTimelineElementFromManifestClip({ clip: item, fallbackIndex }),
|
||||
);
|
||||
usePlayerStore.getState().setElements(rows);
|
||||
}
|
||||
|
||||
function expectOnlyNumericRows(): void {
|
||||
const rows = usePlayerStore.getState().elements;
|
||||
expect(rows.map((row) => row.id)).toEqual(["good"]);
|
||||
for (const row of rows) {
|
||||
for (const value of [row.start, row.duration, row.track, row.authoredTrack]) {
|
||||
expect(typeof value).toBe("number");
|
||||
expect(Number.isFinite(value)).toBe(true);
|
||||
}
|
||||
expect(Number.isInteger(row.track)).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
function handlerFor(frame: Record<string, unknown>, iframe: HTMLIFrameElement) {
|
||||
const handle = createPreviewMessageHandler({
|
||||
iframeRef: { current: iframe },
|
||||
processTimelineMessageRef: { current: storeClips },
|
||||
enrichMissingCompositionsRef: { current: vi.fn() },
|
||||
lastTimelineMessageRef: { current: Date.now() },
|
||||
getAdapter: () => null,
|
||||
syncTimelineElements: vi.fn(),
|
||||
});
|
||||
return (data: unknown) =>
|
||||
handle(
|
||||
new MessageEvent("message", {
|
||||
source: frame as unknown as Window,
|
||||
origin: window.location.origin,
|
||||
data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
describe("clip fields a preview frame sends", () => {
|
||||
it("keeps only clips with numeric timing and a whole-number track from a timeline message", () => {
|
||||
const frame: Record<string, unknown> = {};
|
||||
const post = handlerFor(frame, detachedFakeIframe(frame));
|
||||
post({ source: "hf-preview", type: "timeline", clips: CLIPS, durationInFrames: 300 });
|
||||
expectOnlyNumericRows();
|
||||
});
|
||||
|
||||
it("keeps only clips with numeric timing and a whole-number track from a sealed frame's snapshot", async () => {
|
||||
const frame: Record<string, unknown> = {};
|
||||
const iframe = detachedFakeIframe(frame);
|
||||
Object.defineProperty(iframe, "contentDocument", { value: null });
|
||||
Object.defineProperty(frame, "document", {
|
||||
get: () => {
|
||||
throw new DOMException("blocked", "SecurityError");
|
||||
},
|
||||
});
|
||||
const clipManifest = { clips: CLIPS, durationInFrames: 300, scenes: [] };
|
||||
closers.push(serveEditingRequests(frame, () => ({ clipManifest })));
|
||||
const post = handlerFor(frame, iframe);
|
||||
post({ source: "hf-preview", type: "state", isPlaying: false });
|
||||
await vi.waitFor(() => expect(usePlayerStore.getState().elements).toHaveLength(1));
|
||||
expectOnlyNumericRows();
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,11 @@ afterEach(() => {
|
||||
usePlayerStore.getState().reset();
|
||||
});
|
||||
|
||||
const PORT_MANIFEST = { clips: [{ id: "a" }], durationInFrames: 60, scenes: [] };
|
||||
const PORT_MANIFEST = {
|
||||
clips: [{ id: "a", start: 0, duration: 2, track: 0 }],
|
||||
durationInFrames: 60,
|
||||
scenes: [],
|
||||
};
|
||||
const GLOBAL_MANIFEST = { clips: [{ id: "x" }], durationInFrames: 30, scenes: [] };
|
||||
|
||||
/** A frame whose globals and editing port carry different manifests, so a test sees which was read. */
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from "../store/previewQualitySlice";
|
||||
import { parseTimelineFromDOM } from "../lib/timelineDOM";
|
||||
import { previewClipManifest, previewFrameOpaque } from "../lib/previewChannel";
|
||||
import { wellFormedClips } from "../lib/manifestClips";
|
||||
import { frameOrigins } from "../lib/bridgePlayback";
|
||||
|
||||
/** What `processTimelineMessage` accepts — the clip-manifest postMessage. */
|
||||
@@ -220,7 +221,8 @@ export function createPreviewMessageHandler(
|
||||
return;
|
||||
}
|
||||
if (data.type === "timeline" && Array.isArray(data.clips)) {
|
||||
handleTimelineMessage(deps, iframe, data as unknown as ClipManifestMessage, enriched);
|
||||
const message = { ...data, clips: wellFormedClips(data.clips) };
|
||||
handleTimelineMessage(deps, iframe, message as unknown as ClipManifestMessage, enriched);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ClipManifestClip } from "./playbackTypes";
|
||||
|
||||
const OPTIONAL_NUMBERS = ["zIndex", "playbackStart", "playbackRate"] as const;
|
||||
|
||||
const finiteNumber = (value: unknown): boolean =>
|
||||
typeof value === "number" && Number.isFinite(value);
|
||||
|
||||
function wellFormedClip(clip: unknown): clip is ClipManifestClip {
|
||||
if (typeof clip !== "object" || clip === null) return false;
|
||||
const fields = clip as Record<string, unknown>;
|
||||
if (!finiteNumber(fields.start) || !finiteNumber(fields.duration)) return false;
|
||||
if (!Number.isInteger(fields.track)) return false;
|
||||
return OPTIONAL_NUMBERS.every((name) => fields[name] == null || finiteNumber(fields[name]));
|
||||
}
|
||||
|
||||
/** A preview frame's clip list, keeping only clips whose timing and track are numbers. */
|
||||
export function wellFormedClips(clips: readonly unknown[]): ClipManifestClip[] {
|
||||
return clips.filter(wellFormedClip);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type EditingResult,
|
||||
} from "@hyperframes/core/runtime/editing-port";
|
||||
import type { ClipManifest, IframeWindow } from "./playbackTypes";
|
||||
import { wellFormedClips } from "./manifestClips";
|
||||
|
||||
const clients = new WeakMap<HTMLIFrameElement, { client: EditingPortClient; retire: () => void }>();
|
||||
const loopStarts = new WeakMap<EditingPortClient, number | null>();
|
||||
@@ -128,7 +129,7 @@ export async function previewClipManifest(iframe: HTMLIFrameElement): Promise<Cl
|
||||
const { clips, durationInFrames } = manifest as Partial<ClipManifest>;
|
||||
if (!Array.isArray(clips) || typeof durationInFrames !== "number") return null;
|
||||
if (!Number.isFinite(durationInFrames)) return null;
|
||||
return manifest as ClipManifest;
|
||||
return { ...(manifest as ClipManifest), clips: wellFormedClips(clips) };
|
||||
}
|
||||
|
||||
export async function previewClipParents(iframe: HTMLIFrameElement): Promise<Map<string, string>> {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { encodeUrlPath } from "@hyperframes/parsers";
|
||||
export { buildTimelineAssetId } from "@hyperframes/core/timeline-asset-id";
|
||||
import { AUDIO_EXT, IMAGE_EXT, VIDEO_EXT } from "./mediaTypes";
|
||||
import { roundToCenti } from "./rounding";
|
||||
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
|
||||
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns";
|
||||
import { patchRootCompositionDuration, readRootCompositionDuration } from "./rootDuration";
|
||||
|
||||
@@ -93,6 +94,13 @@ export function fitTimelineAssetGeometry(
|
||||
};
|
||||
}
|
||||
|
||||
const finiteOrZero = (value: unknown): number =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
|
||||
export function writtenTrackIndex(track: unknown): number {
|
||||
return Math.trunc(finiteOrZero(track));
|
||||
}
|
||||
|
||||
export function buildTimelineAssetInsertHtml(input: {
|
||||
id: string;
|
||||
hfId: string;
|
||||
@@ -106,7 +114,7 @@ export function buildTimelineAssetInsertHtml(input: {
|
||||
/** Video only: true inserts `data-has-audio="true"` with no `muted`. Unknown or false stays muted. */
|
||||
hasAudio?: boolean;
|
||||
}): string {
|
||||
const sharedAttrs = `id="${input.id}" data-hf-id="${input.hfId}" class="clip" src="${encodeUrlPath(input.assetPath)}" data-start="${input.start}" data-duration="${input.duration}" data-track-index="${input.track}"`;
|
||||
const sharedAttrs = `id="${input.id}" data-hf-id="${input.hfId}" class="clip" src="${encodeUrlPath(input.assetPath)}" data-start="${formatTimelineAttributeNumber(finiteOrZero(input.start))}" data-duration="${formatTimelineAttributeNumber(finiteOrZero(input.duration))}" data-track-index="${writtenTrackIndex(input.track)}"`;
|
||||
const geometry = input.geometry ?? { left: 0, top: 0, width: 640, height: 360 };
|
||||
const visualStyles = `position: absolute; left: ${geometry.left}px; top: ${geometry.top}px; width: ${geometry.width}px; height: ${geometry.height}px; object-fit: contain; z-index: ${input.zIndex}`;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user