mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(studio): apply-to-scope writes only the grading attribute, exactly as given (#8767)
* fix(studio): apply-to-scope writes only the grading attribute, exactly as given patchMediaTag passed the new attribute to String.prototype.replace as a replacement string, so `$&`, `$'` and similar in a grading value were expanded from the old tag and could split the attribute. Its match also needed a quoted value, so an unquoted or valueless attribute was duplicated instead of replaced. It now walks the tag's attributes the way the browser reads them and slices out the data-color-grading spans: the first gets the new value, any later duplicate is removed. When a grading is copied to other media, an unknown preset id, an unknown color space, or a LUT source with a scheme other than http, https or data is dropped instead of being written into other files. Variable references stay. * fix(studio): apply-to-scope keeps a known bare preset id The attribute's short form is a preset id alone, which core reads as a preset. It is now kept when it is a known id or a variable reference instead of being refused as unreadable. The quick-save concurrency test applied the filler preset warm, which is not a preset; it applies warm-daylight now. * fix(studio): grading attribute scan splits on HTML whitespace, appends after the last attribute The scan used JavaScript's \s, which also splits on a no-break space that HTML keeps inside an unquoted value, so clearing a grade could cut the source. It now separates on HTML whitespace only. A new attribute goes after the last attribute the scan read, so the slash that ends an unquoted value such as src=images/ stays part of it.
This commit is contained in:
@@ -646,6 +646,10 @@ const PRESETS_BY_ID = new Map<string, HfColorGradingPreset>(
|
||||
|
||||
const VARIABLE_REF_RE = /^\$(?:\{([A-Za-z0-9_.:-]+)\}|([A-Za-z0-9_.:-]+))$/;
|
||||
|
||||
export function isHfColorGradingVariableRef(value: unknown): boolean {
|
||||
return typeof value === "string" && VARIABLE_REF_RE.test(value.trim());
|
||||
}
|
||||
|
||||
const ADJUST_LIMITS: Record<HfColorGradingAdjustKey, { min: number; max: number }> = {
|
||||
exposure: { min: -2, max: 2 },
|
||||
contrast: { min: -1, max: 1 },
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { patchMediaColorGradingInHtml } from "./colorGradingScopePatch";
|
||||
import {
|
||||
keepKnownColorGradingValues,
|
||||
patchMediaColorGradingInHtml,
|
||||
} from "./colorGradingScopePatch";
|
||||
|
||||
describe("patchMediaColorGradingInHtml", () => {
|
||||
it.each(['"', "'"])("replaces and removes long grading values quoted with %s", (quote) => {
|
||||
@@ -92,3 +96,176 @@ describe("patchMediaColorGradingInHtml", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function readTag(html: string): { names: string[]; grading: string | null } {
|
||||
const element = new DOMParser().parseFromString(html, "text/html").querySelector("video");
|
||||
if (!element) throw new Error(`no video in ${html}`);
|
||||
return {
|
||||
names: element.getAttributeNames(),
|
||||
grading: element.getAttribute("data-color-grading"),
|
||||
};
|
||||
}
|
||||
|
||||
describe("patchMediaColorGradingInHtml with replacement patterns in the value", () => {
|
||||
const patterns = [
|
||||
"$&",
|
||||
"$'",
|
||||
"$`",
|
||||
"$1",
|
||||
"$$",
|
||||
"$<x>",
|
||||
"' data-extra='x' a='",
|
||||
'" data-extra="x" a="',
|
||||
];
|
||||
it.each(['"', "'"])("writes the value as given into a tag quoted with %s", (quote) => {
|
||||
const old = quote === '"' ? "{"preset":"old"}" : '{"preset":"old"}';
|
||||
const before = `<video id="v" data-color-grading=${quote}${old}${quote} muted></video>`;
|
||||
for (const pattern of patterns) {
|
||||
const value = JSON.stringify({ preset: `a${pattern}b`, lut: { src: `${pattern}.cube` } });
|
||||
const { html, count } = patchMediaColorGradingInHtml(before, value);
|
||||
expect(count).toBe(1);
|
||||
expect(readTag(html)).toEqual({
|
||||
names: ["id", "data-color-grading", "muted"],
|
||||
grading: value,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("patchMediaColorGradingInHtml with other ways to write the attribute", () => {
|
||||
it.each([
|
||||
["unquoted", "data-color-grading=clean-studio"],
|
||||
["with no value", "data-color-grading"],
|
||||
["with spaces around =", "data-color-grading = 'x'"],
|
||||
])("replaces an attribute written %s", (_, attribute) => {
|
||||
const before = `<video ${attribute} src="a.mp4"></video>`;
|
||||
const value = '{"preset":"mono-clean"}';
|
||||
expect(readTag(patchMediaColorGradingInHtml(before, value).html)).toEqual({
|
||||
names: ["data-color-grading", "src"],
|
||||
grading: value,
|
||||
});
|
||||
expect(patchMediaColorGradingInHtml(before, null).html).toBe(`<video src="a.mp4"></video>`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"its own unquoted value holding =",
|
||||
`<video data-color-grading=a=b src="c">`,
|
||||
["data-color-grading", "src"],
|
||||
],
|
||||
[
|
||||
"its own unquoted value holding <",
|
||||
`<video data-color-grading=a<b src="c">`,
|
||||
["data-color-grading", "src"],
|
||||
],
|
||||
[
|
||||
"no space after its quoted value",
|
||||
`<video data-color-grading="a"src="c">`,
|
||||
["data-color-grading", "src"],
|
||||
],
|
||||
])("finds the attribute past %s", (_, before, names) => {
|
||||
const value = '{"preset":"mono-clean"}';
|
||||
expect(readTag(patchMediaColorGradingInHtml(before, value).html)).toEqual({
|
||||
names,
|
||||
grading: value,
|
||||
});
|
||||
const cleared = readTag(patchMediaColorGradingInHtml(before, null).html);
|
||||
expect(cleared).toEqual({
|
||||
names: names.filter((name) => name !== "data-color-grading"),
|
||||
grading: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("finds the attribute past an unquoted value holding =", () => {
|
||||
const before = `<video src=clip.mp4?t=1 data-color-grading="old">`;
|
||||
expect(patchMediaColorGradingInHtml(before, '{"preset":"mono-clean"}').html).toBe(
|
||||
`<video src=clip.mp4?t=1 data-color-grading="{"preset":"mono-clean"}">`,
|
||||
);
|
||||
expect(patchMediaColorGradingInHtml(before, null).html).toBe(`<video src=clip.mp4?t=1>`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"a no-break space, which HTML does not treat as a separator",
|
||||
"<img src=x\u00a0data-color-grading>",
|
||||
],
|
||||
["a slash that ends an unquoted value", "<img src=images/>"],
|
||||
["a self-closing slash after a quoted value", '<img src="a.png" />'],
|
||||
])("keeps the source whole past %s", (_, before) => {
|
||||
const lastValueEnd =
|
||||
before.lastIndexOf(" />") === -1 ? before.length - 1 : before.lastIndexOf(" />");
|
||||
const written = ' data-color-grading="{"preset":"mono-clean"}"';
|
||||
expect(patchMediaColorGradingInHtml(before, '{"preset":"mono-clean"}').html).toBe(
|
||||
before.slice(0, lastValueEnd) + written + before.slice(lastValueEnd),
|
||||
);
|
||||
expect(patchMediaColorGradingInHtml(before, null).html).toBe(before);
|
||||
});
|
||||
|
||||
it("writes the first of two grading attributes and removes the second", () => {
|
||||
const before = `<video data-color-grading="a" src="c" data-color-grading="b">`;
|
||||
const value = '{"preset":"mono-clean"}';
|
||||
expect(readTag(patchMediaColorGradingInHtml(before, value).html)).toEqual({
|
||||
names: ["data-color-grading", "src"],
|
||||
grading: value,
|
||||
});
|
||||
expect(patchMediaColorGradingInHtml(before, null).html).toBe(`<video src="c">`);
|
||||
});
|
||||
|
||||
it("leaves the attribute's name alone where it is only text inside another attribute", () => {
|
||||
const before = `<video title="no data-color-grading here" data-color-grading='x'></video>`;
|
||||
const value = '{"preset":"mono-clean"}';
|
||||
expect(readTag(patchMediaColorGradingInHtml(before, value).html)).toEqual({
|
||||
names: ["title", "data-color-grading"],
|
||||
grading: value,
|
||||
});
|
||||
expect(patchMediaColorGradingInHtml(before, null).html).toBe(
|
||||
`<video title="no data-color-grading here"></video>`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("keepKnownColorGradingValues", () => {
|
||||
const kept = (grading: Record<string, unknown>) =>
|
||||
JSON.parse(keepKnownColorGradingValues(JSON.stringify(grading)) ?? "null");
|
||||
|
||||
it("keeps known presets, variable references, the known color space and loadable LUTs", () => {
|
||||
for (const grading of [
|
||||
{
|
||||
preset: "clean-studio",
|
||||
colorSpace: "rec709",
|
||||
lut: { src: "luts/film.cube", intensity: 1 },
|
||||
},
|
||||
{ preset: null, lut: { src: "https://cdn.example.com/film.cube", intensity: 0.5 } },
|
||||
{ preset: "$look", lut: { src: "data:text/plain;base64,AA==", intensity: 1 } },
|
||||
{ preset: "${look}", lut: { src: "/luts/film.cube", intensity: 1 } },
|
||||
{ adjust: { exposure: 0.2 }, lut: null },
|
||||
]) {
|
||||
expect(kept(grading)).toEqual(grading);
|
||||
}
|
||||
});
|
||||
|
||||
it("drops an unknown preset, an unknown color space and a LUT the player cannot load", () => {
|
||||
expect(
|
||||
kept({
|
||||
preset: 'x" data-extra="1',
|
||||
colorSpace: 'srgb" a="',
|
||||
lut: { src: "ftp://example.com/film.cube", intensity: 1 },
|
||||
adjust: { exposure: 0.2 },
|
||||
}),
|
||||
).toEqual({ adjust: { exposure: 0.2 } });
|
||||
expect(kept({ lut: { src: "file:///luts/film.cube", intensity: 1 } })).toEqual({});
|
||||
expect(kept({ lut: "luts/film.cube" })).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps a bare preset id only when it is known or a variable reference", () => {
|
||||
expect(keepKnownColorGradingValues(" clean-studio ")).toBe("clean-studio");
|
||||
expect(keepKnownColorGradingValues("$look")).toBe("$look");
|
||||
expect(keepKnownColorGradingValues("made-up-look")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads nothing but a preset id or a serialized grading object", () => {
|
||||
for (const value of ["[]", "null", "{"]) {
|
||||
expect(keepKnownColorGradingValues(value)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import {
|
||||
HF_COLOR_GRADING_COLOR_SPACE,
|
||||
HF_COLOR_GRADING_PRESETS,
|
||||
isHfColorGradingVariableRef,
|
||||
} from "@hyperframes/core/color-grading";
|
||||
|
||||
const MEDIA_TAG_RE = /<\s*(video|img)\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
|
||||
const COLOR_GRADING_ATTR_RE = /\sdata-color-grading=(?:"[^"]*"|'[^']*')/i;
|
||||
const TAG_NAME_RE = /^<\s*\w+/;
|
||||
const HTML_SPACE = "\\t\\n\\f\\r ";
|
||||
const NEXT_ATTRIBUTE_RE = new RegExp(
|
||||
`[${HTML_SPACE}/]*([^${HTML_SPACE}/>][^${HTML_SPACE}/>=]*)` +
|
||||
`(?:[${HTML_SPACE}]*=[${HTML_SPACE}]*(?:"[^"]*"|'[^']*'|[^${HTML_SPACE}>]+))?`,
|
||||
"y",
|
||||
);
|
||||
const SEPARATES_ATTRIBUTES = new RegExp(`[${HTML_SPACE}/>]`);
|
||||
const IGNORED_HTML_RANGE_RE = /<!--[\s\S]*?-->|<(script|style)\b[\s\S]*?<\/\1\s*>/gi;
|
||||
|
||||
interface TextRange {
|
||||
@@ -29,16 +42,39 @@ function escapeHtmlAttribute(value: string): string {
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function patchMediaTag(tag: string, value: string | null): string {
|
||||
if (value === null || value === "") {
|
||||
return tag.replace(COLOR_GRADING_ATTR_RE, "");
|
||||
function readAttributes(tag: string): { gradingSpans: TextRange[]; end: number } {
|
||||
const gradingSpans: TextRange[] = [];
|
||||
let end = TAG_NAME_RE.exec(tag)?.[0].length ?? 0;
|
||||
NEXT_ATTRIBUTE_RE.lastIndex = end;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = NEXT_ATTRIBUTE_RE.exec(tag)) !== null && match[0] !== "") {
|
||||
end = match.index + match[0].length;
|
||||
if (match[1]?.toLowerCase() === "data-color-grading") {
|
||||
gradingSpans.push({ start: match.index, end });
|
||||
}
|
||||
}
|
||||
return { gradingSpans, end };
|
||||
}
|
||||
|
||||
const nextAttr = ` data-color-grading="${escapeHtmlAttribute(value)}"`;
|
||||
if (COLOR_GRADING_ATTR_RE.test(tag)) {
|
||||
return tag.replace(COLOR_GRADING_ATTR_RE, nextAttr);
|
||||
const keepsNextAttributeApart = (tag: string, end: number): string =>
|
||||
end < tag.length && !SEPARATES_ATTRIBUTES.test(tag.charAt(end)) ? " " : "";
|
||||
|
||||
function patchMediaTag(tag: string, value: string | null): string {
|
||||
const nextAttr = value ? ` data-color-grading="${escapeHtmlAttribute(value)}"` : "";
|
||||
const { gradingSpans, end } = readAttributes(tag);
|
||||
if (gradingSpans.length === 0) {
|
||||
return nextAttr ? tag.slice(0, end) + nextAttr + tag.slice(end) : tag;
|
||||
}
|
||||
return tag.replace(/\s*\/?>$/, (end) => `${nextAttr}${end}`);
|
||||
let patched = tag;
|
||||
for (const [index, span] of [...gradingSpans.entries()].reverse()) {
|
||||
const written = index === 0 ? nextAttr : "";
|
||||
patched =
|
||||
patched.slice(0, span.start) +
|
||||
written +
|
||||
keepsNextAttributeApart(patched, span.end) +
|
||||
patched.slice(span.end);
|
||||
}
|
||||
return patched;
|
||||
}
|
||||
|
||||
export function patchMediaColorGradingInHtml(
|
||||
@@ -55,3 +91,41 @@ export function patchMediaColorGradingInHtml(
|
||||
});
|
||||
return { html: patched, count };
|
||||
}
|
||||
|
||||
const KNOWN_PRESETS = new Set<string>(HF_COLOR_GRADING_PRESETS.map((preset) => preset.id));
|
||||
const LUT_SCHEME = /^([a-z][a-z0-9+.-]*):/i;
|
||||
const LOADABLE_LUT_SCHEMES = new Set(["data", "http", "https"]);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isKnownPreset(value: unknown): boolean {
|
||||
return value === null || isHfColorGradingVariableRef(value) || KNOWN_PRESETS.has(value as string);
|
||||
}
|
||||
|
||||
function isLoadableLut(value: unknown): boolean {
|
||||
if (value === null || isHfColorGradingVariableRef(value)) return true;
|
||||
if (!isRecord(value) || typeof value.src !== "string") return false;
|
||||
if (isHfColorGradingVariableRef(value.src)) return true;
|
||||
const scheme = LUT_SCHEME.exec(value.src.trim())?.[1]?.toLowerCase();
|
||||
return scheme === undefined || LOADABLE_LUT_SCHEMES.has(scheme);
|
||||
}
|
||||
|
||||
export function keepKnownColorGradingValues(value: string): string | null {
|
||||
const presetOnly = value.trim();
|
||||
if (!presetOnly.startsWith("{")) return isKnownPreset(presetOnly) ? presetOnly : null;
|
||||
let grading: unknown;
|
||||
try {
|
||||
grading = JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!isRecord(grading)) return null;
|
||||
const kept = { ...grading };
|
||||
if ("preset" in kept && !isKnownPreset(kept.preset)) delete kept.preset;
|
||||
if ("colorSpace" in kept && kept.colorSpace !== HF_COLOR_GRADING_COLOR_SPACE)
|
||||
delete kept.colorSpace;
|
||||
if ("lut" in kept && !isLoadableLut(kept.lut)) delete kept.lut;
|
||||
return JSON.stringify(kept);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { applyColorGradingScopeUpdate } from "./studioColorGradingScope";
|
||||
|
||||
function project(files: Record<string, string>) {
|
||||
const showToast = vi.fn();
|
||||
return {
|
||||
files,
|
||||
showToast,
|
||||
options: {
|
||||
selectedSourceFile: "index.html",
|
||||
compositionPaths: Object.keys(files),
|
||||
projectId: "p",
|
||||
waitForPendingDomEditSaves: async () => {},
|
||||
readProjectFile: async (path: string) => files[path] ?? "",
|
||||
writeProjectFile: async (path: string, content: string) => {
|
||||
files[path] = content;
|
||||
},
|
||||
recordEdit: async () => {},
|
||||
reloadPreview: () => {},
|
||||
showToast,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("applyColorGradingScopeUpdate", () => {
|
||||
it("copies a grading to every composition without its unknown preset or color space", async () => {
|
||||
const { files, options } = project({
|
||||
"index.html": `<video src="a.mp4"></video>`,
|
||||
"compositions/b.html": `<img src="b.png" data-color-grading='{"preset":"clean-studio"}'>`,
|
||||
});
|
||||
const value = JSON.stringify({
|
||||
preset: "made-up$'look",
|
||||
colorSpace: "made-up-space",
|
||||
adjust: { exposure: 0.2 },
|
||||
});
|
||||
const result = await applyColorGradingScopeUpdate({ ...options, scope: "project", value });
|
||||
expect(result).toEqual({ changedFiles: 2, changedElements: 2 });
|
||||
const written = JSON.stringify({ adjust: { exposure: 0.2 } }).replace(/"/g, """);
|
||||
expect(files["index.html"]).toBe(`<video src="a.mp4" data-color-grading="${written}"></video>`);
|
||||
expect(files["compositions/b.html"]).toBe(`<img src="b.png" data-color-grading="${written}">`);
|
||||
expect(Object.values(files).join("")).not.toContain("made-up");
|
||||
});
|
||||
|
||||
it("writes nothing when the value is not a serialized grading", async () => {
|
||||
const before = `<video src="a.mp4"></video>`;
|
||||
const { files, options, showToast } = project({ "index.html": before });
|
||||
await applyColorGradingScopeUpdate({ ...options, scope: "project", value: "not json" });
|
||||
expect(files["index.html"]).toBe(before);
|
||||
expect(showToast).toHaveBeenCalledWith(expect.stringContaining("could not be read"), "error");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
|
||||
import { patchMediaColorGradingInHtml } from "./editor/colorGradingScopePatch";
|
||||
import {
|
||||
keepKnownColorGradingValues,
|
||||
patchMediaColorGradingInHtml,
|
||||
} from "./editor/colorGradingScopePatch";
|
||||
import { hasRelativeLutSource } from "./studioMediaJobs";
|
||||
|
||||
export type ColorGradingScope = "source-file" | "project";
|
||||
@@ -55,7 +58,12 @@ export async function applyColorGradingScopeUpdate({
|
||||
showToast,
|
||||
}: ApplyColorGradingScopeOptions): Promise<ColorGradingScopeResult> {
|
||||
await waitForPendingDomEditSaves();
|
||||
if (scope === "project" && hasRelativeLutSource(value)) {
|
||||
const copied = value ? keepKnownColorGradingValues(value) : null;
|
||||
if (value && copied === null) {
|
||||
showToast("That color grading could not be read, so nothing was applied.", "error");
|
||||
return EMPTY_COLOR_GRADING_SCOPE_RESULT;
|
||||
}
|
||||
if (scope === "project" && hasRelativeLutSource(copied)) {
|
||||
showToast(
|
||||
"Project-wide color grading cannot copy relative LUT paths. Apply to this file or use a URL/data LUT.",
|
||||
"error",
|
||||
@@ -65,14 +73,14 @@ export async function applyColorGradingScopeUpdate({
|
||||
|
||||
let changedElements = 0;
|
||||
const patchGrading = (before: string) => {
|
||||
const result = patchMediaColorGradingInHtml(before, value);
|
||||
const result = patchMediaColorGradingInHtml(before, copied);
|
||||
changedElements += result.count;
|
||||
return result.html;
|
||||
};
|
||||
const paths = colorGradingScopePaths(scope, selectedSourceFile, compositionPaths);
|
||||
const changedPaths = await saveProjectFilesWithHistory({
|
||||
projectId,
|
||||
label: value ? "Apply color grading" : "Clear color grading",
|
||||
label: copied ? "Apply color grading" : "Clear color grading",
|
||||
files: Object.fromEntries(paths.map((path) => [path, patchGrading])),
|
||||
readFile: readProjectFile,
|
||||
writeFile: writeProjectFile,
|
||||
@@ -84,7 +92,7 @@ export async function applyColorGradingScopeUpdate({
|
||||
}
|
||||
reloadPreview();
|
||||
showToast(
|
||||
`${value ? "Applied" : "Cleared"} color grading on ${changedElements} media item${changedElements === 1 ? "" : "s"}`,
|
||||
`${copied ? "Applied" : "Cleared"} color grading on ${changedElements} media item${changedElements === 1 ? "" : "s"}`,
|
||||
"info",
|
||||
);
|
||||
return { changedFiles: changedPaths.length, changedElements };
|
||||
|
||||
@@ -155,7 +155,7 @@ describe("two quick timeline saves on one file", () => {
|
||||
const grade = () =>
|
||||
applyColorGradingScopeUpdate({
|
||||
scope: "source-file",
|
||||
value: "warm",
|
||||
value: "warm-daylight",
|
||||
selectedSourceFile: "index.html",
|
||||
fileTree: ["index.html"],
|
||||
projectId: "p1",
|
||||
@@ -169,7 +169,7 @@ describe("two quick timeline saves on one file", () => {
|
||||
await expectBothLand(project, () => move(project, "a", 3), grade);
|
||||
|
||||
expect(project.read()).toContain('id="a" class="clip" data-start="3"');
|
||||
expect(project.read()).toContain('data-color-grading="warm"');
|
||||
expect(project.read()).toContain('data-color-grading="warm-daylight"');
|
||||
});
|
||||
|
||||
it("lands a move started while the previous move's GSAP rewrite is in flight", async () => {
|
||||
|
||||
Reference in New Issue
Block a user