Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): fail the suite on a class that resolves to nothing (#3623)
Miguel Ángel93ff9a994d5f
diff --git a/packages/studio/src/components/editor/PreviewGuides.tsx b/packages/studio/src/components/editor/PreviewGuides.tsxindex 5a58e5876c..91f38ca7ab 100644--- a/packages/studio/src/components/editor/PreviewGuides.tsx+++ b/packages/studio/src/components/editor/PreviewGuides.tsx@@ -8,7 +8,7 @@ interface PreviewGuidesProps {}const TICKS = Array.from({ length: 11 }, (_, i) => i * 10);-const INK = "rgba(255,255,255,0.7)";+const INK = "color-mix(in srgb, white 70%, transparent)";/** Ruler and safe-margin boxes drawn over the preview pane, never inside the composition. */export const PreviewGuides = memo(function PreviewGuides({ iframeRef }: PreviewGuidesProps) {diff --git a/packages/studio/src/player/components/AutomationSelectionMenu.tsx b/packages/studio/src/player/components/AutomationSelectionMenu.tsxindex c8375bb768..f55cd2fb9e 100644--- a/packages/studio/src/player/components/AutomationSelectionMenu.tsx+++ b/packages/studio/src/player/components/AutomationSelectionMenu.tsx@@ -29,7 +29,7 @@ export const AutomationSelectionMenu = memo(function AutomationSelectionMenu({}: AutomationSelectionMenuProps) {const menuRef = useContextMenuDismiss(onClose);const row =- "block w-full px-2 py-1 text-left text-[11px] text-panel-text-1 hover:bg-panel-bg-3 disabled:opacity-40";+ "block w-full px-2 py-1 text-left text-[11px] text-panel-text-1 hover:bg-panel-hover disabled:opacity-40";// Same edge-clamping precedent as TrackGapContextMenu: without it a// right-click near the bottom/right of the timeline renders this menu// partially off-screen.diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsxindex 1debf1c4f7..0a83043818 100644--- a/packages/studio/src/player/components/TimelineCanvas.tsx+++ b/packages/studio/src/player/components/TimelineCanvas.tsx@@ -179,8 +179,8 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvasleft: props.contentOrigin + draggedClip.previewStart * props.pps,width: Math.max(draggedClip.element.duration * props.pps, 4),height: draggedClipHeight,- border: "1px solid rgba(60,230,172,0.55)",- background: "rgba(60,230,172,0.12)",+ border: "1px solid color-mix(in srgb, var(--color-accent) 55%, transparent)",+ background: "color-mix(in srgb, var(--color-accent) 12%, transparent)",borderRadius: 4,zIndex: 30,}}@@ -199,8 +199,8 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvasleft: props.contentOrigin + props.dropPreview.start * props.pps,width: DROP_PREVIEW_SECONDS * props.pps,height: TRACK_H - CLIP_Y * 2,- border: "1px solid rgba(60,230,172,0.55)",- background: "rgba(60,230,172,0.12)",+ border: "1px solid color-mix(in srgb, var(--color-accent) 55%, transparent)",+ background: "color-mix(in srgb, var(--color-accent) 12%, transparent)",borderRadius: 4,zIndex: 30,}}diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsxindex b8279c3823..696746aff1 100644--- a/packages/studio/src/player/components/TimelineClip.tsx+++ b/packages/studio/src/player/components/TimelineClip.tsx@@ -71,7 +71,6 @@ export const TimelineClip = memo(function TimelineClip({isSelected ? "is-selected" : "",isHovered ? "is-hovered" : "",isDragging ? "is-dragging" : "",- showDefaultText ? "" : "is-micro",isAudioTimelineElement(el) ? "is-audio" : "",].filter((className) => className.length > 0)diff --git a/packages/studio/src/styles/classCandidates.test.ts b/packages/studio/src/styles/classCandidates.test.tsnew file mode 100644index 0000000000..d120c23546--- /dev/null+++ b/packages/studio/src/styles/classCandidates.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";+import { extractClassCandidates } from "./classCandidates";++function bases(source: string): string[] {+ return extractClassCandidates(source)+ .map((candidate) => candidate.base)+ .sort();+}++describe("extractClassCandidates", () => {+ it("reads a plain className attribute", () => {+ expect(bases(`<div className="text-center border-dashed" />`)).toEqual([+ "border-dashed",+ "text-center",+ ]);+ });++ it("reads every string a class-building call is given", () => {+ const source = `<div className={cn("flex", open && "bg-surface", { "text-accent": on })} />`;++ expect(bases(source)).toEqual(["bg-surface", "flex", "text-accent"]);+ });++ it("reads a class map that never touches a className literal", () => {+ // The shape Studio's primitives use: the utility only reaches markup+ // through a lookup, so an attribute-only reader would miss it entirely.+ const source = `const sizeStyles: Record<ButtonSize, string> = {+ sm: "h-7 px-2.5 rounded-button",+ };`;++ expect(bases(source)).toEqual(["h-7", "px-2.5", "rounded-button"]);+ });++ it("reads a class map whose name says nothing about classes", () => {+ // The defect this replaced: candidate-ness was decided by the binding's+ // name, so the same classes were gated in `sizeStyles` and invisible in+ // `buttonSizes`. What makes them classes is where they are used.+ const source = `const fooSizes = { md: "h-ctl rounded-hologram" };+ const Foo = ({ size }) => <span className={cn(fooSizes[size])} />;`;++ expect(bases(source)).toEqual(["h-ctl", "rounded-hologram"]);+ });++ it("follows an identifier that contains a dollar sign", () => {+ const source = `const $cls = "flex-none";\nconst a = <div className={$cls} />;`;++ expect(bases(source)).toEqual(["flex-none"]);+ });++ it("does not read a lookup key's default value as a class", () => {+ // `variant` is the key, not the class list, so the default it falls back+ // to is a map entry name and never reaches markup.+ const source = `const map = { ghost: "bg-transparent" };+ const Foo = ({ variant = "ghost" }) => <span className={map[variant]} />;`;++ expect(bases(source)).toEqual(["bg-transparent"]);+ });++ it("leaves a lookup table alone when nothing uses it as a class", () => {+ const source = `const labels = { md: "Medium size" };+ const Foo = () => <span title={labels.md} />;`;++ expect(bases(source)).toEqual([]);+ });++ it("drops the template chunk that touches an interpolation", () => {+ expect(bases("<div className={`w-${i} flex`} />")).toEqual(["flex"]);+ });++ it("keeps a chunk that whitespace separates from the interpolation", () => {+ expect(bases("<div className={`${base} flex `} />")).toEqual(["flex"]);+ });++ it("strips variant prefixes, including bracketed ones", () => {+ const source = `<div className="hover:bg-surface/50 md:group-data-[open]:text-accent" />`;++ expect(bases(source)).toEqual(["bg-surface/50", "text-accent"]);+ });++ it("flags bracketed arbitrary values so the sweep can count them", () => {+ const found = extractClassCandidates(`<div className="text-[11px] text-center" />`);++ expect(found.filter((candidate) => candidate.arbitrary).map((c) => c.raw)).toEqual([+ "text-[11px]",+ ]);+ });++ it("ignores strings that are not class lists", () => {+ const source = `const styles = getComputedStyle(el);+ const label = "Export video";+ log("failed to open the project file");`;++ expect(bases(source)).toEqual([]);+ });++ it("does not read past the end of a class region", () => {+ const source = `<div className="flex" title="Export video" />`;++ expect(bases(source)).toEqual(["flex"]);+ });++ it("survives an unterminated region without hanging", () => {+ expect(bases(`<div className={cn("flex",`)).toEqual(["flex"]);+ });+});diff --git a/packages/studio/src/styles/classCandidates.ts b/packages/studio/src/styles/classCandidates.tsnew file mode 100644index 0000000000..c1e559c002--- /dev/null+++ b/packages/studio/src/styles/classCandidates.ts@@ -0,0 +1,281 @@+// Pulls Tailwind class candidates out of a TS/TSX file: only strings unambiguously used as class lists+// (className/class attributes, cn/clsx/cva-style calls, `*class` properties, identifiers those use,+// `*Styles`/`*Classes` bindings). Bare strings are ignored so prose and paths never become "classes".+// Pure: text in, candidates out.++import { escapeRegex } from "../utils/sourcePatcher";++/** A class candidate and where it came from. */+export interface ClassCandidate {+ /** The utility with its variant prefixes removed (`hover:bg-x` -> `bg-x`). */+ readonly base: string;+ /** The token exactly as it was written, for the failure message. */+ readonly raw: string;+ /** True when the utility carries a bracketed arbitrary value. */+ readonly arbitrary: boolean;+}++const OPEN: Record<string, string> = { "{": "}", "(": ")", "[": "]" };++// Index of the last char of the non-code span (string, template, line or block comment) starting at+// `i`, else -1. Known limit: a regex literal containing a quote reads as a string; the cost is a+// spurious candidate, which the gate reports.+function endOfSpan(text: string, i: number): number {+ const ch = text[i];+ if (ch === '"' || ch === "'" || ch === "`") {+ return Math.min(endOfString(text, i), text.length - 1);+ }+ if (ch !== "/") return -1;+ if (text[i + 1] === "/") {+ const end = text.indexOf("\n", i);+ return end === -1 ? text.length - 1 : end - 1;+ }+ if (text[i + 1] === "*") {+ const end = text.indexOf("*/", i + 2);+ return end === -1 ? text.length - 1 : end + 1;+ }+ return -1;+}++// Index just past the region starting at `start` (an opening bracket), skipping strings, templates+// and comments; `text.length` when it never closes.+function endOfRegion(text: string, start: number): number {+ const stack: string[] = [];+ for (let i = start; i < text.length; i += 1) {+ const span = endOfSpan(text, i);+ if (span >= i) {+ i = span;+ continue;+ }+ const ch = text[i];+ if (OPEN[ch]) {+ stack.push(OPEN[ch]);+ } else if (stack.length > 0 && ch === stack[stack.length - 1]) {+ stack.pop();+ if (stack.length === 0) return i + 1;+ }+ }+ return text.length;+}++/** Index of the closing quote of the string that opens at `start`. */+function endOfString(text: string, start: number): number {+ const quote = text[start];+ for (let i = start + 1; i < text.length; i += 1) {+ if (text[i] === "\\") {+ i += 1;+ continue;+ }+ if (text[i] === quote) return i;+ if (quote === "`" && text[i] === "$" && text[i + 1] === "{") {+ i = endOfRegion(text, i + 1) - 1;+ }+ }+ return text.length;+}++// Splits a template literal body into safe chunks. A chunk touching an interpolation is dropped at+// that edge (`w-${size}` claims no class `w-`) unless whitespace separates it from the hole.+function templateChunks(body: string): string[] {+ const chunks: string[] = [];+ let cursor = 0;+ let precededByHole = false;+ while (cursor <= body.length) {+ const hole = body.indexOf("${", cursor);+ const end = hole === -1 ? body.length : hole;+ let chunk = body.slice(cursor, end);+ if (precededByHole && !/^\s/.test(chunk)) chunk = chunk.replace(/^\S+/, "");+ if (hole !== -1 && !/\s$/.test(chunk)) chunk = chunk.replace(/\S+$/, "");+ chunks.push(chunk);+ if (hole === -1) break;+ cursor = endOfRegion(body, hole + 1);+ precededByHole = true;+ }+ return chunks;+}++// A same-length copy with comment and string bodies blanked, so offsets line up. Anchors match+// against it to keep out prose (one apostrophe in a comment opens a string that swallows the rest)+// and generated code (`captions/generator.ts` writes `x.className = 'word'` into a string).+function maskLiterals(text: string): string {+ let out = "";+ for (let i = 0; i < text.length; i += 1) {+ const span = endOfSpan(text, i);+ if (span < i) {+ out += text[i];+ continue;+ }+ // A comment goes entirely, newlines kept so line numbers survive. A string+ // keeps its quotes, so the region scan still finds where it ends.+ const body = " ".repeat(span - i - 1);+ out +=+ text[i] === "/"+ ? text.slice(i, span + 1).replace(/[^\n]/g, " ")+ : text[i] + body + text[span];+ i = span;+ }+ return out;+}++// `activeTool === "razor" ? a : b` inside a `className=` region: the operand+// of a comparison is a value being tested, never a class list.+const COMPARISON = /(?:[=!]==?|\bcase)\s*$/;+// A class list never carries a declaration, so `position: absolute; ...` in a+// constant called `visualStyles` is a stylesheet, not classes.+const CSS_TEXT = /[a-z-]+\s*:\s*[^;]+;/;+// The calls whose arguments are class lists.+const CLASS_BUILDER = /^(?:cn|clsx|classnames|classNames|twMerge|twJoin|cva|tv)$/;++// Written with escapes, not literal quotes: `maskLiterals` reads a quote in+// a regular-expression literal as the start of a string, and this file is+// one of the files the gate scans.+const CLOSE = /[)\]}]/;+const QUOTE = /[\u0022\u0027\u0060]/;++/**+ * A string is a class list unless it is being compared against or is a sheet+ * of CSS text.+ */+function isClassList(mask: string, start: number, i: number, body: string): boolean {+ return !COMPARISON.test(mask.slice(Math.max(start, i - 8), i)) && !CSS_TEXT.test(body);+}++/**+ * Does a string inside the bracket that opens at `i` hold classes? A bracket opened by a+ * non-class-builder name closes the door: `T[f.inlineStyles["font-weight"]]` has a lookup key.+ */+function opensClassContext(mask: string, from: number, i: number): boolean {+ const name = /([A-Za-z_$][\w$]*)\s*$/.exec(mask.slice(Math.max(from, i - 40), i))?.[1];+ return name === undefined || CLASS_BUILDER.test(name);+}++/**+ * Every string and template body inside a source region. Where the strings are+ * is decided on the mask; what they contain is read from the real text.+ */+function stringsIn(text: string, mask: string, start: number, end: number): string[] {+ const found: string[] = [];+ const classy: boolean[] = [];+ for (let i = start; i < end; i += 1) {+ const ch = mask[i];+ if (OPEN[ch]) classy.push(opensClassContext(mask, start, i));+ else if (CLOSE.test(ch)) classy.pop();+ else if (QUOTE.test(ch)) {+ const close = endOfString(mask, i);+ const body = text.slice(i + 1, close);+ if (classy.at(-1) !== false && isClassList(mask, start, i, body)) {+ found.push(...(ch === "`" ? templateChunks(body) : [body]));+ }+ i = close;+ }+ }+ return found;+}++/** Split on `:` that sits outside brackets, so `[&:hover]:x` yields `x`. */+function stripVariants(token: string): string {+ let depth = 0;+ let last = 0;+ for (let i = 0; i < token.length; i += 1) {+ const ch = token[i];+ if (ch === "[" || ch === "(") depth += 1;+ else if (ch === "]" || ch === ")") depth -= 1;+ else if (ch === ":" && depth === 0) last = i + 1;+ }+ return token.slice(last);+}++// A utility starts with a letter, a digit, `-` (negative), `@` (container+// query) or `[` (fully arbitrary), and never contains a quote or a backslash.+// The quotes are written as escapes so this file can be read by its own+// comment stripper, which treats a quote in a regex literal as a string.+const TOKEN = /^[-@[a-z0-9][^\s\u0022\u0027\u0060\\]*$/;++// Class contexts: each anchor's balanced region is read for strings. The first `CLASS_POSITIONS` are+// places a class lands, so identifiers used inside them are followed to their bindings.+const ANCHORS = [+ // className={...} / className="..." / class="..."+ /\bclass(?:Name)?\s*=\s*/g,+ // cn("..."), clsx(...), twMerge(...), cva(...)+ /\b(?:cn|clsx|classnames|classNames|twMerge|twJoin|cva|tv)\s*\(/g,+ // { className: "...", itemClass: "..." }+ /\b\w*[Cc]lass(?:Names?)?\s*:\s*/g,+ // const sizeStyles: Record<Size, string> = { ... } / baseClasses = "..." (exported maps used elsewhere)+ // Prefix and plural both required: bare `style=` is the JSX attribute, `fxPresetStyle` is CSS text.+ // The optional group is a type annotation; without it the gap spans `computedStyles["z-index"] !== "auto"`.+ /\b\w+(?:Styles|Classes|ClassNames?)\b(?:\s*:[^=;{}()[\]]*)?\s*=(?!=)\s*/g,+] as const;++const CLASS_POSITIONS = 3;++/** Bare identifiers in a region of the mask; property accesses excluded. */+const REFERENCE = /(?<![.\w$])[A-Za-z_$][\w$]*/g;++// A subscript, i.e. the `[variant]` of `variantStyles[variant]`. In+// `cn(variantStyles[variant])` the class list is the map; the key is a value+// being looked up, and `variant = "secondary"` is a default, not a class.+const SUBSCRIPT = /(?<=[\w$)\]])\s*\[[^[\]]*\]/g;++// End of the bracketed region or string at `at`, else -1: `const styles = getComputedStyle(el)`+// matches the binding-name anchor but is not a class list.+function regionAfter(mask: string, at: number): number {+ if (OPEN[mask[at]]) return endOfRegion(mask, at);+ if (QUOTE.test(mask[at])) return endOfString(mask, at) + 1;+ return -1;+}++/** Split one class list into candidates, keeping the first spelling of each. */+function collect(byRaw: Map<string, ClassCandidate>, list: string): void {+ for (const raw of list.split(/\s+/)) {+ if (raw === "" || !TOKEN.test(raw) || byRaw.has(raw)) continue;+ const base = stripVariants(raw);+ if (base === "") continue;+ byRaw.set(raw, { base, raw, arbitrary: base.includes("[") });+ }+}++// Every `[start, end)` an anchor opens. `lastIndex` jumps past each region so a nested `cn()`+// inside a `className=` is not read twice.+function regionsAfter(mask: string, anchor: RegExp): [number, number][] {+ const pattern = new RegExp(anchor.source, "g");+ const regions: [number, number][] = [];+ let match: RegExpExecArray | null;+ while ((match = pattern.exec(mask)) !== null) {+ const start = match.index + match[0].length - (match[0].endsWith("(") ? 1 : 0);+ const end = regionAfter(mask, start);+ if (end <= start) continue;+ regions.push([start, end]);+ pattern.lastIndex = Math.max(pattern.lastIndex, end);+ }+ return regions;+}++// Every string bound to `name` by an assignment in this file. A name with no literal binding+// (parameter, import, call result) yields nothing, so an over-broad reference scan is safe.+function boundStrings(text: string, mask: string, name: string): string[] {+ const anchor = new RegExp(+ `(?<![\\w$])${escapeRegex(name)}(?![\\w$])(?:\\s*:[^=;{}()[\\]]*)?\\s*=(?!=)\\s*`,+ );+ return regionsAfter(mask, anchor).flatMap(([start, end]) => stringsIn(text, mask, start, end));+}++/** Every class candidate claimed by one source file. */+export function extractClassCandidates(source: string): ClassCandidate[] {+ // Anchors and region bounds come from the mask (code only); the strings+ // themselves are read back out of the real text.+ const mask = maskLiterals(source);+ const byRaw = new Map<string, ClassCandidate>();+ const referenced = new Set<string>();+ for (const [index, anchor] of ANCHORS.entries()) {+ for (const [start, end] of regionsAfter(mask, anchor)) {+ for (const text of stringsIn(source, mask, start, end)) collect(byRaw, text);+ if (index >= CLASS_POSITIONS) continue;+ const used = mask.slice(start, end).replace(SUBSCRIPT, "");+ for (const [name] of used.matchAll(REFERENCE)) referenced.add(name);+ }+ }+ for (const name of referenced) {+ for (const text of boundStrings(source, mask, name)) collect(byRaw, text);+ }+ return [...byRaw.values()];+}diff --git a/packages/studio/src/styles/hex-baseline.json b/packages/studio/src/styles/hex-baseline.jsonnew file mode 100644index 0000000000..eb038c5e0d--- /dev/null+++ b/packages/studio/src/styles/hex-baseline.json@@ -0,0 +1,85 @@+{+ "total": 423,+ "files": {+ "packages/studio/src/captions/components/CaptionOverlay.tsx": 5,+ "packages/studio/src/captions/components/CaptionTimeline.tsx": 11,+ "packages/studio/src/captions/generator.ts": 1,+ "packages/studio/src/captions/parser.ts": 1,+ "packages/studio/src/captions/types.ts": 4,+ "packages/studio/src/components/StudioHeader.tsx": 5,+ "packages/studio/src/components/StudioToast.tsx": 10,+ "packages/studio/src/components/TimelineToolbar.tsx": 2,+ "packages/studio/src/components/editor/ArcPathControls.tsx": 1,+ "packages/studio/src/components/editor/BorderRadiusEditor.tsx": 10,+ "packages/studio/src/components/editor/DomEditCropHandles.tsx": 1,+ "packages/studio/src/components/editor/EaseCurveSection.tsx": 2,+ "packages/studio/src/components/editor/FileTree.tsx": 2,+ "packages/studio/src/components/editor/FileTreeIcons.tsx": 17,+ "packages/studio/src/components/editor/FileTreeNodes.tsx": 4,+ "packages/studio/src/components/editor/GestureTrailOverlay.tsx": 1,+ "packages/studio/src/components/editor/GridOverlay.tsx": 4,+ "packages/studio/src/components/editor/InlineTextToolbar.tsx": 2,+ "packages/studio/src/components/editor/KeyframeDiamond.tsx": 2,+ "packages/studio/src/components/editor/KeyframeNavigation.tsx": 2,+ "packages/studio/src/components/editor/MotionPathNode.tsx": 5,+ "packages/studio/src/components/editor/SnapGuideOverlay.tsx": 3,+ "packages/studio/src/components/editor/TimelineFxPopover.tsx": 1,+ "packages/studio/src/components/editor/Transform3DCube.tsx": 6,+ "packages/studio/src/components/editor/colorValue.ts": 3,+ "packages/studio/src/components/editor/domEditingElement.ts": 1,+ "packages/studio/src/components/editor/easeCurveSvg.tsx": 2,+ "packages/studio/src/components/editor/gradientValue.ts": 6,+ "packages/studio/src/components/editor/panelTokens.ts": 4,+ "packages/studio/src/components/editor/propertyPanelColor.tsx": 7,+ "packages/studio/src/components/editor/propertyPanelColorCurveGraph.tsx": 17,+ "packages/studio/src/components/editor/propertyPanelColorScopes.tsx": 8,+ "packages/studio/src/components/editor/propertyPanelColorWheels.tsx": 8,+ "packages/studio/src/components/editor/propertyPanelFlatEffectsSection.tsx": 5,+ "packages/studio/src/components/editor/propertyPanelFlatStyleSections.tsx": 2,+ "packages/studio/src/components/editor/propertyPanelFxCarveModule.tsx": 1,+ "packages/studio/src/components/editor/propertyPanelFxFamily.ts": 1,+ "packages/studio/src/components/editor/propertyPanelFxPresetStyle.ts": 24,+ "packages/studio/src/components/editor/propertyPanelHelpers.ts": 4,+ "packages/studio/src/components/editor/propertyPanelPrimitives.tsx": 1,+ "packages/studio/src/components/editor/propertyPanelSections.tsx": 1,+ "packages/studio/src/components/editor/propertyPanelStyleSections.tsx": 3,+ "packages/studio/src/components/editor/transform3dProjection.ts": 3,+ "packages/studio/src/components/feedback/StudioFeedbackCard.tsx": 10,+ "packages/studio/src/components/panels/VariablesBindElement.tsx": 2,+ "packages/studio/src/components/panels/VariablesValueControls.tsx": 2,+ "packages/studio/src/components/sidebar/AudioRow.tsx": 2,+ "packages/studio/src/components/ui/HyperframesMark.tsx": 4,+ "packages/studio/src/hooks/useInlineTextEdit.ts": 1,+ "packages/studio/src/player/components/AudioWaveform.tsx": 6,+ "packages/studio/src/player/components/BeatStrip.tsx": 6,+ "packages/studio/src/player/components/CompositionThumbnail.tsx": 2,+ "packages/studio/src/player/components/ImageThumbnail.tsx": 6,+ "packages/studio/src/player/components/LayerDisclosureRow.tsx": 3,+ "packages/studio/src/player/components/Player.tsx": 2,+ "packages/studio/src/player/components/PlayerControls.tsx": 1,+ "packages/studio/src/player/components/PlayheadIndicator.tsx": 3,+ "packages/studio/src/player/components/ShortcutsPanel.tsx": 7,+ "packages/studio/src/player/components/SpeedMenu.tsx": 2,+ "packages/studio/src/player/components/TimelineAutomationLane.tsx": 4,+ "packages/studio/src/player/components/TimelineCanvas.tsx": 13,+ "packages/studio/src/player/components/TimelineClip.tsx": 2,+ "packages/studio/src/player/components/TimelineClipDiamonds.tsx": 2,+ "packages/studio/src/player/components/TimelineDiamondConnectors.tsx": 2,+ "packages/studio/src/player/components/TimelineEmptyState.tsx": 1,+ "packages/studio/src/player/components/TimelineFxButton.tsx": 8,+ "packages/studio/src/player/components/TimelineGroupHeader.tsx": 6,+ "packages/studio/src/player/components/TimelineGroupLaneLabels.tsx": 1,+ "packages/studio/src/player/components/TimelineGroupRow.tsx": 1,+ "packages/studio/src/player/components/TimelineRazorInteraction.tsx": 1,+ "packages/studio/src/player/components/TimelineRuler.tsx": 1,+ "packages/studio/src/player/components/TimelineShortcutHint.tsx": 2,+ "packages/studio/src/player/components/TimelineTrackHeader.tsx": 2,+ "packages/studio/src/player/components/TimelineTrackPlainHeader.tsx": 2,+ "packages/studio/src/player/components/VideoThumbnail.tsx": 6,+ "packages/studio/src/player/components/timelineTheme.ts": 29,+ "packages/studio/src/player/components/trackHeaderLabelRows.tsx": 6,+ "packages/studio/src/styles/studio.css": 70,+ "packages/studio/src/telemetry/client.ts": 1,+ "packages/studio/src/webmcp/webmcpTestUtils.ts": 1+ }+}diff --git a/packages/studio/src/styles/hexRatchet.test.ts b/packages/studio/src/styles/hexRatchet.test.tsnew file mode 100644index 0000000000..3c5bb0aef0--- /dev/null+++ b/packages/studio/src/styles/hexRatchet.test.ts@@ -0,0 +1,201 @@+// The hex ratchet (R12, AE2): a per-file baseline of colour literals that only ever goes down.+// Per file so two sweep PRs touching one file conflict on its line and force a recount.+// The baseline is never regenerated by a normal run: a missing one fails, and rewriting it needs+// the named flag, so the number in git is one a human accepted.++import { existsSync, readFileSync, writeFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { listSourceFiles, REPO_ROOT, STYLES_DIR } from "./styleSources";++const BASELINE_PATH = path.join(STYLES_DIR, "hex-baseline.json");++const WRITE_FLAG = "HEX_BASELINE_WRITE";+const LOWER_COMMAND = `${WRITE_FLAG}=1 bunx vitest run src/styles/hexRatchet.test.ts`;++// A literal colour: `#abc`, `#aabbcc`, `#aabbccdd`, or functional notation. This test owns the+// regex, so the baseline is whatever this rule sees.+const COLOR_LITERAL = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\b|\b(?:rgba?|hsla?)\(/gi;++/** Files whose whole job is to hold colour values. */+function isTokenSource(relative: string): boolean {+ return /styles\/(theme\.css|tailwind-preset\.shared\.js|tailwind-preset\.ts)$/.test(relative);+}++function isScanned(relative: string): boolean {+ if (isTokenSource(relative) || /\.test\.tsx?$/.test(relative)) return false;+ return /\.(tsx?|css)$/.test(relative);+}++/** Strings match first and are kept, so `"image/*"` or `"a//b"` never opens a comment. */+const STRING_OR_COMMENT =+ /("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g;++/** Comments hold issue numbers like `#2291` that read as hex; count code only. */+function stripComments(text: string, lineComments: boolean): string {+ return text.replace(STRING_OR_COMMENT, (match, string?: string) => {+ if (string !== undefined) return match;+ return match.startsWith("//") && !lineComments ? match : "";+ });+}++function countColorLiterals(text: string, lineComments = true): number {+ return [...stripComments(text, lineComments).matchAll(COLOR_LITERAL)].length;+}++/** Repository-relative path to colour-literal count, for every scanned file. */+function scan(): Map<string, number> {+ const counts = new Map<string, number>();+ for (const [file, text] of listSourceFiles(isScanned, REPO_ROOT)) {+ const count = countColorLiterals(text, !file.endsWith(".css"));+ if (count > 0) counts.set(file, count);+ }+ return counts;+}++interface Baseline {+ readonly total: number;+ readonly files: Readonly<Record<string, number>>;+}++function toBaseline(counts: ReadonlyMap<string, number>): Baseline {+ const files: Record<string, number> = {};+ let total = 0;+ for (const key of [...counts.keys()].sort()) {+ files[key] = counts.get(key) ?? 0;+ total += files[key];+ }+ return { total, files };+}++/** Every file whose count moved, split by direction. */+function compare(counts: ReadonlyMap<string, number>, baseline: Baseline) {+ const risen: string[] = [];+ const fallen: string[] = [];+ // A file missing from the baseline has a baseline of zero, so a rename+ // cannot smuggle its colours past the ratchet.+ for (const [file, count] of counts) {+ const allowed = baseline.files[file] ?? 0;+ if (count > allowed) risen.push(`${file}: ${count} colour literals, baseline ${allowed}`);+ if (count < allowed) fallen.push(`${file}: ${count}, baseline ${allowed}`);+ }+ for (const [file, allowed] of Object.entries(baseline.files)) {+ if (!counts.has(file)) fallen.push(`${file}: now 0, baseline ${allowed}`);+ }+ return { risen, fallen };+}++// A rise is a failure. A fall is reported with the command that banks it, because a baseline+// left high is a budget the next change can spend.+function verdict(counts: ReadonlyMap<string, number>, baseline: Baseline | undefined): string[] {+ if (baseline === undefined) {+ return [`src/styles/hex-baseline.json is missing. Write it with: ${LOWER_COMMAND}`];+ }+ const { risen, fallen } = compare(counts, baseline);+ if (risen.length > 0) {+ return [+ "Colour literals belong in src/styles/theme.css.",+ ...risen,+ `If these are unavoidable, lower is the only direction: ${LOWER_COMMAND}`,+ ];+ }+ if (fallen.length > 0) return [`Colour literals went down. Bank it: ${LOWER_COMMAND}`, ...fallen];+ return [];+}++function readBaseline(): Baseline | undefined {+ if (!existsSync(BASELINE_PATH)) return undefined;+ return JSON.parse(readFileSync(BASELINE_PATH, "utf8")) as Baseline;+}++describe("colour literal counter", () => {+ it("counts a hex in a style object, in canvas code and in a stylesheet", () => {+ expect(countColorLiterals(`<div style={{ background: "#161618" }} />`)).toBe(1);+ expect(countColorLiterals(`context.fillStyle = "#090b0e";`)).toBe(1);+ expect(countColorLiterals(`.ring { box-shadow: 0 0 0 1px rgb(110 231 183); }`)).toBe(1);+ expect(countColorLiterals(`a { color: rgba(0, 0, 0, 0.5); border-color: hsl(0 0% 4%); }`)).toBe(+ 2,+ );+ });++ it("does not mistake a fragment or an issue number for a colour", () => {+ // Known limit: an identifier that is exactly 3, 4, 6 or 8 hex characters+ // in code reads as a colour; the baseline absorbs it.+ expect(countColorLiterals(`href="#section-two" // see #12345`)).toBe(0);+ });++ it("keeps a colour that follows comment-shaped text inside a string", () => {+ expect(countColorLiterals(`accept="image/*"; const c = "#161618"; x = "*/";`)).toBe(1);+ expect(countColorLiterals("const u = `x//y`; const c = '#161618';")).toBe(1);+ expect(countColorLiterals(`.a { background: url(//cdn.test/a.png) #161618; }`, false)).toBe(1);+ });++ it("ignores a colour-shaped issue number in a line or block comment", () => {+ expect(countColorLiterals(`const a = 1; // decision (#2291)`)).toBe(0);+ expect(countColorLiterals(`/** see #2291 and rgba(0,0,0,1) */\nconst a = 1;`)).toBe(0);+ expect(countColorLiterals(`fetch("https://x.test/#abc"); const c = "#161618"; // #2291`)).toBe(+ 2,+ );+ });++ it("leaves the token sources and the tests out of the scan", () => {+ expect(isScanned("packages/studio/src/styles/theme.css")).toBe(false);+ expect(isScanned("packages/studio/src/styles/tailwind-preset.shared.js")).toBe(false);+ expect(isScanned("packages/studio/src/styles/theme.test.ts")).toBe(false);+ expect(isScanned("packages/studio/src/components/ui/Button.tsx")).toBe(true);+ });+});++describe("hex ratchet", () => {+ const baseline: Baseline = { total: 2, files: { "a.tsx": 2 } };++ it("fails when a file's count rises, naming the file and both numbers", () => {+ // Covers AE2.+ const message = verdict(new Map([["a.tsx", 3]]), baseline).join("\n");++ expect(message).toContain("a.tsx: 3 colour literals, baseline 2");+ expect(message).toContain(LOWER_COMMAND);+ });++ it("passes when a count falls and says how to bank it", () => {+ const message = verdict(new Map([["a.tsx", 1]]), baseline).join("\n");++ expect(message).toContain("Colour literals went down");+ expect(message).toContain(LOWER_COMMAND);+ });++ it("treats a file the baseline has never seen as a baseline of zero", () => {+ const empty: Baseline = { total: 0, files: {} };++ expect(verdict(new Map([["new.tsx", 0]]), empty)).toEqual([]);+ expect(verdict(new Map([["new.tsx", 1]]), empty).join("\n")).toContain(+ "new.tsx: 1 colour literals, baseline 0",+ );+ });++ it("round-trips: a baseline written from a scan accepts that same scan", () => {+ const counts = new Map([+ ["b.css", 4],+ ["a.tsx", 2],+ ]);+ const written = toBaseline(counts);++ expect(Object.keys(written.files)).toEqual(["a.tsx", "b.css"]);+ expect(written.total).toBe(6);+ expect(verdict(counts, written)).toEqual([]);+ });++ it("fails with the flag named when there is no baseline at all", () => {+ expect(verdict(new Map([["a.tsx", 0]]), undefined).join("\n")).toContain(`${WRITE_FLAG}=1`);+ });++ it("holds Studio at or below its committed colour-literal baseline", () => {+ const counts = scan();+ if (process.env[WRITE_FLAG] === "1") {+ writeFileSync(BASELINE_PATH, `${JSON.stringify(toBaseline(counts), null, 2)}\n`);+ }+ const committed = readBaseline();++ expect(verdict(counts, committed)).toEqual([]);+ });+});diff --git a/packages/studio/src/styles/styleSources.test.ts b/packages/studio/src/styles/styleSources.test.tsnew file mode 100644index 0000000000..5df740a6bd--- /dev/null+++ b/packages/studio/src/styles/styleSources.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { listSourceFiles, toPosixPath } from "./styleSources";++describe("style source paths", () => {+ it("turns a Windows-style relative path into the forward-slash form the baseline uses", () => {+ expect(toPosixPath("packages\\studio\\src\\App.tsx")).toBe("packages/studio/src/App.tsx");+ });++ it("leaves a forward-slash path alone", () => {+ expect(toPosixPath("packages/studio/src/App.tsx")).toBe("packages/studio/src/App.tsx");+ });++ it("hands the keep filter and the map key the same forward-slash path", () => {+ const seen: string[] = [];+ const files = listSourceFiles((file) => (seen.push(file), file.endsWith("styleSources.ts")));++ expect([...files.keys()]).toEqual(["styles/styleSources.ts"]);+ expect(seen.every((file) => !file.includes("\\"))).toBe(true);+ });+});diff --git a/packages/studio/src/styles/styleSources.ts b/packages/studio/src/styles/styleSources.tsnew file mode 100644index 0000000000..b1cda4487d--- /dev/null+++ b/packages/studio/src/styles/styleSources.ts@@ -0,0 +1,47 @@+// Where the style tests read from: Tailwind's entry resolved from `node_modules`, and the file list+// that `@source` in `studio.css` describes, shared so the gate, ratchet and theme test agree.++import { createRequire } from "node:module";+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++export const STYLES_DIR = path.dirname(fileURLToPath(import.meta.url));+const SRC_DIR = path.dirname(STYLES_DIR);+export const REPO_ROOT = path.resolve(SRC_DIR, "../../..");++const require = createRequire(import.meta.url);+export const TAILWIND_DIR = path.dirname(require.resolve("tailwindcss/package.json"));++/** Resolves `@import` for Tailwind's compiler: bare `tailwindcss`, or a path. */+export function loadStylesheet(id: string, base: string) {+ const file = id === "tailwindcss" ? path.join(TAILWIND_DIR, "index.css") : path.resolve(base, id);+ return { path: file, base: path.dirname(file), content: readFileSync(file, "utf8") };+}++/** Forward slashes on every platform, so keys match the baseline file and the gate's messages. */+export const toPosixPath = (relativePath: string): string => relativePath.replace(/\\/g, "/");++/**+ * Studio's own sources, keyed by path relative to `from`, for every file the+ * caller keeps. Build output and dependencies are never walked.+ */+export function listSourceFiles(+ keep: (relativePath: string) => boolean,+ from: string = SRC_DIR,+): Map<string, string> {+ const files = new Map<string, string>();+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== "node_modules" && entry.name !== "dist") walk(full);+ } else {+ const relative = toPosixPath(path.relative(from, full));+ if (keep(relative)) files.set(relative, readFileSync(full, "utf8"));+ }+ }+ };+ walk(SRC_DIR);+ return files;+}diff --git a/packages/studio/src/styles/theme.css b/packages/studio/src/styles/theme.cssindex e6e0eee11b..95520e9631 100644--- a/packages/studio/src/styles/theme.css+++ b/packages/studio/src/styles/theme.css@@ -47,6 +47,10 @@--radius-md: 0.375rem;--radius-lg: 0.5rem;+ /* The one radius every push-button wears, named by its role so a button does+ * not have to know which step of the scale it sits on. */+ --radius-button: var(--radius-md);+/* Control heights: 24, 28 and 32 px. `--spacing-*` gives `h-ctl`, `min-h-ctl`* and friends. */--spacing-ctl-sm: 24px;@@ -80,12 +84,23 @@--shadow-menu: 0 8px 24px rgb(0 0 0 / 0.45), 0 0 0 1px rgb(0 0 0 / 0.4);--shadow-popover: 0 16px 40px rgb(0 0 0 / 0.55), 0 0 0 1px rgb(0 0 0 / 0.45);+ /* The primary button is the one light surface in a dark UI, so it reads as a+ * raised key rather than a floating panel: a tight contact shadow, a soft+ * ambient one, and an inner top highlight. */+ --shadow-btn-primary:+ 0 1px 2px rgb(0 0 0 / 0.6), 0 2px 6px rgb(0 0 0 / 0.35), inset 0 1px 0 rgb(255 255 255 / 0.65);+/* ---------------------------------------------------------------- motion */--ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1);--ease-out-expo: cubic-bezier(0.23, 1, 0.32, 1);--ease-in-out-circ: cubic-bezier(0.77, 0, 0.175, 1);+ /* The curve for a small state change (hover, press, focus), named by role so+ * a control does not have to pick one. The other two stay for motion that is+ * meant to be noticed. */+ --ease-standard: var(--ease-out-quint);+/* Durations have no Tailwind namespace, so these are plain variables paired* with the `@utility` rules at the bottom of this file. All are at or under* 200 ms. */@@ -126,11 +141,21 @@--color-panel-text-3: var(--color-text-3);--color-panel-text-4: var(--color-text-4);--color-panel-text-5: var(--color-text-5);+ --color-panel-bg-soft: var(--color-bg-2);+ --color-panel-bg-2: var(--color-bg-2);--color-panel-accent: var(--color-accent);--color-panel-danger: var(--color-danger);--color-panel-media: var(--color-media);--color-panel-container: var(--color-container);+ /* Names Studio's markup invented that no config ever defined, so the classes+ * compiled to nothing. Aliased to the token that was meant, rather than+ * given values of their own, so there is still one source per decision.+ * U12 rewrites the call sites and deletes these. */+ --color-surface-hover: var(--color-hover);+ --color-accent-red: var(--color-danger);+ --text-2xs: var(--text-step-10);+/* ------------------------------------------- deprecated: Tailwind palette *//* Verbatim Tailwind 4.3.3 defaults for stock colours markup still names, sodiff --git a/packages/studio/src/styles/theme.test.ts b/packages/studio/src/styles/theme.test.tsindex 75cdc0b312..902d1ad810 100644--- a/packages/studio/src/styles/theme.test.ts+++ b/packages/studio/src/styles/theme.test.ts@@ -4,10 +4,8 @@* property, a utility that stops compiling, the stock Tailwind palette* leaking back in, or the JS preset / legacy colours drifting from it. */-import { createRequire } from "node:module";import { readFileSync } from "node:fs";import path from "node:path";-import { fileURLToPath } from "node:url";import React, { act } from "react";import { createRoot } from "react-dom/client";import { Gear, IconContext } from "@phosphor-icons/react";@@ -15,23 +13,12 @@ import { compile } from "tailwindcss";import { afterEach, describe, expect, it } from "vitest";import studioPreset from "./tailwind-preset.shared.js";import { readIconTokens } from "./iconTokens";+import { loadStylesheet, STYLES_DIR, TAILWIND_DIR } from "./styleSources";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const STYLES_DIR = path.dirname(fileURLToPath(import.meta.url));-const require = createRequire(import.meta.url);-const TAILWIND_DIR = path.dirname(require.resolve("tailwindcss/package.json"));--function loadStylesheet(id: string, base: string) {- const file = id === "tailwindcss" ? path.join(TAILWIND_DIR, "index.css") : path.resolve(base, id);- return { path: file, base: path.dirname(file), content: readFileSync(file, "utf8") };-}-async function buildSource(source: string, candidates: string[]): Promise<string> {- const compiled = await compile(source, {- base: STYLES_DIR,- loadStylesheet,- });+ const compiled = await compile(source, { base: STYLES_DIR, loadStylesheet });return compiled.build(candidates);}diff --git a/packages/studio/src/styles/tokenGate.test.ts b/packages/studio/src/styles/tokenGate.test.tsnew file mode 100644index 0000000000..40dec4151b--- /dev/null+++ b/packages/studio/src/styles/tokenGate.test.ts@@ -0,0 +1,109 @@+// The token gate (R11, AE1). Tailwind silently drops a class it cannot compile, so `rounded-button`+// renders as no radius and nothing goes red. This compiles Studio's real entry stylesheet with every+// class the source claims and reports any candidate producing no selector as `file: class`.+// Tailwind is the only judge, so there is no allowlist; a failing class is fixed, never excused.++import { readFileSync } from "node:fs";+import path from "node:path";+import { compile } from "tailwindcss";+import { describe, expect, it } from "vitest";+import { extractClassCandidates } from "./classCandidates";+import { listSourceFiles, loadStylesheet, STYLES_DIR } from "./styleSources";++// A class selector in the emitted CSS, escapes removed: `.hover\:bg-surface\/50` reads back as its candidate.+const CLASS_SELECTOR = /\.((?:\\.|[^\s.,{}()>+~:[\]#'"*/\\])+)/g;++// Tailwind's `group`/`peer` variant markers (`group/card`) produce no rule of their own, so no+// compiled selector can vouch for them. Nothing else is exempt.+const MARKERS = new Set(["group", "peer"]);++// `hf-` is HyperFrames' reserved prefix for semantic hooks, not utilities, so Tailwind is the+// wrong judge of them.+const HOOK_PREFIX = /^hf-/;++/** Compile Studio's stylesheet and return every class it can produce. */+async function resolvable(candidates: string[]): Promise<Set<string>> {+ const compiled = await compile(readFileSync(path.join(STYLES_DIR, "studio.css"), "utf8"), {+ base: STYLES_DIR,+ loadStylesheet,+ });+ const css = compiled.build(candidates);+ const selectors = new Set<string>();+ for (const [, selector] of css.matchAll(CLASS_SELECTOR)) {+ selectors.add(selector.replace(/\\(.)/g, "$1"));+ }+ return selectors;+}++// `file: class` for every class the sources claim that Tailwind cannot make. Sources are passed+// in so the fixtures exercise the same code path as the tree.+async function unresolved(sources: ReadonlyMap<string, string>): Promise<string[]> {+ const claims = new Map<string, string[]>();+ for (const [file, source] of sources) {+ for (const candidate of extractClassCandidates(source)) {+ const seen = claims.get(candidate.base);+ if (seen) seen.push(file);+ else claims.set(candidate.base, [file]);+ }+ }+ const produced = await resolvable([...claims.keys()]);+ const failures: string[] = [];+ for (const [candidate, files] of claims) {+ if (produced.has(candidate) || MARKERS.has(candidate.split("/")[0])) continue;+ if (HOOK_PREFIX.test(candidate)) continue;+ for (const file of files) failures.push(`${file}: ${candidate}`);+ }+ return failures.sort();+}++// Every file the gate reads, mirroring the `@source` globs in `studio.css`. Tests are excluded:+// a fixture in a test is not markup.+function studioSources(): Map<string, string> {+ return listSourceFiles((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file));+}++describe("token gate", () => {+ it("names the file and the class when a class resolves to nothing", async () => {+ // AE1: `rounded-hologram` looks like a token name but is defined nowhere. The map is named+ // `buttonSizes`, not `sizeStyles`: the `cn()` that consumes it puts it in front of the gate.+ const failures = await unresolved(+ new Map([+ [+ "ui/Button.tsx",+ `const buttonSizes = { md: "h-8 rounded-hologram text-mega" };+ const Button = ({ size }) => <button className={cn(buttonSizes[size])} />;`,+ ],+ ]),+ );++ expect(failures).toEqual(["ui/Button.tsx: rounded-hologram", "ui/Button.tsx: text-mega"]);+ });++ it("accepts an arbitrary value and reports it as one", async () => {+ const source = `<div className="text-[11px]" />`;++ expect(await unresolved(new Map([["a.tsx", source]]))).toEqual([]);+ expect(extractClassCandidates(source).filter((c) => c.arbitrary)).toHaveLength(1);+ });++ it("accepts variants, static utilities and Studio's own CSS classes", async () => {+ // `timeline-clip` is a plain rule in `studio.css`, not a utility.+ const source = `<div className="hover:bg-surface/50 text-center border-dashed timeline-clip" />`;++ expect(await unresolved(new Map([["a.tsx", source]]))).toEqual([]);+ });++ it("leaves Studio's own hook prefix and Tailwind's variant markers alone", async () => {+ const source = `<div className="group group/card peer hf-fx-node" />`;++ expect(await unresolved(new Map([["a.tsx", source]]))).toEqual([]);+ });++ it("claims nothing for a template chunk that touches an interpolation", async () => {+ expect(await unresolved(new Map([["a.tsx", "<div className={`w-${i}`} />"]]))).toEqual([]);+ });++ it("resolves every class Studio's own source claims", async () => {+ expect(await unresolved(studioSources())).toEqual([]);+ });+});diff --git a/packages/studio/src/utils/sourcePatcher.ts b/packages/studio/src/utils/sourcePatcher.tsindex 5f3c531cb6..fd799632ff 100644--- a/packages/studio/src/utils/sourcePatcher.ts+++ b/packages/studio/src/utils/sourcePatcher.ts@@ -3,7 +3,7 @@* Handles inline style updates, attribute changes, and text content.*/-function escapeRegex(s: string): string {+export function escapeRegex(s: string): string {return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}