refactor(frontend): parse SFC styles with PostCSS, resolve the lib boundary (simplify)

- Style rules walk a PostCSS AST parsed once per file instead of
  hand-rolled declaration, @media and comment regexes. postcss becomes a
  direct devDependency at the version already in the lockfile.
- The src/v2/lib boundary uses import-x/no-restricted-paths, so aliases
  and relative imports resolve to the same zones. The resolver now knows
  .d.ts so the emitter types match.
- typescript-eslint's eslintRecommended applies to .vue in place of a
  single no-undef override.
- A reportAt helper replaces the per-rule loc boilerplate, and sfc()
  carries the test filename.
- The Trunk no-emdash linter runs batched.
- CLAUDE.md and address-bot-reviews point to review-polish instead of
  repeating the encode-a-check guidance.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-26 10:31:43 -04:00
parent 48f2d4574e
commit 1c2a60a776
16 changed files with 163 additions and 190 deletions

View File

@@ -91,10 +91,8 @@ undo a behaviour the maintainer asked for is a decline, with that intent as the
reason. Repo rules are a valid source: Greptile enforces the comment discipline
from `CLAUDE.md` and `review-polish`, and those findings stand.
For every valid finding, ask whether a static check could have caught it. If it
is pattern-shaped (a banned import, character, CSS value, or SFC shape), name
the stock or `frontend/eslint-plugin-romm/` rule as a follow-up in the reply. A
bot catching the same thing twice is a missing rule.
A valid finding that is pattern-shaped is a missing check: name one as a
follow-up in the reply (see `review-polish`, "Encode what you fixed twice").
Suggestion blocks are a starting point, not a patch to apply blindly. Check they
are complete and not duplicating a call a neighbouring branch already makes.

View File

@@ -92,6 +92,7 @@ lint:
" - Replace the em dash with a comma, parentheses, or a separate sentence." }'
${target}
success_codes: [0]
batch: true
- name: eslint
files:
- javascript

View File

@@ -66,8 +66,8 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha
**Tests travel with code.** New logic gets a test; new endpoints get endpoint tests; new v2 primitives get a Storybook story (+ `play()` if interactive).
**Verify before handoff.** Don't say "done" on UI work without testing it in the browser in both themes and all input modalities. See `review-polish`.
**English first.** Outside of language files, all code, comments, identifiers, `.md` files, and commit/PR messages are in English.
**No em-dashes.** Never use em-dashes (U+2014) when writing comments or text. Use commas, parentheses, or separate sentences instead. ESLint (`romm/no-emdash-in-comment`) checks comments under `frontend/src/v2`, and Trunk's `no-emdash` checks Markdown and Python comments. An em-dash string literal is code (an empty-value glyph) and stays allowed.
**Prefer a check to a model review.** A mechanical rule (an import, a character, a CSS pattern, an SFC shape) belongs in ESLint, `tsconfig`, or Trunk. When a review finding repeats, propose the stock or `frontend/eslint-plugin-romm/` rule as a named follow-up rather than growing the current PR.
**No em-dashes.** Never use em-dashes (U+2014) when writing comments or text. Use commas, parentheses, or separate sentences instead. An em-dash string literal is code (an empty-value glyph) and stays allowed.
**Prefer a check to a model review.** A mechanical rule (an import, a character, a CSS pattern, an SFC shape) belongs in ESLint, `tsconfig`, or Trunk. When a review finding repeats, propose a check as a named follow-up; see `review-polish`.
**Keep comments short.** Comments should be concise, and focus on the "why" rather than the "what" (the code itself is the "what"). A comment is one or two lines; a docstring is one sentence plus `Args:`/`Returns:` when the signature needs it. Three or more lines of prose means you are explaining, not commenting. See `review-polish` for what to cut.
**Don't restate the code.** The code is self-documenting, so skip comments that narrate what a reader can already see (which button sits where, that something is disabled when empty, obvious ordering). Comment only non-obvious "why" that the code can't convey on its own.
**One home per value.** Before declaring a constant, type, limit, regex, or store getter, search for an existing one and import it. Validation limits live on the model and are imported by endpoints; a type lives in the component that owns it and is exported. Don't add a near-duplicate that differs only by sorting, and don't invent an identity scheme where a foreign key already exists.

View File

@@ -1,9 +1,7 @@
// @ts-check
import { sfcStyleBlocks } from "../utils/sfcStyles.js";
import { reportAt } from "../utils/report.js";
import { rangeOf, sfcStyleRoots } from "../utils/sfcStyles.js";
// A declaration follows `{`, `;` or a nested block's `}` and ends at `;` or
// `}`. A selector ends at `{`, so `a:not(#abc) {` is never read as a value.
const DECLARATION = /(?<=[{;}]\s*)(--[\w-]+|[a-z-]+)\s*:([^;{}]*)(?=[;}])/gi;
const URL_OR_STRING = /url\([^)]*\)|"[^"]*"|'[^']*'/gi;
const COLOR_LITERAL =
/#[0-9a-f]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|device-cmyk)\(/gi;
@@ -25,27 +23,26 @@ export default {
create(context) {
return {
Program() {
const { sourceCode } = context;
for (const block of sfcStyleBlocks(context)) {
for (const decl of block.text.matchAll(DECLARATION)) {
const value = decl[2];
for (const block of sfcStyleRoots(context)) {
block.root.walkDecls((decl) => {
const value = decl.raws.value?.raw ?? decl.value;
const valueStart =
block.start + (decl.index ?? 0) + decl[0].length - value.length;
rangeOf(block, decl)[0] +
decl.prop.length +
(decl.raws.between ?? "").length;
const scanned = value.replace(URL_OR_STRING, (u) =>
" ".repeat(u.length),
);
for (const hit of scanned.matchAll(COLOR_LITERAL)) {
const index = valueStart + (hit.index ?? 0);
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(index + hit[0].length),
},
messageId: "colorLiteral",
data: { literal: hit[0] },
});
reportAt(
context,
valueStart + (hit.index ?? 0),
hit[0].length,
"colorLiteral",
{ literal: hit[0] },
);
}
}
});
}
},
};

View File

@@ -8,27 +8,24 @@ const error = (literal: string) => ({
ruleTester.run("no-color-literal", rule, {
valid: [
{ code: sfc(".a { color: var(--r-color-fg); }"), filename: "A.vue" },
sfc(".a { color: var(--r-color-fg); }"),
{
code: sfc(
...sfc(
".a { box-shadow: 0 1px 2px color-mix(in srgb, black 40%, transparent); }",
),
filename: "A.vue",
},
{
code: sfc(
...sfc(
".a { background: color-mix(in srgb, var(--r-color-bg) 60%, transparent); }",
),
filename: "A.vue",
},
{ code: sfc(".a:not(#abc) { color: currentColor; }"), filename: "A.vue" },
{ code: sfc("#fade { fill: url(#fade); }"), filename: "A.vue" },
sfc(".a:not(#abc) { color: currentColor; }"),
sfc("#fade { fill: url(#fade); }"),
{
code: sfc(".a {\n color: red;\n li:not(#abc) { opacity: 1; }\n}"),
filename: "A.vue",
...sfc(".a {\n color: red;\n li:not(#abc) { opacity: 1; }\n}"),
},
{ code: sfc('.a::before { content: "#123"; }'), filename: "A.vue" },
{ code: sfc("/* was #fff */\n.a { color: white; }"), filename: "A.vue" },
sfc('.a::before { content: "#123"; }'),
sfc("/* was #fff */\n.a { color: white; }"),
{ code: 'const fill = "#ffffff";' },
{
code: '<script setup lang="ts">const c = "rgba(0,0,0,.5)";</script>\n<template><div /></template>\n',
@@ -37,50 +34,39 @@ ruleTester.run("no-color-literal", rule, {
],
invalid: [
{
code: sfc(".a { color: #fff; }"),
filename: "A.vue",
...sfc(".a { color: #fff; }"),
errors: [error("#fff")],
},
{
code: sfc(".a { --r-color-fg: #ffffff; }"),
filename: "A.vue",
...sfc(".a { --r-color-fg: #ffffff; }"),
errors: [error("#ffffff")],
},
{
code: sfc(".a { text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7); }"),
filename: "A.vue",
...sfc(".a { text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7); }"),
errors: [error("rgba(")],
},
{
code: sfc(
".a { color: hsl(0 0% 100%); border-color: oklch(70% 0.1 200); }",
),
filename: "A.vue",
...sfc(".a { color: hsl(0 0% 100%); border-color: oklch(70% 0.1 200); }"),
errors: [error("hsl("), error("oklch(")],
},
{
code: sfc(".a { color: color(display-p3 1 0 0); }"),
filename: "A.vue",
...sfc(".a { color: color(display-p3 1 0 0); }"),
errors: [error("color(")],
},
{
code: sfc(".a { color: device-cmyk(0 81% 81% 30%); }"),
filename: "A.vue",
...sfc(".a { color: device-cmyk(0 81% 81% 30%); }"),
errors: [error("device-cmyk(")],
},
{
code: sfc(".a { background: linear-gradient(#000, #111); }"),
filename: "A.vue",
...sfc(".a { background: linear-gradient(#000, #111); }"),
errors: [error("#000"), error("#111")],
},
{
code: sfc(".a {\n color: #abc;\n}"),
filename: "A.vue",
...sfc(".a {\n color: #abc;\n}"),
errors: [{ ...error("#abc"), line: 5, column: 10 }],
},
{
code: sfc(".a {\n @media print { display: none; }\n color: #fff;\n}"),
filename: "A.vue",
...sfc(".a {\n @media print { display: none; }\n color: #fff;\n}"),
errors: [{ ...error("#fff"), line: 6 }],
},
{

View File

@@ -1,5 +1,6 @@
// @ts-check
import { sfcFragment, sfcStyleCommentRanges } from "../utils/sfcStyles.js";
import { reportAt } from "../utils/report.js";
import { rangeOf, sfcFragment, sfcStyleRoots } from "../utils/sfcStyles.js";
const EM_DASH = "—";
@@ -15,7 +16,11 @@ function commentRanges(context) {
if (c.range) ranges.push(c.range);
}
for (const c of sfcFragment(context)?.comments ?? []) ranges.push(c.range);
ranges.push(...sfcStyleCommentRanges(context));
for (const block of sfcStyleRoots(context)) {
block.root.walkComments((c) => {
ranges.push(rangeOf(block, c));
});
}
return ranges;
}
@@ -36,21 +41,13 @@ export default {
create(context) {
return {
Program() {
const { sourceCode } = context;
const { text } = sourceCode;
const { text } = context.sourceCode;
if (!text.includes(EM_DASH)) return;
for (const [start, end] of commentRanges(context)) {
const comment = text.slice(start, end);
let offset = comment.indexOf(EM_DASH);
while (offset !== -1) {
const index = start + offset;
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(index + 1),
},
messageId: "emDash",
});
reportAt(context, start + offset, 1, "emDash");
offset = comment.indexOf(EM_DASH, offset + 1);
}
}

View File

@@ -28,7 +28,7 @@ ruleTester.run("no-emdash-in-comment", rule, {
code: '<script setup lang="ts"></script>\n<template><RTag text="—" /></template>\n',
filename: "A.vue",
},
{ code: sfc('.a::after { content: "—"; }'), filename: "A.vue" },
sfc('.a::after { content: "—"; }'),
],
invalid: [
{
@@ -62,8 +62,7 @@ ruleTester.run("no-emdash-in-comment", rule, {
errors: [{ ...error, line: 2 }],
},
{
code: sfc('/* Glass — dark */\n.a { content: "—"; }'),
filename: "A.vue",
...sfc('/* Glass — dark */\n.a { content: "—"; }'),
errors: [{ ...error, line: 4 }],
},
],

View File

@@ -1,7 +1,7 @@
// @ts-check
import { sfcStyleBlocks } from "../utils/sfcStyles.js";
import { reportAt } from "../utils/report.js";
import { rangeOf, sfcStyleRoots } from "../utils/sfcStyles.js";
const MEDIA_RULE = /@media\b([^{;]*)/gi;
// Whatever is left after removing these is a condition the rule rejects.
const ALLOWED_PARTS =
/\(\s*prefers-reduced-motion\b[^)]*\)|\b(?:print|screen|all|only|not|and|or)\b|[\s,]/gi;
@@ -23,21 +23,17 @@ export default {
create(context) {
return {
Program() {
const { sourceCode } = context;
for (const block of sfcStyleBlocks(context)) {
for (const rule of block.text.matchAll(MEDIA_RULE)) {
if (rule[1].replace(ALLOWED_PARTS, "") === "") continue;
const index = block.start + (rule.index ?? 0);
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(
index + rule[0].trimEnd().length,
),
},
messageId: "layoutMedia",
});
}
for (const block of sfcStyleRoots(context)) {
block.root.walkAtRules("media", (rule) => {
if (rule.params.replace(ALLOWED_PARTS, "") === "") return;
const prelude = `@${rule.name}${rule.raws.afterName ?? ""}${rule.params}`;
reportAt(
context,
rangeOf(block, rule)[0],
prelude.length,
"layoutMedia",
);
});
}
},
};

View File

@@ -6,60 +6,50 @@ const error = { messageId: "layoutMedia" };
ruleTester.run("no-layout-media-query", rule, {
valid: [
{
code: sfc(
...sfc(
"@media (prefers-reduced-motion: reduce) { .a { transition: none; } }",
),
filename: "A.vue",
},
{ code: sfc("@media print { .a { display: none; } }"), filename: "A.vue" },
sfc("@media print { .a { display: none; } }"),
{
code: sfc(
...sfc(
"@media not print and (prefers-reduced-motion: no-preference) { .a { opacity: 1; } }",
),
filename: "A.vue",
},
{
code: sfc(
...sfc(
"@media (prefers-reduced-motion: reduce) or print { .a { gap: 0; } }",
),
filename: "A.vue",
},
{
code: sfc('html[data-bp~="xs"] .a { display: none; }'),
filename: "A.vue",
...sfc('html[data-bp~="xs"] .a { display: none; }'),
},
{
code: sfc("/* @media (max-width: 600px) */\n.a { color: red; }"),
filename: "A.vue",
...sfc("/* @media (max-width: 600px) */\n.a { color: red; }"),
},
{ code: 'const q = "@media (max-width: 600px)";' },
],
invalid: [
{
code: sfc("@media (max-width: 600px) { .a { display: none; } }"),
filename: "A.vue",
...sfc("@media (max-width: 600px) { .a { display: none; } }"),
errors: [{ ...error, line: 4, column: 1 }],
},
{
code: sfc("@media screen and (min-width: 960px) { .a { gap: 0; } }"),
filename: "A.vue",
...sfc("@media screen and (min-width: 960px) { .a { gap: 0; } }"),
errors: [error],
},
{
code: sfc(
...sfc(
"@media (prefers-reduced-motion: reduce), (width < 600px) { .a { gap: 0; } }",
),
filename: "A.vue",
errors: [error],
},
{
code: sfc("@media (hover: hover) { .a:hover { opacity: 1; } }"),
filename: "A.vue",
...sfc("@media (hover: hover) { .a:hover { opacity: 1; } }"),
errors: [error],
},
{
code: sfc(".a { @media (max-width: 600px) { gap: 0; } }"),
filename: "A.vue",
...sfc(".a { @media (max-width: 600px) { gap: 0; } }"),
errors: [error],
},
],

View File

@@ -17,6 +17,9 @@ export const ruleTester = new RuleTester({
},
});
export function sfc(style: string): string {
return `<script setup lang="ts"></script>\n<template><div /></template>\n<style scoped>\n${style}\n</style>\n`;
export function sfc(style: string): { code: string; filename: string } {
return {
code: `<script setup lang="ts"></script>\n<template><div /></template>\n<style scoped>\n${style}\n</style>\n`,
filename: "A.vue",
};
}

View File

@@ -0,0 +1,21 @@
// @ts-check
/**
* Report a problem over `length` characters starting at a source offset.
* @param {import("eslint").Rule.RuleContext} context
* @param {number} index
* @param {number} length
* @param {string} messageId
* @param {Record<string, string>} [data]
*/
export function reportAt(context, index, length, messageId, data) {
const { sourceCode } = context;
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(index + length),
},
messageId,
data,
});
}

View File

@@ -1,11 +1,13 @@
// @ts-check
import postcss from "postcss";
/**
* @typedef {{ text: string, start: number }} StyleBlock
* @typedef {{ root: import("postcss").Root, start: number }} StyleRoot
* @typedef {{ type: string, name?: string, range: [number, number], children?: SfcNode[], comments?: SfcNode[] }} SfcNode
*/
const CSS_COMMENT = /\/\*[\s\S]*?\*\//g;
/** @type {WeakMap<import("eslint").SourceCode, StyleRoot[]>} */
const parsed = new WeakMap();
/**
* The SFC document fragment, or null for files that are not SFCs.
@@ -21,52 +23,44 @@ export function sfcFragment(context) {
}
/**
* The raw text and offset of each `<style>` block in an SFC.
* Each `<style>` block of an SFC parsed once per file, with its source offset.
* @param {import("eslint").Rule.RuleContext} context
* @returns {StyleBlock[]}
* @returns {StyleRoot[]}
*/
function rawStyleBlocks(context) {
const fragment = sfcFragment(context);
if (!fragment?.children) return [];
export function sfcStyleRoots(context) {
const { sourceCode } = context;
const cached = parsed.get(sourceCode);
if (cached) return cached;
/** @type {StyleBlock[]} */
const blocks = [];
for (const node of fragment.children) {
/** @type {StyleRoot[]} */
const roots = [];
for (const node of sfcFragment(context)?.children ?? []) {
if (node.type !== "VElement" || node.name !== "style") continue;
const body = node.children?.[0];
if (!body) continue;
const [start, end] = body.range;
blocks.push({ text: context.sourceCode.text.slice(start, end), start });
}
return blocks;
}
/**
* The `<style>` blocks of a Vue SFC (none for other files), with comments
* blanked out so offsets still map to the source.
* @param {import("eslint").Rule.RuleContext} context
* @returns {StyleBlock[]}
*/
export function sfcStyleBlocks(context) {
return rawStyleBlocks(context).map((block) => ({
start: block.start,
text: block.text.replace(CSS_COMMENT, (c) => c.replace(/[^\n]/g, " ")),
}));
}
/**
* Absolute source ranges of the CSS comments in an SFC's `<style>` blocks.
* @param {import("eslint").Rule.RuleContext} context
* @returns {[number, number][]}
*/
export function sfcStyleCommentRanges(context) {
/** @type {[number, number][]} */
const ranges = [];
for (const block of rawStyleBlocks(context)) {
for (const match of block.text.matchAll(CSS_COMMENT)) {
const start = block.start + (match.index ?? 0);
ranges.push([start, start + match[0].length]);
try {
roots.push({
root: postcss.parse(sourceCode.text.slice(start, end)),
start,
});
} catch {
// Vite reports CSS it cannot parse, so the lint rules skip the block.
}
}
return ranges;
parsed.set(sourceCode, roots);
return roots;
}
/**
* Absolute source range of a node inside a parsed style block.
* @param {StyleRoot} block
* @param {import("postcss").AnyNode} node
* @returns {[number, number]}
*/
export function rangeOf(block, node) {
return [
block.start + (node.source?.start?.offset ?? 0),
block.start + (node.source?.end?.offset ?? 0),
];
}

View File

@@ -97,7 +97,7 @@ export default tseslint.config(
"import-x/resolver-next": [
createTypeScriptImportResolver({
project: "./tsconfig.json",
extensions: [".ts", ".tsx", ".vue", ".js", ".mjs", ".json"],
extensions: [".ts", ".d.ts", ".tsx", ".vue", ".js", ".mjs", ".json"],
}),
],
},
@@ -114,12 +114,8 @@ export default tseslint.config(
],
},
},
{
// vue-tsc checks undefined names; without type info this rule misreads
// DOM type names (`EventListener`, `ScrollBehavior`) as undefined.
files: ["**/*.vue"],
rules: { "no-undef": "off" },
},
// typescript-eslint scopes these TS-redundant core rules to .ts files only.
{ ...tseslint.configs.eslintRecommended, files: ["**/*.vue"] },
{
// Frozen v1: two cycles between the console theme helpers predate the
// rule and cannot be refactored under the freeze.
@@ -141,55 +137,52 @@ export default tseslint.config(
message:
"Primitives take text via props, slots, or useChromeLabels().",
},
{
name: "@/locales",
message:
"Primitives take text via props, slots, or useChromeLabels().",
},
{ name: "axios", message: "Primitives do not fetch." },
{
name: "vue-router",
importNames: ["useRouter", "useRoute"],
message: "Primitives accept a RouterLink `to`, not the router.",
},
{
name: "@/plugins/router",
message: "Primitives accept a RouterLink `to`, not the router.",
},
],
patterns: [
},
],
// Matches resolved files, so every alias and relative spelling is covered.
"import-x/no-restricted-paths": [
"error",
{
zones: [
{
group: [
"@/services/*",
"@/services/**",
"@/stores/*",
"@/stores/**",
],
from: ["./src/services", "./src/stores"],
message:
"Primitives do not use services or stores; move this to a shared or feature composite.",
},
{
group: ["@/__generated__", "@/__generated__/**"],
from: "./src/__generated__",
message:
"Backend types are product domain; primitives take generic props.",
},
{
group: ["@/types/emitter"],
from: "./src/types/emitter.d.ts",
message: "Primitives do not use the emitter.",
},
{
group: [
"@/v2/components/**",
"@v2/components/**",
"@/v2/composables/usePlatformIconCache",
"@/v2/composables/usePlatformIconCache/**",
"@v2/composables/usePlatformIconCache",
"@v2/composables/usePlatformIconCache/**",
from: "./src/locales",
message:
"Primitives take text via props, slots, or useChromeLabels().",
},
{
from: "./src/plugins/router.ts",
message: "Primitives accept a RouterLink `to`, not the router.",
},
{
from: [
"./src/v2/components",
"./src/v2/composables/usePlatformIconCache",
],
message:
"Primitives cannot depend on composites or domain composables.",
},
],
].map((zone) => ({ target: "./src/v2/lib", ...zone })),
},
],
},

View File

@@ -61,6 +61,7 @@
"globals": "^16.0.0",
"happy-dom": "^20.9.0",
"openapi-typescript-codegen": "^0.29.0",
"postcss": "^8.5.23",
"storybook": "^10.2.19",
"tsx": "^4.21.0",
"typescript": "^5.9.3",

View File

@@ -91,6 +91,7 @@
"globals": "^16.0.0",
"happy-dom": "^20.9.0",
"openapi-typescript-codegen": "^0.29.0",
"postcss": "^8.5.23",
"storybook": "^10.2.19",
"tsx": "^4.21.0",
"typescript": "^5.9.3",

View File

@@ -10,9 +10,5 @@
"checkJs": true,
"types": ["node"]
},
"include": [
"scripts/**/*.ts",
"eslint-plugin-romm/**/*.js",
"eslint-plugin-romm/**/*.ts"
]
"include": ["scripts/**/*.ts", "eslint-plugin-romm"]
}