Skip to content

Write HTML. Render video. Built for agents.

fix(lint): flag an id override written with reduced-specificity selector forms (#3871)

miga-heygen9afafa79ec13
diff --git a/packages/lint/src/rules/core.test.ts b/packages/lint/src/rules/core.test.ts
index 5cef1f332d..beb7f39449 100644
--- a/packages/lint/src/rules/core.test.ts
+++ b/packages/lint/src/rules/core.test.ts
@@ -1068,6 +1068,80 @@ describe("core rules", () => {
});
});
+ describe("id_override_reduced_specificity", () => {
+ const comp = (css: string) => `
+<html><head><style>${css}</style></head><body>
+ <div id="root" data-composition-id="main" data-width="1920" data-height="1080">
+ <div class="parent"><div id="line1" class="row">text</div></div>
+ </div>
+ <script>window.__timelines = { main: gsap.timeline({ paused: true }) };</script>
+</body></html>`;
+
+ it("warns when an attribute selector on id sets a position property", async () => {
+ const result = await lintHyperframeHtml(
+ comp(`.parent .row { position: absolute; left: 0; } [id="line1"] { left: 40px; }`),
+ );
+ const finding = result.findings.find((f) => f.code === "id_override_reduced_specificity");
+ expect(finding).toBeDefined();
+ expect(finding?.severity).toBe("warning");
+ expect(finding?.selector).toBe(`[id="line1"]`);
+ expect(finding?.fixHint).toContain("`#line1`");
+ });
+
+ it("warns when a :where()-wrapped id selector sets a position property", async () => {
+ const result = await lintHyperframeHtml(
+ comp(`.parent .row { position: absolute; top: 0; } :where(#line1) { top: 20px; }`),
+ );
+ const finding = result.findings.find((f) => f.code === "id_override_reduced_specificity");
+ expect(finding).toBeDefined();
+ expect(finding?.selector).toBe(`:where(#line1)`);
+ });
+
+ it("does not flag a bare #id selector, which always wins regardless of specificity", async () => {
+ const result = await lintHyperframeHtml(
+ comp(`.parent .row { position: absolute; left: 0; } #line1 { left: 40px; }`),
+ );
+ expect(
+ result.findings.find((f) => f.code === "id_override_reduced_specificity"),
+ ).toBeUndefined();
+ });
+
+ it("hints an escaped #id for a digit-leading id, where a bare #01-intro is invalid CSS", async () => {
+ const result = await lintHyperframeHtml(
+ comp(`.parent .row { position: absolute; left: 0; } [id="01-intro"] { left: 40px; }`),
+ );
+ const finding = result.findings.find((f) => f.code === "id_override_reduced_specificity");
+ expect(finding?.fixHint).toContain("`#\\30 1-intro`");
+ });
+
+ it("does not flag prefix-matching id selectors or !important position overrides", async () => {
+ const result = await lintHyperframeHtml(
+ comp(
+ `[id^="line"] { top: 0; } [id*="ine"] { left: 0; } [id="line1"] { left: 40px !important; }`,
+ ),
+ );
+ expect(
+ result.findings.find((f) => f.code === "id_override_reduced_specificity"),
+ ).toBeUndefined();
+ });
+
+ it("does not flag a compound that also carries a bare #id, or a nested rule's position", async () => {
+ const result = await lintHyperframeHtml(
+ comp(`#line1[id="line1"] { left: 40px; } [id="root"] { color: red; .row { left: 0; } }`),
+ );
+ expect(
+ result.findings.find((f) => f.code === "id_override_reduced_specificity"),
+ ).toBeUndefined();
+ });
+
+ it("does not flag an attribute selector on id for a non-position property", async () => {
+ const result = await lintHyperframeHtml(comp(`[id="line1"] { color: red; }`));
+ expect(
+ result.findings.find((f) => f.code === "id_override_reduced_specificity"),
+ ).toBeUndefined();
+ });
+ });
+
describe("unclosed_tag_swallowed_element", () => {
it("flags an <img> tag whose unclosed start tag swallows a nested <div> as bogus attribute text", async () => {
const html = compositionWithBodyPrefix(
diff --git a/packages/lint/src/rules/core.ts b/packages/lint/src/rules/core.ts
index e634afe968..df942c84a1 100644
--- a/packages/lint/src/rules/core.ts
+++ b/packages/lint/src/rules/core.ts
@@ -103,16 +103,22 @@ function resolvedRuleSelectors(rule: postcss.Rule): string[] {
);
}
+// The rightmost compound: the nodes that match the styled element itself.
+function rightmostCompoundNodes(selectorNode: selectorParser.Selector): selectorParser.Node[] {
+ const subject: selectorParser.Node[] = [];
+ selectorNode.each((node) => {
+ if (node.type === "combinator") subject.length = 0;
+ else subject.push(node);
+ });
+ return subject;
+}
+
function selectorAliasesRuntimeHiddenStyle(selector: string): boolean {
let unsafe = false;
try {
selectorParser((root) => {
root.each((selectorNode) => {
- const subject: selectorParser.Node[] = [];
- selectorNode.each((node) => {
- if (node.type === "combinator") subject.length = 0;
- else subject.push(node);
- });
+ const subject = rightmostCompoundNodes(selectorNode);
const hostScoped = subject.some(
(node) =>
@@ -142,6 +148,69 @@ function selectorAliasesRuntimeHiddenStyle(selector: string): boolean {
return unsafe;
}
+const POSITION_PROPERTIES = new Set(["left", "top", "right", "bottom", "inset"]);
+
+function weakIdOf(node: selectorParser.Node): string | null {
+ if (node.type === "attribute" && node.attribute.toLowerCase() === "id") {
+ return node.operator === "=" && node.value ? node.value : null;
+ }
+ if (node.type !== "pseudo" || node.value.toLowerCase() !== ":where") return null;
+ const inner = node.nodes.flatMap((option) => option.nodes).find((n) => n.type === "id");
+ return inner ? inner.value : null;
+}
+
+// The id a subject targets only via `[id="x"]` or `:where(#x)`, which carry class-level or zero specificity
+// and so lose to a compound class rule like `.parent .row`. A bare `#id` never does.
+function reducedSpecificityId(selector: string): string | null {
+ let matched: string | null = null;
+ try {
+ selectorParser((root) => {
+ root.each((selectorNode) => {
+ const subject = rightmostCompoundNodes(selectorNode);
+ if (subject.some((node) => node.type === "id")) return;
+ for (const node of subject) matched = weakIdOf(node) ?? matched;
+ });
+ }).processSync(selector);
+ } catch {
+ return null;
+ }
+ return matched;
+}
+
+// `#id` with the characters a bare id selector cannot hold (a leading digit, punctuation) hex-escaped.
+function cssIdSelector(id: string): string {
+ return `#${id.replace(/[^a-zA-Z0-9_-]|^-?\d/g, (match) =>
+ Array.from(match, (char) => `\\${char.codePointAt(0)?.toString(16)} `).join(""),
+ )}`;
+}
+
+function reducedSpecificityIdFindings(
+ rule: postcss.Rule,
+ reported: Set<string>,
+): HyperframeLintFinding[] {
+ const positionProps = rule.nodes.flatMap((node) =>
+ node.type === "decl" && !node.important && POSITION_PROPERTIES.has(node.prop.toLowerCase())
+ ? [node.prop]
+ : [],
+ );
+ if (positionProps.length === 0) return [];
+ const findings: HyperframeLintFinding[] = [];
+ for (const selector of resolvedRuleSelectors(rule)) {
+ const id = reported.has(selector) ? null : reducedSpecificityId(selector);
+ if (id === null) continue;
+ reported.add(selector);
+ findings.push({
+ code: "id_override_reduced_specificity",
+ severity: "warning",
+ message: `Selector "${selector}" sets ${positionProps.join("/")} through [id=...] or :where(#id), which has class-level or zero specificity, so a compound class rule (e.g. ".parent .row") on the same element can silently win over this override.`,
+ selector,
+ fixHint: `Use \`${cssIdSelector(id)}\` instead; id specificity beats any selector built only from classes.`,
+ snippet: truncateSnippet(rule.toString()),
+ });
+ }
+ return findings;
+}
+
function ruleForcesOpacityZero(rule: postcss.Rule): boolean {
let forcesOpacityZero = false;
rule.walkDecls(/^opacity$/i, (declaration) => {
@@ -501,6 +570,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
const findings: HyperframeLintFinding[] = [];
const reportedRepeatedIds = new Set<string>();
const reportedHiddenStyleSelectors = new Set<string>();
+ const reportedReducedIdSelectors = new Set<string>();
for (const style of styles) {
let root: postcss.Root;
try {
@@ -521,6 +591,7 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
}
root.walkRules((rule) => {
const forcesOpacityZero = ruleForcesOpacityZero(rule);
+ findings.push(...reducedSpecificityIdFindings(rule, reportedReducedIdSelectors));
for (const selector of resolvedRuleSelectors(rule)) {
const repeatedId = repeatedDescendantId(selector);
if (repeatedId && !reportedRepeatedIds.has(repeatedId)) {