SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore(css-modules): add good practices for writing css module files (#11587)
Vinicius Lourençoed04ff09ff99
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.jsonindex 8589025af3..d72b1e5de3 100644--- a/frontend/.oxlintrc.json+++ b/frontend/.oxlintrc.json@@ -291,6 +291,8 @@// Prevents the usage of specific antd components in favor of our lib"signoz/no-signozhq-ui-barrel": "error",// Forces subpath imports (@signozhq/ui/<component>) instead of the eagerly-loaded barrel+ "signoz/no-css-module-bracket-access": "warn",+ // Prevents bracket access on CSS modules (styles['kebab-case']) which fails with camelCaseOnly config"no-restricted-globals": ["error",{diff --git a/frontend/.stylelintrc.cjs b/frontend/.stylelintrc.cjsindex 153deff96c..2fb044dca2 100644--- a/frontend/.stylelintrc.cjs+++ b/frontend/.stylelintrc.cjs@@ -2,9 +2,33 @@const path = require('path');module.exports = {- plugins: [path.join(__dirname, 'stylelint-rules/no-unsupported-asset-url.js')],+ plugins: [+ path.join(__dirname, 'stylelint-rules/no-unsupported-asset-url.js'),+ path.join(__dirname, 'stylelint-rules/css-modules/no-deep-nesting.js'),+ path.join(__dirname, 'stylelint-rules/css-modules/no-id-selectors.js'),+ path.join(+ __dirname,+ 'stylelint-rules/css-modules/no-bare-element-selectors.js',+ ),+ path.join(__dirname, 'stylelint-rules/css-modules/prefer-css-variables.js'),+ path.join(__dirname, 'stylelint-rules/css-modules/class-name-pattern.js'),+ ],customSyntax: 'postcss-scss',rules: {+ // Applies to all SCSS files'local/no-unsupported-asset-url': true,},+ overrides: [+ {+ // CSS module-specific rules+ files: ['**/*.module.scss'],+ rules: {+ 'local/no-deep-nesting': [true, { severity: 'warning' }],+ 'local/no-id-selectors': true,+ 'local/no-bare-element-selectors': true,+ 'local/prefer-css-variables': [true, { severity: 'warning' }],+ 'local/class-name-pattern': [true, { severity: 'warning' }],+ },+ },+ ],};diff --git a/frontend/AGENTS.md b/frontend/AGENTS.mdindex 32de46434c..b773695bdc 100644--- a/frontend/AGENTS.md+++ b/frontend/AGENTS.md@@ -23,6 +23,8 @@ You are operating within a constrained context window and strict system prompts.- Always add data-testid or testId (if supported) to critical/behavioral components like inputs, buttons, etc...- When creating test, these IDs should be used instead of finding by role.- Never create barrel files.+- When writing new css, prefer CSS Modules+ - Use ./docs/css-modules-guide.md as reference on how to write good CSS Modules.3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. You are FORBIDDEN from reporting a task as complete until you have:- Run `pnpm tsgo --noEmit`diff --git a/frontend/docs/css-modules-guide.md b/frontend/docs/css-modules-guide.mdnew file mode 100644index 0000000000..2114b436d1--- /dev/null+++ b/frontend/docs/css-modules-guide.md@@ -0,0 +1,513 @@+# CSS Modules Guide++## Checklist Before Committing++- [ ] All class names use camelCase in CSS+- [ ] State classes use `is-`/`has-` prefix (e.g., `isActive`, `hasError`)+- [ ] No bracket access (`styles['...']`) in JS unless verified+- [ ] No dynamic class lookup - use explicit variant maps instead+- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)+- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)+- [ ] No magic numbers - use `--spacing-*` tokens+- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens+- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides+- [ ] Global escapes only for third-party overrides+- [ ] No ID selectors+- [ ] No bare element selectors+- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions++## Config (vite.config.ts)++```ts+css: {+ modules: {+ localsConvention: 'camelCaseOnly',+ },+}+```++**Critical:** `camelCaseOnly` exports ONLY camelCase keys. Original kebab-case NOT accessible.++## Quick Reference++| CSS Class | JS Access | Works? | Preferred? |+|-----------|-----------|--------|----------------------------|+| `.alertHistory` | `styles.alertHistory` | Yes | Yes |+| `.alert-history` | `styles.alertHistory` | Yes | No, use `.alertHistory` |+| `.alert-history` | `styles['alert-history']` | NO - undefined | Never, use `.alertHistory` |++## Bad Patterns++### Class Naming++```scss+// BAD: Bracket access won't work+.my-class { }+// Then in JS: styles['my-class'] -> undefined++// BAD: Collision - both become same key+.alertHistory { }+.alert-history { } // -> styles.alertHistory (conflicts)++// BAD: Underscore inconsistency+.my_class { } // -> styles.myClass (confusing)++// GOOD: Direct camelCase+.alertHistory { }+.statsCard { }++// GOOD: State classes with is-/has- prefix+.isDisabled { }+.isActive { }+.hasError { }+.isLoading { }+```++### Nesting++```scss+// BAD: Deep nesting - specificity wars, hard to override+.container {+ .wrapper {+ .inner {+ .content { }+ }+ }+}++// BAD: Nesting creates separate classes you might not expect+.button {+ .icon { } // -> styles.icon (separate class, not scoped under .button)+}++// GOOD: Flat structure+.container { }+.containerWrapper { }+.containerContent { }++// GOOD: Nesting only for pseudo/states+.button {+ &:hover { }+ &:disabled { }+ &::before { }+}+```++### Global Escapes++```scss+// BAD: Overusing global+:global {+ .everything { }+ .in-here { }+ .is-global { }+}++// BAD: Global without necessity+:global(.myComponent) { } // defeats purpose of modules++// GOOD: Targeted global for third-party overrides+.container {+ :global(.ant-modal-content) {+ padding: 0;+ }+}+```++### Selectors++```scss+// BAD: ID selectors - not reusable+#myComponent { }++// BAD: Element selectors without scope+div { } // affects ALL divs in component++// BAD: Complex selectors+.container > div + span ~ p { }++// GOOD: Class-only selectors+.container { }+.title { }+```++### Variables & Values++```scss+// BAD: Hardcoded colors+.button {+ background: #1890ff;+ color: white;+}++// BAD: Magic numbers+.container {+ padding: 17px;+ margin-left: 43px;+}++// GOOD: Semantic tokens (theme-aware)+.button {+ background: var(--primary-background);+ color: var(--primary-foreground);+}++.card {+ background: var(--l2-background);+ color: var(--l2-foreground);+}++// GOOD: Spacing system+.container {+ padding: var(--spacing-4);+ margin-left: var(--spacing-5);+}+```++## Design Tokens (@signozhq/design-tokens)++Prefer semantic tokens over hardcoded values.++You can read the ./node_modules/@signozhq/design-tokens/dist/style.css to find complete list of available tokens.++### Spacing++```scss+// Spacing scale (index -> px):+// --spacing-0=0 --spacing-1=2 --spacing-2=4 --spacing-3=6 --spacing-4=8+// --spacing-5=10 --spacing-6=12 --spacing-7=14 --spacing-8=16 --spacing-10=20+// --spacing-12=24 --spacing-16=32 --spacing-20=40 --spacing-24=48 --spacing-32=64+// --spacing-40=80 --spacing-48=96 --spacing-56=112 --spacing-64=128+// (index != px; --spacing-2 is 4px, not 2px)+.container {+ padding: var(--spacing-4); // 8px+ gap: var(--spacing-6); // 12px+ margin-bottom: var(--spacing-8); // 16px+}++// Also available: --padding-* and --margin-* (rem-based)+// --padding-1 = 0.25rem, --padding-4 = 1rem, etc.+```++### Typography++```scss+// Font sizes (preferred)+.title {+ font-size: var(--periscope-font-size-large); // 18px+ font-size: var(--periscope-font-size-medium); // 16px+ font-size: var(--periscope-font-size-base); // 13px+ font-size: var(--periscope-font-size-small); // 11px+}++// Alternative scale (rem-based)+.heading {+ font-size: var(--font-size-xl); // 1.25rem+ font-size: var(--font-size-lg); // 1.125rem+ font-size: var(--font-size-base); // 1rem+ font-size: var(--font-size-sm); // 0.875rem+}++// Font weights+.bold {+ font-weight: var(--font-weight-semibold); // 600+ font-weight: var(--font-weight-medium); // 500+ font-weight: var(--font-weight-normal); // 400+}++// Line heights+.text {+ line-height: var(--line-height-20); // 20px+ line-height: var(--line-height-24); // 24px+}+```++### Colors (Prefer Semantic Tokens)++Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.++```scss+// BAD: Primitive tokens (fixed value across themes, won't swap on theme change)+.card {+ background: var(--bg-ink-400);+ color: var(--text-vanilla-100);+}++// GOOD: L1/L2/L3 tokens (theme-aware - swap automatically light/dark)+.card {+ background: var(--l1-background); // base layer+ color: var(--l1-foreground); // primary text+}++.panel {+ background: var(--l2-background); // elevated surface+ color: var(--l2-foreground); // secondary text+ border-color: var(--l2-border);+}++.nested {+ background: var(--l3-background); // nested/inset+ color: var(--l3-foreground); // tertiary text+}++// Hover states+.card:hover {+ background: var(--l1-background-hover);+ color: var(--l1-foreground-hover);+}++// Semantic action colors (also theme-aware)+.primary {+ background: var(--primary-background);+ color: var(--primary-foreground);+}++.danger {+ background: var(--danger-background);+ color: var(--danger-foreground);+}++.success {+ background: var(--success-background);+ color: var(--success-foreground);+}++.warning {+ background: var(--warning-background);+ color: var(--warning-foreground);+}++// Accent colors (for highlights, badges, etc.)+.accent {+ background: var(--accent-primary); // robin blue+ background: var(--accent-forest); // green+ background: var(--accent-cherry); // red+ background: var(--accent-amber); // yellow+}+```++**Token hierarchy:**+- Primitive tokens (`--bg-*`, `--text-*`, etc.) have fixed values across themes.+- Semantic tokens (L1/L2/L3, `--primary-*`, `--danger-*`, etc.) automatically swap based on theme.+- L1 = base/root layer+- L2 = elevated surfaces (cards, panels)+- L3 = nested/inset elements++## Overriding @signozhq/ui Components++Components expose CSS variables for customization.++You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.+Never write a override without confirm it exists.++Override via:++### Method 1: CSS Variables (Preferred)++Each component exposes `--<component>-<property>` variables:++```scss+// Override Button+.customButton {+ --button-background: var(--success-background);+ --button-border-radius: var(--radius-2);+ --button-padding: var(--spacing-4) var(--spacing-8);+ --button-font-size: var(--periscope-font-size-base);+}++// Override Input+.customInput {+ --input-height: 2.5rem;+ --input-border-color: var(--l2-border);+ --input-padding: var(--spacing-2) var(--spacing-6);+ --input-placeholder-color: var(--l3-foreground);+}++// Override nested parts+.customInput {+ --input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);+ --input-suffix-color: var(--accent-primary);+}+```++### Method 2: Data Attributes++Components use data attributes for variants/states. Target them for state-specific overrides:++```scss+// Target variant+.wrapper :global([data-variant="outlined"]) {+ --button-border-color: var(--accent-primary);+}++// Target size+.wrapper :global([data-size="sm"]) {+ --button-font-size: var(--periscope-font-size-small);+}++// Target color+.wrapper :global([data-color="destructive"]) {+ --button-background: var(--danger-background);+}++// Target state (Radix patterns)+.popover :global([data-state="open"]) {+ opacity: 1;+}++.tooltip :global([data-side="top"]) {+ margin-bottom: var(--spacing-2);+}+```++### Common Component CSS Variables++**Button:**+- `--button-background`, `--button-border-radius`, `--button-padding`+- `--button-font-size`, `--button-height`, `--button-gap`+- `--button-hover-background`, `--button-disabled-opacity`++**Input:**+- `--input-height`, `--input-border-color`, `--input-background`+- `--input-padding`, `--input-font-size`, `--input-placeholder-color`+- `--input-focus-outline-color`, `--input-hover-border-color`+- `--input-prefix-*`, `--input-suffix-*` for adornments++**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`++## Good Patterns++### Structure++```scss+// Flat, descriptive, component-scoped+.alertHistory { }+.alertHistoryHeader { }+.alertHistoryContent { }+.alertHistoryFooter { }++// State modifiers as separate classes+.alertHistory { }+.alertHistoryLoading { }+.alertHistoryEmpty { }+.alertHistoryError { }+```++### Composition++```scss+// GOOD: Composing styles+.baseButton {+ padding: var(--spacing-2) var(--spacing-4);+ border-radius: var(--radius-2);+}++.primaryButton {+ composes: baseButton;+ background: var(--primary-background);+}+```++### Pseudo Elements++```scss+.button {+ // States+ &:hover { opacity: 0.9; }+ &:focus { outline: 2px solid var(--ring); outline-offset: 2px; }+ &:disabled { opacity: 0.5; cursor: not-allowed; }++ // Pseudo elements+ &::before { content: ''; }+ &::after { content: ''; }+}+```++### Media Queries++```scss+.container {+ display: flex;+ flex-direction: column;++ @media (min-width: 768px) {+ flex-direction: row;+ }+}+```++### Keyframes (Local Scoping)++Without `:local()`, keyframe names are global and can clash across modules:++```scss+// BAD: Global keyframe - can conflict with other modules+@keyframes fadeIn {+ from { opacity: 0; }+ to { opacity: 1; }+}++// GOOD: Locally scoped keyframe+:local(@keyframes fadeIn) {+ from { opacity: 0; }+ to { opacity: 1; }+}++.modal {+ animation: fadeIn 200ms ease;+}+```++## JS Import Patterns++```tsx+// GOOD+import styles from './Component.module.scss';++<div className={styles.container}>+ <span className={styles.title}>Title</span>+</div>++// GOOD: Conditional classes+<div className={`${styles.button} ${isActive ? styles.buttonActive : ''}`}>++// GOOD: With clsx/classnames+<div className={clsx(styles.button, { [styles.buttonActive]: isActive })}>++// BAD: Bracket access (may be undefined)+<div className={styles['button-active']}> // undefined if CSS has .button-active++// BAD: String interpolation for class names+<div className={`${styles.button}-active`}> // won't work++// BAD: Dynamic class lookup - can't be statically analyzed+const cls = styles[`variant${props.type}`]; // Vite can't tree-shake or type-check++// GOOD: Explicit map for dynamic variants+const variantMap = {+ primary: styles.variantPrimary,+ secondary: styles.variantSecondary,+ ghost: styles.variantGhost,+};+const cls = variantMap[props.type];+```++## Lint Rules++### JS/TS (oxlint)++| Rule | Severity | Catches |+|------|----------|---------|+| `signoz/no-css-module-bracket-access` | warn | `styles['kebab-case']`, dynamic access |++### CSS/SCSS (stylelint)++| Rule | Severity | Catches |+|------|----------|---------|+| `local/no-deep-nesting` | warning | class nesting >3 levels (pseudo-classes/elements and parent-reference selectors `&.foo`, `&#bar` not counted; configurable via `maxDepth` secondary option) |+| `local/no-id-selectors` | error | `#id` selectors |+| `local/no-bare-element-selectors` | error | root-level `div`, `span` etc |+| `local/prefer-css-variables` | warning | hardcoded colors |+| `local/class-name-pattern` | warning | kebab-case, snake_case, PascalCase |++Run: `pnpm lint:styles` to check CSS modules.diff --git a/frontend/plugins/rules/no-css-module-bracket-access.mjs b/frontend/plugins/rules/no-css-module-bracket-access.mjsnew file mode 100644index 0000000000..45028db8fc--- /dev/null+++ b/frontend/plugins/rules/no-css-module-bracket-access.mjs@@ -0,0 +1,144 @@+/**+ * Rule: no-css-module-bracket-access+ *+ * Prevents bracket access on CSS module imports that may fail with camelCaseOnly config.+ *+ * With Vite's `localsConvention: 'camelCaseOnly'`, kebab-case class names are+ * converted to camelCase and the original key is NOT exported.+ *+ * This rule catches patterns like:+ * styles['my-class'] // BAD - undefined if CSS has .my-class+ * styles['myClass'] // OK but prefer dot notation+ * styles.myClass // GOOD+ *+ * Catches:+ * - Bracket access with kebab-case strings (always fails)+ * - Bracket access with any string literal (warn - prefer dot notation)+ * - Dynamic bracket access (warn - risky)+ */++const CSS_MODULE_IMPORT_NAMES = new Set([+ 'styles',+ 'classes',+ 'css',+ 'classNames',+]);++function looksLikeCssModuleImport(name) {+ // Common patterns: styles, componentStyles, alertHistoryStyles+ return (+ CSS_MODULE_IMPORT_NAMES.has(name) ||+ name.endsWith('Styles') ||+ name.endsWith('Classes') ||+ name.endsWith('Css')+ );+}++function isKebabCase(str) {+ return str.includes('-');+}++function isSnakeCase(str) {+ return str.includes('_');+}++export default {+ create(context) {+ return {+ MemberExpression(node) {+ // Only check bracket notation: styles['...']+ if (!node.computed) {+ return;+ }++ const object = node.object;+ if (object.type !== 'Identifier') {+ return;+ }++ // Check if this looks like a CSS module import+ if (!looksLikeCssModuleImport(object.name)) {+ return;+ }++ const property = node.property;++ // Dynamic access: styles[variable]+ if (property.type === 'Identifier') {+ context.report({+ node,+ message: `Dynamic CSS module access '${object.name}[${property.name}]' is risky. With 'camelCaseOnly' config, kebab-case keys don't exist. Use dot notation or verify the key exists.`,+ });+ return;+ }++ // Template literal: styles[\`...\`]+ if (property.type === 'TemplateLiteral') {+ context.report({+ node,+ message: `Template literal CSS module access is risky. With 'camelCaseOnly' config, kebab-case keys don't exist. Prefer dot notation.`,+ });+ return;+ }++ // Numeric / boolean / null literal: styles[0]. Not a class lookup; ignore.+ if (property.type === 'Literal' && typeof property.value !== 'string') {+ return;+ }++ // String literal: styles['...']+ if (property.type === 'Literal' && typeof property.value === 'string') {+ const className = property.value;++ // Kebab-case will definitely fail+ if (isKebabCase(className)) {+ context.report({+ node,+ message: `CSS module class '${className}' uses kebab-case which won't work with 'camelCaseOnly' config. Use '${object.name}.${toCamelCase(className)}' instead.`,+ });+ return;+ }++ // Snake_case is suspicious+ if (isSnakeCase(className)) {+ context.report({+ node,+ message: `CSS module class '${className}' uses snake_case which may not work as expected. Prefer camelCase: '${object.name}.${toCamelCase(className)}'.`,+ });+ return;+ }++ // Valid camelCase but using bracket notation - prefer dot+ if (/^[a-z][a-zA-Z0-9]*$/.test(className)) {+ context.report({+ node,+ message: `Prefer dot notation: '${object.name}.${className}' instead of '${object.name}['${className}']'.`,+ });+ }+ return;+ }++ // Catch-all for other dynamic expressions:+ // styles['prefix' + suffix] (BinaryExpression)+ // styles[isActive && 'foo'] (LogicalExpression)+ // styles[isActive ? 'a' : 'b'] (ConditionalExpression)+ // styles[fn()] (CallExpression)+ context.report({+ node,+ message: `Dynamic CSS module access on '${object.name}' is risky. With 'camelCaseOnly' config, kebab-case keys don't exist. Use dot notation or verify each key resolves to an exported camelCase class.`,+ });+ },+ };+ },+};++function toCamelCase(str) {+ return str+ .split(/[-_]/)+ .map((part, i) =>+ i === 0+ ? part.toLowerCase()+ : part.charAt(0).toUpperCase() + part.slice(1).toLowerCase(),+ )+ .join('');+}diff --git a/frontend/plugins/signoz.mjs b/frontend/plugins/signoz.mjsindex 2ee0b02002..5672157f6c 100644--- a/frontend/plugins/signoz.mjs+++ b/frontend/plugins/signoz.mjs@@ -11,6 +11,7 @@ import noUnsupportedAssetPattern from './rules/no-unsupported-asset-pattern.mjs'import noRawAbsolutePath from './rules/no-raw-absolute-path.mjs';import noAntdComponents from './rules/no-antd-components.mjs';import noSignozhqUiBarrel from './rules/no-signozhq-ui-barrel.mjs';+import noCssModuleBracketAccess from './rules/no-css-module-bracket-access.mjs';export default {meta: {@@ -23,5 +24,6 @@ export default {'no-raw-absolute-path': noRawAbsolutePath,'no-antd-components': noAntdComponents,'no-signozhq-ui-barrel': noSignozhqUiBarrel,+ 'no-css-module-bracket-access': noCssModuleBracketAccess,},};diff --git a/frontend/stylelint-rules/css-modules/class-name-pattern.js b/frontend/stylelint-rules/css-modules/class-name-pattern.jsnew file mode 100644index 0000000000..de1caa2c38--- /dev/null+++ b/frontend/stylelint-rules/css-modules/class-name-pattern.js@@ -0,0 +1,186 @@+/**+ * Stylelint rule: local/class-name-pattern+ *+ * Enforces camelCase class names in CSS modules.+ * With Vite's `localsConvention: 'camelCaseOnly'`, kebab-case is converted but+ * using camelCase directly avoids confusion.+ *+ * BAD:+ * .my-class { } // converted to myClass, but confusing+ * .my_class { } // converted to myClass, but confusing+ * .MyClass { } // PascalCase not conventional+ *+ * GOOD:+ * .myClass { }+ * .alertHistory { }+ * .statsCard { }+ */+import stylelint from 'stylelint';++const ruleName = 'local/class-name-pattern';++const messages = stylelint.utils.ruleMessages(ruleName, {+ kebabCase: (className) =>+ `Class "${className}" is not on camelCase. Use instead: "${toCamelCase(className)}".`,+ snakeCase: (className) =>+ `Class "${className}" is not on camelCase. Use instead: "${toCamelCase(className)}".`,+ pascalCase: (className) =>+ `Class "${className}" is not on camelCase. Use instead: "${className.charAt(0).toLowerCase() + className.slice(1)}".`,+});++function toCamelCase(str) {+ return str+ .split(/[-_]/)+ .map((part, i) =>+ i === 0+ ? part.toLowerCase()+ : part.charAt(0).toUpperCase() + part.slice(1).toLowerCase(),+ )+ .join('');+}++function isKebabCase(str) {+ return str.includes('-');+}++function isSnakeCase(str) {+ return str.includes('_');+}++function isPascalCase(str) {+ return /^[A-Z][a-zA-Z0-9]*$/.test(str);+}++const CLASS_PATTERN = /\.([a-zA-Z_][a-zA-Z0-9_-]*)/g;++const DEFAULT_THIRD_PARTY_PREFIXES = [+ 'ant-', // Ant Design+ 'rc-', // rc-components (Ant Design internals)+ 'recharts-', // Recharts+ 'uplot-', // uPlot+ 'u-', // uPlot legacy+ 'leaflet-', // Leaflet+ 'monaco-', // Monaco editor+ 'react-resizable', // react-resizable+ 'cm-', // CodeMirror+];++// Bare `:global { ... }` block (no parens) makes all descendants global.+// `:global(.foo)` is a per-selector escape — handled separately by globalRanges().+function hasBareGlobalAncestor(node) {+ let current = node.parent;+ while (current) {+ const selector = current.selector;+ if (selector && /:global(?!\s*\()/.test(selector)) {+ return true;+ }+ current = current.parent;+ }+ return false;+}++// Return list of [start, end) index ranges inside `selector` that fall within a+// balanced `:global(...)` argument list. Class matches inside these ranges are+// third-party and should be skipped.+function globalRanges(selector) {+ const ranges = [];+ const re = /:global\s*\(/g;+ let match;+ while ((match = re.exec(selector)) !== null) {+ const argStart = match.index + match[0].length;+ let depth = 1;+ let i = argStart;+ while (i < selector.length && depth > 0) {+ const ch = selector[i];+ if (ch === '(') {+ depth++;+ } else if (ch === ')') {+ depth--;+ }+ if (depth > 0) {+ i++;+ }+ }+ ranges.push([argStart, i]);+ re.lastIndex = i;+ }+ return ranges;+}++function indexInRanges(index, ranges) {+ for (const [start, end] of ranges) {+ if (index >= start && index < end) {+ return true;+ }+ }+ return false;+}++const rule = (primaryOption, secondaryOptions) => {+ return (root, result) => {+ if (!primaryOption) {+ return;+ }++ const userPrefixes =+ (secondaryOptions && secondaryOptions.ignoreThirdPartyPrefixes) || [];+ const allPrefixes = [...DEFAULT_THIRD_PARTY_PREFIXES, ...userPrefixes];++ root.walkRules((ruleNode) => {+ const selector = ruleNode.selector;++ // Bare `:global { }` block makes all descendants global — skip entirely.+ if (hasBareGlobalAncestor(ruleNode)) {+ return;+ }++ const ranges = globalRanges(selector);++ let match;+ CLASS_PATTERN.lastIndex = 0;++ while ((match = CLASS_PATTERN.exec(selector)) !== null) {+ const className = match[1];+ // Skip classes inside `:global(...)` ranges of this selector.+ if (indexInRanges(match.index, ranges)) {+ continue;+ }++ // Skip third-party library classes+ if (allPrefixes.some((prefix) => className.startsWith(prefix))) {+ continue;+ }++ if (isKebabCase(className)) {+ stylelint.utils.report({+ message: messages.kebabCase(className),+ node: ruleNode,+ result,+ ruleName,+ });+ } else if (isSnakeCase(className)) {+ stylelint.utils.report({+ message: messages.snakeCase(className),+ node: ruleNode,+ result,+ ruleName,+ });+ } else if (isPascalCase(className)) {+ stylelint.utils.report({+ message: messages.pascalCase(className),+ node: ruleNode,+ result,+ ruleName,+ });+ }+ }+ });+ };+};++rule.ruleName = ruleName;+rule.messages = messages;+rule.meta = {};++export { ruleName, rule };+export default { ruleName, rule };diff --git a/frontend/stylelint-rules/css-modules/no-bare-element-selectors.js b/frontend/stylelint-rules/css-modules/no-bare-element-selectors.jsnew file mode 100644index 0000000000..473761964f--- /dev/null+++ b/frontend/stylelint-rules/css-modules/no-bare-element-selectors.js@@ -0,0 +1,164 @@+/**+ * Stylelint rule: local/no-bare-element-selectors+ *+ * Prevents bare element selectors at root level in CSS modules.+ * Bare elements affect ALL instances of that element within component scope,+ * often unintentionally.+ *+ * BAD:+ * div { }+ * span { padding: 4px; }+ * p { margin: 0; }+ *+ * GOOD:+ * .container { }+ * .title { }+ *+ * ALLOWED (nested under class):+ * .container {+ * p { margin: 0; } // Scoped to .container+ * }+ */+import stylelint from 'stylelint';++const ruleName = 'local/no-bare-element-selectors';++const messages = stylelint.utils.ruleMessages(ruleName, {+ unexpected: (element) =>+ `Bare element selector "${element}" at root level affects all instances. Use class selector or nest under a class.`,+ unexpectedInCompound: (element, full) =>+ `Bare element "${element}" in unscoped selector "${full}" at root level matches every "<${element}>" in the module. Anchor the selector with a class (e.g., ".container ${element}") or use :global() if intentional.`,+});++const ELEMENT_PATTERN = /^[a-z][a-z0-9]*$/i;+const EXCLUDED_ELEMENTS = new Set(['html', 'body', 'root']);++function isPartBareElement(part) {+ const trimmed = part.trim();+ if (!trimmed) {+ return false;+ }+ // Strip pseudo suffixes (`:hover`, `::before`) — element part is what's before+ const elementOnly = trimmed.split(':')[0];+ if (!elementOnly) {+ return false;+ }+ // Skip class/id/attribute parts+ if (/[.#[]/.test(elementOnly)) {+ return false;+ }+ return (+ ELEMENT_PATTERN.test(elementOnly) &&+ !EXCLUDED_ELEMENTS.has(elementOnly.toLowerCase())+ );+}++function isBareElement(selector) {+ const trimmed = selector.trim();+ // Skip combined selectors+ if (/[,\s>+~]/.test(trimmed)) {+ return false;+ }+ // Skip pseudo-selectors+ if (trimmed.includes(':')) {+ return false;+ }+ // Skip class/id/attribute selectors+ if (/[.#[]/.test(trimmed)) {+ return false;+ }+ return (+ ELEMENT_PATTERN.test(trimmed) && !EXCLUDED_ELEMENTS.has(trimmed.toLowerCase())+ );+}++// Split a compound selector on combinators (`>`, `+`, `~`, descendant space)+// while keeping each part intact. Returns an array of selector parts.+function splitOnCombinators(selector) {+ return selector+ .split(/\s*[>+~]\s*|\s+/)+ .map((p) => p.trim())+ .filter(Boolean);+}++function isInsideGlobal(selector) {+ return /:global\s*\(/.test(selector);+}++const KEYFRAME_ATRULES = new Set([+ 'keyframes',+ '-webkit-keyframes',+ '-moz-keyframes',+ '-o-keyframes',+]);++// Rule's effective parent is root if all ancestors above it are atrules+// (e.g. `@media`, `@supports`). A bare `div` inside `@media { }` at top level+// still matches every `<div>` in the module. Exclude `@keyframes` — its+// `from`/`to`/`0%` children are not element selectors.+function isEffectivelyTopLevel(node) {+ let parent = node.parent;+ while (parent && parent.type === 'atrule') {+ if (KEYFRAME_ATRULES.has(parent.name.toLowerCase())) {+ return false;+ }+ parent = parent.parent;+ }+ return Boolean(parent) && parent.type === 'root';+}++const rule = (primaryOption) => {+ return (root, result) => {+ if (!primaryOption) {+ return;+ }++ root.walkRules((ruleNode) => {+ if (!isEffectivelyTopLevel(ruleNode)) {+ return;+ }++ const selectors = ruleNode.selector.split(',').map((s) => s.trim());++ for (const selector of selectors) {+ if (isInsideGlobal(selector)) {+ continue;+ }++ if (isBareElement(selector)) {+ stylelint.utils.report({+ message: messages.unexpected(selector),+ node: ruleNode,+ result,+ ruleName,+ });+ continue;+ }++ // Check combined selectors part-by-part. Only flag when the compound+ // has NO class/id anchor — `.container > div` is already scoped, but+ // `div + span` at root affects every matching descendant in the module.+ if (/[\s>+~]/.test(selector) && !/[.#]/.test(selector)) {+ const parts = splitOnCombinators(selector);+ for (const part of parts) {+ if (isPartBareElement(part)) {+ stylelint.utils.report({+ message: messages.unexpectedInCompound(part.split(':')[0], selector),+ node: ruleNode,+ result,+ ruleName,+ });+ }+ }+ }+ }+ });+ };+};++rule.ruleName = ruleName;+rule.messages = messages;+rule.meta = {};++export { ruleName, rule };+export default { ruleName, rule };diff --git a/frontend/stylelint-rules/css-modules/no-deep-nesting.js b/frontend/stylelint-rules/css-modules/no-deep-nesting.jsnew file mode 100644index 0000000000..24a28cb255--- /dev/null+++ b/frontend/stylelint-rules/css-modules/no-deep-nesting.js@@ -0,0 +1,97 @@+/**+ * Stylelint rule: local/no-deep-nesting+ *+ * Prevents deep nesting in CSS modules (max 3 levels).+ * Deep nesting creates specificity wars and hard-to-override styles.+ *+ * BAD:+ * .container { .wrapper { .inner { .content { } } } } // 4 levels+ *+ * GOOD:+ * .container { }+ * .containerWrapper { }+ * .containerContent { }+ *+ * Allowed nesting (pseudo-classes/elements):+ * .button { &:hover { } &::before { } }+ */+import stylelint from 'stylelint';++const ruleName = 'local/no-deep-nesting';+const DEFAULT_MAX_DEPTH = 3;++const messages = stylelint.utils.ruleMessages(ruleName, {+ tooDeep: (depth, max) =>+ `Nesting depth ${depth} exceeds maximum of ${max}. Flatten selectors for CSS modules.`,+});++function isPseudoSelector(selector) {+ return /^&?:/.test(selector.trim());+}++function isParentReference(selector) {+ return /^&[.#[]/.test(selector.trim());+}++function countNestingDepth(rule, depth = 0) {+ const selector = rule.selector || '';++ // Don't count pseudo-selectors or parent references toward depth+ if (isPseudoSelector(selector) || isParentReference(selector)) {+ // Still check children+ let maxChildDepth = depth;+ rule.walkRules?.((child) => {+ const childDepth = countNestingDepth(child, depth);+ maxChildDepth = Math.max(maxChildDepth, childDepth);+ });+ return maxChildDepth;+ }++ const currentDepth = depth + 1;+ let maxDepth = currentDepth;++ rule.walkRules?.((child) => {+ const childDepth = countNestingDepth(child, currentDepth);+ maxDepth = Math.max(maxDepth, childDepth);+ });++ return maxDepth;+}++const rule = (primaryOption, secondaryOptions) => {+ return (root, result) => {+ if (!primaryOption) {+ return;+ }++ const maxDepth =+ secondaryOptions && Number.isInteger(secondaryOptions.maxDepth)+ ? secondaryOptions.maxDepth+ : DEFAULT_MAX_DEPTH;++ root.walkRules((ruleNode) => {+ // Only check top-level rules+ if (ruleNode.parent.type !== 'root' && ruleNode.parent.type !== 'atrule') {+ return;+ }++ const depth = countNestingDepth(ruleNode);++ if (depth > maxDepth) {+ stylelint.utils.report({+ message: messages.tooDeep(depth, maxDepth),+ node: ruleNode,+ result,+ ruleName,+ });+ }+ });+ };+};++rule.ruleName = ruleName;+rule.messages = messages;+rule.meta = {};++export { ruleName, rule };+export default { ruleName, rule };diff --git a/frontend/stylelint-rules/css-modules/no-id-selectors.js b/frontend/stylelint-rules/css-modules/no-id-selectors.jsnew file mode 100644index 0000000000..6ae48051bc--- /dev/null+++ b/frontend/stylelint-rules/css-modules/no-id-selectors.js@@ -0,0 +1,55 @@+/**+ * Stylelint rule: local/no-id-selectors+ *+ * Prevents ID selectors in CSS modules.+ * IDs create high specificity, can't be reused, and defeat CSS modules scoping purpose.+ *+ * BAD:+ * #myComponent { }+ * .container #header { }+ *+ * GOOD:+ * .myComponent { }+ * .containerHeader { }+ */+import stylelint from 'stylelint';++const ruleName = 'local/no-id-selectors';++const messages = stylelint.utils.ruleMessages(ruleName, {+ unexpected: (selector) =>+ `ID selector "${selector}" not allowed in CSS modules. Use class selector instead.`,+});++const ID_PATTERN = /#[a-zA-Z_][a-zA-Z0-9_-]*/g;++const rule = (primaryOption) => {+ return (root, result) => {+ if (!primaryOption) {+ return;+ }++ root.walkRules((ruleNode) => {+ const selector = ruleNode.selector;+ const matches = selector.match(ID_PATTERN);++ if (matches) {+ for (const match of matches) {+ stylelint.utils.report({+ message: messages.unexpected(match),+ node: ruleNode,+ result,+ ruleName,+ });+ }+ }+ });+ };+};++rule.ruleName = ruleName;+rule.messages = messages;+rule.meta = {};++export { ruleName, rule };+export default { ruleName, rule };diff --git a/frontend/stylelint-rules/css-modules/prefer-css-variables.js b/frontend/stylelint-rules/css-modules/prefer-css-variables.jsnew file mode 100644index 0000000000..a3b39f8fda--- /dev/null+++ b/frontend/stylelint-rules/css-modules/prefer-css-variables.js@@ -0,0 +1,168 @@+/**+ * Stylelint rule: local/prefer-css-variables+ *+ * Warns on hardcoded colors in CSS modules.+ * Use CSS variables for consistent theming.+ *+ * BAD:+ * color: #ff0000;+ * background: rgb(255, 0, 0);+ * border: 1px solid blue;+ *+ * GOOD:+ * color: var(--l1-foreground);+ * background: var(--primary-background);+ * border: 1px solid var(--l2-border);+ *+ * ALLOWED:+ * transparent, inherit, currentColor, none+ * Colors inside var() fallbacks+ */+import stylelint from 'stylelint';++const ruleName = 'local/prefer-css-variables';++const messages = stylelint.utils.ruleMessages(ruleName, {+ hardcodedColor: (value, property) =>+ `Hardcoded color "${value}" in "${property}". Use a semantic CSS variable instead (e.g., var(--l1-foreground), var(--primary-background)). See docs/css-modules-guide.md.`,+});++const COLOR_PROPERTIES = new Set([+ 'color',+ 'background',+ 'background-color',+ 'background-image',+ 'border',+ 'border-color',+ 'border-top',+ 'border-right',+ 'border-bottom',+ 'border-left',+ 'border-top-color',+ 'border-right-color',+ 'border-bottom-color',+ 'border-left-color',+ 'border-image',+ 'border-image-source',+ 'outline',+ 'outline-color',+ 'box-shadow',+ 'text-shadow',+ 'fill',+ 'stroke',+ 'caret-color',+ 'text-decoration-color',+ 'column-rule-color',+ 'mask',+ 'mask-image',+]);++const ALLOWED_VALUES = new Set([+ 'transparent',+ 'inherit',+ 'initial',+ 'unset',+ 'currentcolor',+ 'none',+ 'auto',+]);++const HEX_PATTERN = /#[0-9a-fA-F]{3,8}\b/;+const RGB_PATTERN = /rgba?\s*\([^)]+\)/i;+const HSL_PATTERN = /hsla?\s*\([^)]+\)/i;+const NAMED_COLOR_PATTERN =+ /\b(red|blue|green|yellow|orange|purple|pink|black|white|gray|grey|cyan|magenta|brown|navy|teal|olive|maroon|lime|aqua|fuchsia|silver)\b/i;++// Strip balanced `fn(...)` sections (e.g. `var(...)`, `url(...)`) from value.+// Handles nested parens by counting depth.+function stripBalancedFn(value, fnName) {+ const needle = `${fnName}(`;+ let out = '';+ let i = 0;+ while (i < value.length) {+ if (value.startsWith(needle, i)) {+ let depth = 1;+ i += needle.length;+ while (i < value.length && depth > 0) {+ const ch = value[i];+ if (ch === '(') {+ depth++;+ } else if (ch === ')') {+ depth--;+ }+ i++;+ }+ } else {+ out += value[i];+ i++;+ }+ }+ return out;+}++function containsHardcodedColor(value) {+ // Strip url(...) first — paths/fragments may contain hex-like or color-named substrings+ let scanned = value.includes('url(') ? stripBalancedFn(value, 'url') : value;++ // Strip var(...) — color tokens inside var fallbacks are allowed+ if (scanned.includes('var(')) {+ scanned = stripBalancedFn(scanned, 'var');+ if (!scanned.trim()) {+ return null;+ }+ }++ const lower = scanned.toLowerCase();+ if (ALLOWED_VALUES.has(lower)) {+ return null;+ }++ if (HEX_PATTERN.test(scanned)) {+ return scanned.match(HEX_PATTERN)[0];+ }+ if (RGB_PATTERN.test(scanned)) {+ return scanned.match(RGB_PATTERN)[0];+ }+ if (HSL_PATTERN.test(scanned)) {+ return scanned.match(HSL_PATTERN)[0];+ }+ if (NAMED_COLOR_PATTERN.test(scanned)) {+ return scanned.match(NAMED_COLOR_PATTERN)[0];+ }++ return null;+}++const rule = (primaryOption) => {+ return (root, result) => {+ if (!primaryOption) {+ return;+ }++ root.walkDecls((decl) => {+ const prop = decl.prop.toLowerCase();++ if (!COLOR_PROPERTIES.has(prop)) {+ return;+ }++ const hardcodedColor = containsHardcodedColor(decl.value);++ if (hardcodedColor) {+ stylelint.utils.report({+ message: messages.hardcodedColor(hardcodedColor, decl.prop),+ node: decl,+ result,+ ruleName,+ });+ }+ });+ };+};++rule.ruleName = ruleName;+rule.messages = messages;+rule.meta = {};++export { ruleName, rule };+export default { ruleName, rule };