diff --git a/docs/snippets/catalog-detail.jsx b/docs/snippets/catalog-detail.jsx index 02e476047c..87869d8f5f 100644 --- a/docs/snippets/catalog-detail.jsx +++ b/docs/snippets/catalog-detail.jsx @@ -1710,6 +1710,27 @@ export const CatalogDetail = ({ */ const urlKey = `vars-${compositionId}`; + // >>> preview values + /** JSON that is also inert inside an inline ` +`; + const result = await lintHyperframeHtml(html); + const finding = result.findings.find((f) => f.code === "svg_drawon_css_dasharray_conflict"); + expect(finding).toBeDefined(); + }); + + it("matches a many-placeholder template id against a long near-miss id in linear time", async () => { + const template = Array.from({ length: 40 }, () => "${x}").join("a") + "b"; + const html = ` + +
+ +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(2000); + }); + + it("scans a long style block with no braces in linear time", async () => { + const html = ` +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("scans a closed style block of many unclosed rules in linear time", async () => { + const html = ` +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(2000); + }); + // ── gsap_timeline_set_initial_hide ───────────────────────────────────────── it("gsap_timeline_set_initial_hide: warns on tl.set hidden state at position 0", async () => { diff --git a/packages/lint/src/rules/gsap.ts b/packages/lint/src/rules/gsap.ts index 5886ddd4e0..adef478304 100644 --- a/packages/lint/src/rules/gsap.ts +++ b/packages/lint/src/rules/gsap.ts @@ -420,10 +420,35 @@ function styleLooksFullFrameOverlay(style: string): boolean { return coversFrame && styleHasOpaqueBackground(style); } +// The `[selectorList, body]` pairs `/(? { + const out: Array<[string, string]> = []; + let start = 0; + let close = 0; + while (start < css.length) { + let brace = start; + while (brace < css.length && css[brace] !== "{" && css[brace] !== "}") brace++; + if (brace === css.length) break; + if (css[brace] === "{" && brace > start) { + if (close !== -1 && close <= brace) close = css.indexOf("}", brace + 1); + if (close === -1) break; + if (close > brace + 1) { + out.push([css.slice(start, brace), css.slice(brace + 1, close)]); + start = close + 1; + continue; + } + } + start = brace + 1; + } + return out; +} + function collectSimpleStyleRules(styles: LintContext["styles"]): Map { const rules = new Map(); for (const style of styles) { - for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) { + for (const [selectorList, body] of styleRuleBodies(style.content)) { if (!selectorList || !body) continue; for (const selector of selectorList.split(",")) { const token = selector.trim(); @@ -897,6 +922,25 @@ function expressionReachesMeasurement(expression: string, measuring: Set return false; } +const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; + +// Whether `id` is `parts` in order with a gap of non-line-terminators between each pair, the +// language of `^a.*b.*c$`, checked with leftmost indexOf so time stays linear in the id. +function matchesTemplateParts(id: string, parts: string[]): boolean { + const first = parts[0] ?? ""; + const last = parts[parts.length - 1] ?? ""; + if (parts.length === 1) return id === first; + if (!id.startsWith(first)) return false; + let at = first.length; + for (const part of parts.slice(1, -1)) { + const found = id.indexOf(part, at); + if (found === -1 || LINE_TERMINATOR.test(id.slice(at, found))) return false; + at = found + part.length; + } + const end = id.length - last.length; + return end >= at && id.endsWith(last) && !LINE_TERMINATOR.test(id.slice(at, end)); +} + // Resolve script-level element variables to the simple selector tokens they can // denote: literal getElementById/querySelector lookups, template-literal ids // matched against the document's actual ids, and script-assigned class names @@ -923,9 +967,8 @@ function resolveScriptElementTokens(source: string, tags: OpenTag[]): Map part === "")) continue; - const idPattern = new RegExp(`^${staticParts.map(escapeRegExp).join(".*")}$`); for (const id of documentIds) { - if (idPattern.test(id)) add(match[1] ?? "", `#${id}`); + if (matchesTemplateParts(id, staticParts)) add(match[1] ?? "", `#${id}`); } } for (const match of source.matchAll( @@ -2332,7 +2375,7 @@ export const gsapRules: LintRule[] = [ const multiDashTokens = new Set(); for (const style of styles) { - for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) { + for (const [selectorList, body] of styleRuleBodies(style.content)) { if (!selectorList || !body) continue; const value = readStyleProperty(body, "stroke-dasharray"); if (!value || !isMultiComponentDasharray(value)) continue; diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.ts index a85689beaf..464bbffb80 100644 --- a/packages/parsers/src/gsapParser.ts +++ b/packages/parsers/src/gsapParser.ts @@ -25,6 +25,9 @@ import { distributeArrayKeyframes, authorsKeyframes, plainPercentKey, + scriptJson, + tweenMethodCode, + assertMotionPathNumbers, } from "./gsapSerialize"; export type { @@ -1479,7 +1482,7 @@ function insertAfterAnchor(parsed: ParsedGsapAst, newStatement: AstNode): void { /** Build the source for a single `tl.method(selector, vars, position)` call. */ function buildTweenStatementCode(timelineVar: string, anim: Omit): string { - const selector = JSON.stringify(anim.targetSelector); + const selector = scriptJson(anim.targetSelector); const props: Record = { ...anim.properties }; if (anim.method !== "set" && anim.duration !== undefined) props.duration = anim.duration; if (anim.ease) props.ease = anim.ease; @@ -1521,7 +1524,7 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit `${k}: ${typeof v === "string" ? JSON.stringify(v) : v}`) + .map(([k, v]) => `${safeKey(k)}: ${typeof v === "string" ? scriptJson(v) : v}`) .join(", "); - const code = `${tlVar}.set(${JSON.stringify(selector)}, { ${props} }, ${position});`; + const code = `${tlVar}.set(${scriptJson(selector)}, { ${props} }, ${position});`; const newStatement = parseScript(code).program.body[0]; const anchor = findTimelineDeclarationPath(parsed.ast, tlVar); if (anchor) { @@ -2071,11 +2074,11 @@ function buildKeyframeObjectCode( ): string { const entries = mergePercentageKeyframes(keyframes).map((kf) => { const props = keyframePropsToCode(kf); - if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`); + if (kf.ease) props.push(`ease: ${scriptJson(kf.ease)}`); if (kf.auto) props.push(`_auto: 1`); - return `${JSON.stringify(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`; + return `${scriptJson(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`; }); - if (options?.easeEach) entries.push(`easeEach: ${JSON.stringify(options.easeEach)}`); + if (options?.easeEach) entries.push(`easeEach: ${scriptJson(options.easeEach)}`); return `{ ${entries.join(", ")} }`; } @@ -2124,7 +2127,7 @@ function buildKeyframeValueNode( const entries = Object.entries(properties) .filter(([k]) => k !== "ease") .map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); - if (effectiveEase) entries.push(`ease: ${JSON.stringify(effectiveEase)}`); + if (effectiveEase) entries.push(`ease: ${scriptJson(effectiveEase)}`); return parseExpr(`{ ${entries.join(", ")} }`); } @@ -2134,7 +2137,7 @@ function setObjectExpressionEase(node: AstNode, ease: string): boolean { const easeIdx = props.findIndex( (property: AstNode) => isObjectProperty(property) && propKeyName(property) === "ease", ); - const easeNode = parseExpr(`({ ease: ${JSON.stringify(ease)} })`).properties[0]; + const easeNode = parseExpr(`({ ease: ${scriptJson(ease)} })`).properties[0]; if (easeIdx >= 0) props[easeIdx] = easeNode; else props.push(easeNode); return true; @@ -2235,7 +2238,7 @@ function convertArrayKeyframesToObjectNode(varsArg: AstNode, scope: ScopeBinding el.properties = (el.properties ?? []).filter( (property: AstNode) => !isObjectProperty(property) || propKeyName(property) !== "duration", ); - return `${JSON.stringify(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`; + return `${scriptJson(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`; }); prop.value = parseExpr(`{ ${entries.join(", ")}, easeEach: "none" }`); return prop.value; @@ -2327,7 +2330,7 @@ export function addKeyframeToScript( } } else { // Build the new property node with a quoted percentage key - const newProp = parseExpr(`{ ${JSON.stringify(pctKey)}: {} }`).properties[0]; + const newProp = parseExpr(`{ ${scriptJson(pctKey)}: {} }`).properties[0]; newProp.value = newValueNode; // Insert in sorted order by percentage @@ -2513,7 +2516,7 @@ export function moveKeyframeInScript( const kept = (kfNode.properties ?? []).filter((p: AstNode) => !pctProps.has(p)); kfNode.properties = [ ...entries.map((e) => { - const p = parseExpr(`{ ${JSON.stringify(plainPercentKey(e.pct))}: {} }`).properties[0]; + const p = parseExpr(`{ ${scriptJson(plainPercentKey(e.pct))}: {} }`).properties[0]; p.value = e.value; return p; }), @@ -2555,7 +2558,7 @@ export function resizeKeyframedTweenInScript( seen.add(match.prop); // Replace only the key node; the value node (incl. _auto + per-keyframe ease) // stays verbatim. easeEach is a sibling non-percentage prop, left untouched. - match.prop.key = parseExpr(`{ ${JSON.stringify(plainPercentKey(to))}: 0 }`).properties[0].key; + match.prop.key = parseExpr(`{ ${scriptJson(plainPercentKey(to))}: 0 }`).properties[0].key; } applyUpdatesToCall(loc.target.call, { @@ -2672,7 +2675,7 @@ export function updateKeyframeInScript( else props.push(node); }; for (const [k, v] of Object.entries(properties)) upsert(k, valueToCode(v)); - if (ease !== undefined) upsert("ease", JSON.stringify(ease)); + if (ease !== undefined) upsert("ease", scriptJson(ease)); return recast.print(loc.parsed.ast).code; } match.prop.value = buildKeyframeValueNode(properties, ease); @@ -2701,7 +2704,7 @@ function insertKeyframesProp( ): void { const fromEntries = Object.entries(fromProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); const toEntries = Object.entries(toProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); - const easeEntry = easeEach ? `, easeEach: ${JSON.stringify(easeEach)}` : ""; + const easeEntry = easeEach ? `, easeEach: ${scriptJson(easeEach)}` : ""; const kfCode = `{ "0%": { ${fromEntries.join(", ")} }, "100%": { ${toEntries.join(", ")} }${easeEntry} }`; const kfProp = parseExpr(`{ keyframes: {} }`).properties[0]; kfProp.value = parseExpr(kfCode); @@ -2853,7 +2856,7 @@ export function materializeKeyframesInScript( // Replace dynamic selector with resolved static string if (resolvedSelector && loc.target.call.node.arguments[0]) { - loc.target.call.node.arguments[0] = parseExpr(JSON.stringify(resolvedSelector)); + loc.target.call.node.arguments[0] = parseExpr(scriptJson(resolvedSelector)); } const kfObjCode = buildKeyframeObjectCode(sortedKeyframes(keyframes), { easeEach }); @@ -2898,6 +2901,7 @@ function buildMotionPathObjectCode(config: { segments: ArcPathSegment[]; autoRotate: boolean | number; }): string { + assertMotionPathNumbers(config); const { waypoints, segments, autoRotate } = config; const hasExplicitControlPoints = segments.some((s) => s.cp1 && s.cp2); // The simple `path` array supports only one scalar curviness for the whole @@ -3230,11 +3234,11 @@ export function addMotionPathToScript( segments: [{ curviness: 1 }], autoRotate: false, }); - const selector = JSON.stringify(targetSelector); + const selector = scriptJson(targetSelector); const varEntries = [ `motionPath: ${motionPathCode}`, `duration: ${valueToCode(duration)}`, - `ease: ${JSON.stringify(ease)}`, + `ease: ${scriptJson(ease)}`, ]; const stmtCode = `${parsed.timelineVar}.to(${selector}, { ${varEntries.join(", ")} }, ${valueToCode(position)});`; const newStatement = parseScript(stmtCode).program.body[0]; @@ -3432,7 +3436,7 @@ export function unrollDynamicAnimations( typeof position === "number" ? String(position) : typeof position === "string" - ? JSON.stringify(position) + ? scriptJson(position) : "0"; // Find the enclosing loop (for/forEach) by walking up the AST path @@ -3467,7 +3471,7 @@ export function unrollDynamicAnimations( easeEach: el.easeEach, }); calls.push( - `${loc.parsed.timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`, + `${loc.parsed.timelineVar}.to(${scriptJson(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${scriptJson(ease)} }, ${posCode});`, ); } diff --git a/packages/parsers/src/gsapSerialize.ts b/packages/parsers/src/gsapSerialize.ts index 85a3fda390..3cf19a8838 100644 --- a/packages/parsers/src/gsapSerialize.ts +++ b/packages/parsers/src/gsapSerialize.ts @@ -274,7 +274,7 @@ export function serializeGsapAnimations( }); // fallow-ignore-next-line complexity const lines = sorted.map((anim) => { - const selector = JSON.stringify(anim.targetSelector); + const selector = scriptJson(anim.targetSelector); const props: Record = { ...anim.properties }; if (anim.duration !== undefined) props.duration = anim.duration; if (anim.ease) props.ease = anim.ease; @@ -288,7 +288,7 @@ export function serializeGsapAnimations( propsStr = propsStr.slice(0, -2) + `, ${extrasStr} }`; } } - const posStr = JSON.stringify(anim.position); + const posStr = scriptJson(anim.position); switch (anim.method) { case "set": // A global set is a base `gsap.set` — off the timeline, no position arg. @@ -338,11 +338,25 @@ ${lines.join("\n")}${mediaSync}${postamble} `; } +/** `JSON.stringify` whose output cannot end, or open a comment in, the inline script it lands in. */ +export function scriptJson(value: unknown): string { + return String(JSON.stringify(value)).replace(/<(\/script|!--)/gi, "\\u003c$1"); +} + +const TWEEN_METHODS: ReadonlySet = new Set(["set", "to", "from", "fromTo"]); + +/** The method name, checked against the four tween methods because it is emitted as code. */ +export function tweenMethodCode(method: string): GsapMethod { + if (!TWEEN_METHODS.has(method)) + throw new TypeError(`Unsupported tween method: ${scriptJson(method)}`); + return method as GsapMethod; +} + export function serializeValue(value: unknown): string { if (typeof value === "string" && value.startsWith("__raw:")) { return value.slice(6); } - if (typeof value === "string") return JSON.stringify(value); + if (typeof value === "string") return scriptJson(value); return String(value); } @@ -353,7 +367,7 @@ export function plainPercentKey(percentage: number): string { } export function safeJsKey(key: string): string { - return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key); + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : scriptJson(key); } function serializeObject(obj: Record): string { @@ -603,6 +617,24 @@ export function resolveConversionProps( // ── Arc path serialization helpers (shared by recast + acorn writers) ───────── +/** Rejects a motion path whose coordinates or curviness are not numbers, since they are emitted as code. */ +export function assertMotionPathNumbers(config: { + waypoints: Array<{ x: number; y: number }>; + segments: ArcPathSegment[]; +}): void { + const points = [ + ...config.waypoints, + ...config.segments.flatMap((s) => [s.cp1, s.cp2].filter((p) => p !== undefined)), + ]; + const values = [ + ...points.flatMap((p): unknown[] => [p.x, p.y]), + ...config.segments.map((s): unknown => s.curviness ?? 1), + ]; + if (values.some((v) => typeof v !== "number")) { + throw new TypeError("Motion path coordinates and curviness must be numbers"); + } +} + function numericXY(props: Record): { x: number; y: number } | null { const vx = props.x; const vy = props.y; @@ -671,6 +703,7 @@ export function buildMotionPathObjectCode(config: { segments: ArcPathSegment[]; autoRotate: boolean | number; }): string { + assertMotionPathNumbers(config); const { waypoints, segments, autoRotate } = config; const arSuffix = autoRotateSuffix(autoRotate); // GSAP's simple `path` array supports only ONE scalar `curviness` for the whole diff --git a/packages/parsers/src/gsapWriter.scriptContext.test.ts b/packages/parsers/src/gsapWriter.scriptContext.test.ts new file mode 100644 index 0000000000..c2fdb29c67 --- /dev/null +++ b/packages/parsers/src/gsapWriter.scriptContext.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import * as acornWriter from "./gsapWriterAcorn.js"; +import * as recastWriter from "./gsapParser.js"; +import { parseGsapScript } from "./gsapParser.js"; +import type { GsapAnimation } from "./gsapSerialize.js"; + +const SCRIPT = `var tl = gsap.timeline({ paused: true }); +tl.to("#box", { opacity: 1, duration: 1 }, 0);`; +const CLOSER = "