diff --git a/.husky/pre-commit b/.husky/pre-commit index 5d7770045e2b..599731e2ab3c 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -18,4 +18,5 @@ else cd ./frontend fi -npx lint-staged --allow-empty +# LINT_STAGED makes eslint check only the staged lines (see .eslintrc.js). +LINT_STAGED=true npx lint-staged --allow-empty diff --git a/frontend/.claude/commands/e2e-create.md b/frontend/.claude/commands/e2e-create.md index 2bbf350ca1ab..1f77abfea706 100644 --- a/frontend/.claude/commands/e2e-create.md +++ b/frontend/.claude/commands/e2e-create.md @@ -27,7 +27,7 @@ Create a new E2E test following the existing patterns in the codebase. 4. **Scan application code:** - Find components being tested in `frontend/web/components/` or `frontend/common/` - - Add `data-test` attributes if missing + - Make sure elements have a role or accessible name to locate them by; add `data-test` only as a last resort 5. **Create the test file:** - Follow naming convention: `*-test.pw.ts` or `*-tests.pw.ts` @@ -41,11 +41,11 @@ Create a new E2E test following the existing patterns in the codebase. 7. **Report what was created:** - Test file path - - Any `data-test` attributes added + - Any accessible names or `data-test` attributes added - Test stability results ## Important Notes -- Always use `data-test` attributes for selectors +- Prefer `getByRole`, `getByLabel` and `getByText`; keep `data-test` as a fallback - Use existing helper functions instead of raw Playwright APIs - Tests should be independent and not rely on execution order diff --git a/frontend/.claude/context/e2e.md b/frontend/.claude/context/e2e.md index 84b7f07f163a..b2515c646924 100644 --- a/frontend/.claude/context/e2e.md +++ b/frontend/.claude/context/e2e.md @@ -95,7 +95,7 @@ grep -i "error\|failed" 0-trace.network # Check for network errors ### Common Fix Patterns - **Wrong selector** → Update to match actual DOM from error-context.md -- **Missing `data-test` attribute** → Add it to the component +- **No good locator** → Give the element a role or accessible name (e.g. `aria-label`) and use `getByRole`/`getByText`; add `data-test` only as a last resort - **Element hidden** → Filter for visible elements or wait for visibility - **Missing wait** → Add appropriate `waitFor*` calls - **Race condition** → Add network waits, increase timeouts, or use more specific waits @@ -122,7 +122,7 @@ Tests that fail initially but pass on retry are FLAKY and MUST be investigated, ## Important Rules - **DO** modify test files to fix timing issues, missing waits, or broken selectors -- **DO** add `data-test` attributes to components if they're missing +- **DO** prefer `getByRole`, `getByLabel` and `getByText`; add `data-test` only when an element has no role or accessible name to match (the lint warns on new ones) - **DON'T** modify test assertions or business logic unless the test is clearly wrong - If the failure is in application code (not test code), report it as a bug but don't try to fix it - Always explain what fixes you're attempting and why diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js index 2d2591f5ee4e..61f797791960 100644 --- a/frontend/.eslintrc.js +++ b/frontend/.eslintrc.js @@ -1,3 +1,86 @@ +// Patterns we keep catching in review. Warnings only, on changed lines only +// (CI and pre-commit), so they never block a PR. For a real exception, +// disable the rule on that line and say why. +const colourMessage = 'Use a colour token, not a hex, rgb or hsl literal.' +const fetchMessage = + 'Add an RTK Query endpoint in common/services/ instead of fetch().' + +const colourLiterals = [ + { + message: colourMessage, + selector: + 'Literal[value=/^\\s*(#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$|(rgba?|hsla?)\\()/]', + }, + { + message: colourMessage, + selector: + 'TemplateElement[value.raw=/#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\\b|(rgba?|hsla?)\\(/]', + }, +] + +// Legacy classes that have a DS component. Keep this list short: add a class +// only once its replacement exists, remove it once the last use migrates. +const legacyClasses = [ + { re: '(^|\\s)chip(--|\\s|$)', use: 'Chip' }, + { re: '(^|\\s)alert(\\s|$)', use: 'Banner' }, +].flatMap(({ re, use }) => { + const message = `Use the DS ${use} instead of the legacy class.` + return [ + { + message, + selector: `JSXAttribute[name.name='className'] Literal[value=/${re}/]:not(CallExpression Literal)`, + }, + { + message, + selector: `JSXAttribute[name.name='className'] TemplateElement[value.raw=/${re}/]`, + }, + { + message, + selector: `CallExpression[callee.name=/^(cn|classNames|cx)$/] Literal[value=/${re}/]`, + }, + ] +}) + +// A style object that only sets CSS custom properties is allowed. +const styleMessage = + 'Use a SCSS class with tokens. For a runtime value, set a CSS custom property.' +// `as const` only narrows, so it stays allowed. +const assertionMessage = 'Type the value instead of asserting its type.' +const otherPatterns = [ + ...legacyClasses, + { + message: assertionMessage, + selector: "TSAsExpression:not([typeAnnotation.typeName.name='const'])", + }, + { + message: assertionMessage, + selector: 'TSTypeAssertion', + }, + { + message: styleMessage, + selector: + "JSXAttribute[name.name='style'] > JSXExpressionContainer > :not(ObjectExpression)", + }, + { + message: styleMessage, + selector: + "JSXAttribute[name.name='style'] > JSXExpressionContainer > ObjectExpression > :not(Property[key.value=/^--/])", + }, + { + message: "Use BareButton instead of role='button'.", + selector: "JSXAttribute[name.name='role'] Literal[value='button']", + }, + { + message: 'Give the element a role or accessible name instead of data-test.', + selector: "JSXAttribute[name.name='data-test']", + }, + { + message: fetchMessage, + selector: + "CallExpression[callee.object.name=/^(window|globalThis|self)$/][callee.property.name='fetch']", + }, +] + module.exports = { 'env': { 'browser': true, @@ -11,9 +94,9 @@ module.exports = { 'plugin:prettier/recommended', 'plugin:@dword-design/import-alias/recommended', 'plugin:storybook/recommended', - // Lints only changed lines in CI (no-op locally), so the pre-existing - // eslint backlog doesn't fail PRs that merely touch a file. - 'plugin:diff/ci', + // Lints only changed lines in CI and in the pre-commit hook (which sets + // LINT_STAGED), so the pre-existing backlog doesn't fail a commit or PR. + process.env.LINT_STAGED ? 'plugin:diff/staged' : 'plugin:diff/ci', ], 'globals': { '$': true, @@ -99,6 +182,29 @@ module.exports = { 'zE': true, }, 'ignorePatterns': ['server/index.js', 'next.config.js', 'babel.config.js'], + 'overrides': [ + { + // Where raw colour values are defined or are brand colours. + 'files': [ + '.storybook/**', + 'common/constants.ts', + 'common/theme/**', + 'common/utils/paletteColour.ts', + 'documentation/**', + 'web/components/icons/**', + ], + 'rules': { + 'no-restricted-syntax': ['warn', ...otherPatterns], + }, + }, + { + // The legacy request layer RTK Query is built on. + 'files': ['common/data/base/**'], + 'rules': { + 'no-restricted-globals': 'off', + }, + }, + ], 'parser': '@typescript-eslint/parser', 'parserOptions': { 'ecmaFeatures': { @@ -132,6 +238,7 @@ module.exports = { '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-namespace': 'off', + '@typescript-eslint/no-non-null-assertion': 'warn', '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-var-requires': 'off', 'default-case': 'error', @@ -144,6 +251,29 @@ module.exports = { 'no-empty': 'off', 'no-empty-pattern': 'off', 'no-nested-ternary': 'error', + 'no-restricted-globals': [ + 'warn', + { + message: fetchMessage, + name: 'fetch', + }, + ], + 'no-restricted-imports': [ + 'warn', + { + patterns: [ + { + group: ['**/ErrorMessage', '**/InfoMessage', '**/WarningMessage'], + message: 'Use the DS Banner (components/base/Banner) instead.', + }, + { + group: ['@ionic/react', 'ionicons', 'ionicons/*'], + message: 'Use components/icons/Icon, our own SVG icons.', + }, + ], + }, + ], + 'no-restricted-syntax': ['warn', ...colourLiterals, ...otherPatterns], 'no-unused-vars': 'off', 'no-var': 'error', 'object-curly-spacing': ['error', 'always'], diff --git a/frontend/web/components/LintRulesCheck.tsx b/frontend/web/components/LintRulesCheck.tsx new file mode 100644 index 000000000000..f0a79d23f383 --- /dev/null +++ b/frontend/web/components/LintRulesCheck.tsx @@ -0,0 +1,47 @@ +// Throwaway: checks the review lint rules from #8819 warn in CI. Never merge. +import { FC } from 'react' +import ErrorMessage from './ErrorMessage' + +type Shape = { a: number } + +const LintRulesCheck: FC<{ value?: unknown; maybe?: Shape }> = ({ + maybe, + value, +}) => { + // Expect a warning: type assertion + const shape = value as Shape + // No warning: as const + const sizes = ['sm', 'lg'] as const + // Expect a warning: non-null assertion + const a = maybe!.a + // Expect a warning: hex literal + const hex = '#ff0000' + // Expect a warning: rgb in a template + const rgb = `rgb(${a}, 0, 0)` + // Expect two warnings: fetch and window.fetch + fetch('/api') + window.fetch('/api') + + return ( +
+ {/* Expect a warning: style object */} +
+ {/* No warning: custom property only */} +
+ {/* Expect a warning: data-test */} +
+ {/* Expect a warning: role='button' */} +
+ {/* Expect warnings: legacy chip and alert classes */} + +
+ + {shape.a} + {sizes[0]} + {hex} + {rgb} +
+ ) +} + +export default LintRulesCheck diff --git a/frontend/web/components/pages/IdentitiesPage.tsx b/frontend/web/components/pages/IdentitiesPage.tsx index 5bcc560c57f5..4a51b235f2f2 100644 --- a/frontend/web/components/pages/IdentitiesPage.tsx +++ b/frontend/web/components/pages/IdentitiesPage.tsx @@ -121,6 +121,7 @@ const IdentitiesPage: FC<{ props: any }> = (props) => { ) } + // Throwaway (#8819): the data-test lines below predate this PR, so no warnings return (