An open source design system that's fully customizable and agent ready
TypeScript
fix(i18n): lint JSX children, object-field templates, and text-sink bindings (#9021)
nynexman4464f2beb0b8ffd3
diff --git a/eslint.config.js b/eslint.config.jsindex e4c0e52754..3e5b0d70cb 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -341,7 +341,41 @@ export default defineConfig(],// announce() live-region messages are user-facing text; the rule checks// them as call arguments (callees defaults to ['announce']).- '@astryx/no-hardcoded-i18n-string': isStrictMode ? 'error' : 'warn',+ '@astryx/no-hardcoded-i18n-string': [+ isStrictMode ? 'error' : 'warn',+ {+ // Exact reported chunks exempted per file. Remove an entry when its+ // site moves into the catalog; the list should only shrink.+ allowedStringsByFile: {+ // Developer diagnostics, not interface copy.+ 'BottomSheet/BottomSheetPanel.tsx': ['snapPoints ignored '],+ 'Markdown/plugins/protocol.ts': [+ 'plugin "',+ '" failed in ',+ '; rendered readable fallback.',+ ],+ // Pre-existing hardcoded text awaiting catalog keys.+ 'Chat/useChatPasteAsToken.ts': [' lines, ', ' chars'],+ 'Chat/useTriggerMenu.tsx': ['No results'],+ 'CodeBlock/CodeBlock.tsx': [' diff'],+ 'MultiSelector/MultiSelector.tsx': [' selected'],+ 'PowerSearch/PowerSearch.tsx': [+ 'date range',+ '1 filter',+ ' filters',+ ' items',+ ],+ 'PowerSearch/PowerSearchValueEditor.tsx': [' ago', ' from now'],+ 'Slider/Slider.tsx': ['Minimum value', 'Maximum value', 'Required'],+ 'Table/plugins/columnResize/useTableColumnResize.tsx': [+ 'Resize column ',+ ],+ 'TimeInput/TimeInput.tsx': ['e.g., 2:30 PM', 'e.g., 14:30'],+ 'Timer/Timer.tsx': ['m ', 'h '],+ 'Tokenizer/Tokenizer.tsx': ['Create "', ' more'],+ },+ },+ ],},},// What a disabled control says to the pointer is a defect wherever itdiff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.jsindex f0f27c2c06..285be9f761 100644--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js@@ -22,7 +22,18 @@* that "looks user-facing". Other `aria-*` attributes (aria-controls,* aria-expanded, aria-hidden, …) take IDs / booleans / enums and are* NOT flagged.- * 2. Object property assignments of the same names inside .tsx files.+ * 2. Object property values of the same names: plain literals, plus+ * templates, ternaries and `??`/`||` fallbacks walked like a JSX+ * attribute value, ignoring punctuation-only chunks (`${a}: ${b}`).+ * 2b. Local bindings of the same names (`const thumbLabel = …`,+ * `const ariaLabel = `Resize column ${h}``). The binding NAME is the+ * heuristic; values are not traced from other names into a sink.+ * 2c. JSX children: rendered text (`<span>No results</span>`) and+ * expression children (`{formatValue?.(x) ?? `${n} selected`}`).+ * JSX text is judged as it renders, so ` items` in `{count} items` is+ * prose, like the same chunk of a template.+ * Punctuation and number layout (`{used}/{max}`) are not English and are+ * not flagged; that ordering is a manual review concern.* 3. Destructure defaults (`function Foo({label = 'X'})`) of the same names.* 4. Call arguments: hardcoded first arguments to configured callees* (default: `announce`, the live-region announcer returned by@@ -34,7 +45,9 @@* literals reached through a ternary or an `||`/`??` fallback and the* literal chunks of an interpolated template are flagged too;* identifiers and t(...) results are allowed.- * 5. Returns from format* and get*String/Text/Label/Message helpers, including+ * 5. Returns from format* and get*String/Text/Label/Message helpers, and from+ * functions bound to a text-sink name (`const displayPlaceholder =+ * useMemo(() => …)`, `const emptyLabel = () => …`), including* expression-bodied arrows. Helper names are a heuristic, not data-flow* analysis. Obvious CSS serializer names (color, style, shadow, transform,* gradient, length, angle, RGB/HSL/hex) are excluded; text-sink suffixes@@ -75,6 +88,12 @@* allowedCalleeStrings: string[] — exact string values temporarily exempted* from the callee check (grandfathered sites tracked for removal).* Default: [].+ * allowedStringsByFile: {[pathSuffix: string]: string[]} — exact reported+ * values exempted from every surface, but only in files whose path ends+ * with the key. For grandfathered sites tracked for removal, and for+ * developer diagnostics that are not interface copy. The value is the+ * reported chunk: a literal, one template chunk, or trimmed JSX text.+ * Default: {}.*//**@@ -213,12 +232,14 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {const report = (node, value) => {if (opts.requireEnglish && !/[A-Za-z]/.test(value)) return false;if (allowed?.has(value)) return false;- context.report({+ // The per-file allowlist wrapper returns false when it suppresses, so an+ // exempted chunk does not end the scan of the rest of its template.+ const emitted = context.report({node,messageId,data: {value: JSON.stringify(value), name},});- return true;+ return emitted !== false;};switch (expr.type) {case 'Literal':@@ -322,6 +343,49 @@ function getFunctionName(node) {return node.id?.name;}+function allowedStringsForFile(filename, byFile) {+ const allowed = new Set();+ if (byFile == null) return allowed;+ const path = filename.replace(/\\/g, '/');+ for (const [suffix, values] of Object.entries(byFile)) {+ if (path === suffix || path.endsWith(`/${suffix}`)) {+ for (const value of values) allowed.add(value);+ }+ }+ return allowed;+}++/**+ * JSX text as it renders: whitespace that touches a line break is dropped,+ * whitespace inside a line (including next to an expression child) is kept and+ * collapsed to one space.+ */+function renderedJSXText(raw) {+ const lines = raw.split(/\r\n|\n|\r/);+ const kept = [];+ for (const [index, line] of lines.entries()) {+ let text = line.replace(/[\t ]+/g, ' ');+ if (index > 0) text = text.replace(/^ /, '');+ if (index < lines.length - 1) text = text.replace(/ $/, '');+ if (text !== '') kept.push(text);+ }+ return kept.join(' ');+}++function isJSXChild(node) {+ const parent = node.parent;+ return parent?.type === 'JSXElement' || parent?.type === 'JSXFragment';+}++/**+ * Functions whose return value is user-facing text: format* / get*Label+ * helpers, plus functions bound to a text-sink name — `const fooLabel = () =>`+ * or `const displayPlaceholder = useMemo(() => …)`.+ */+function isTextReturningName(name) {+ return isFormatterName(name) || isUserFacingName(name);+}+function isFunction(node) {return (node.type === 'FunctionDeclaration' ||@@ -366,25 +430,51 @@ const rule = {type: 'array',items: {type: 'string'},},+ allowedStringsByFile: {+ type: 'object',+ additionalProperties: {+ type: 'array',+ items: {type: 'string'},+ },+ },},additionalProperties: false,},],},- create(context) {- const filename = context.filename;+ create(ruleContext) {+ const filename = ruleContext.filename;if (shouldIgnoreFile(filename)) return {};- const options = context.options[0] || {};+ const options = ruleContext.options[0] || {};const callees = new Set(options.callees ?? ['announce']);const allowedCalleeStrings = new Set(options.allowedCalleeStrings ?? []);+ const allowedInFile = allowedStringsForFile(+ filename,+ options.allowedStringsByFile,+ );+ const context =+ allowedInFile.size === 0+ ? ruleContext+ : Object.create(ruleContext, {+ report: {+ value(descriptor) {+ const value = descriptor.data?.value;+ if (value != null && allowedInFile.has(JSON.parse(value))) {+ return false;+ }+ ruleContext.report(descriptor);+ return true;+ },+ },+ });return {ReturnStatement(node) {let owner = node.parent;while (owner && !isFunction(owner)) owner = owner.parent;const name = owner && getFunctionName(owner);- if (!isFormatterName(name)) return;+ if (!isTextReturningName(name)) return;reportUserFacingLiteralsIn(node.argument, name, context, false, {messageId: 'hardcodedReturn',requireEnglish: true,@@ -394,7 +484,7 @@ const rule = {ArrowFunctionExpression(node) {if (node.body.type === 'BlockStatement') return;const name = getFunctionName(node);- if (!isFormatterName(name)) return;+ if (!isTextReturningName(name)) return;reportUserFacingLiteralsIn(node.body, name, context, false, {messageId: 'hardcodedReturn',requireEnglish: true,@@ -449,17 +539,58 @@ const rule = {? node.key.value: null;if (!isUserFacingName(name)) return;- if (- node.value.type !== 'Literal' ||- typeof node.value.value !== 'string'- )+ if (node.value.type === 'Literal') {+ const val = node.value.value;+ if (typeof val !== 'string' || !looksUserFacing(val)) return;+ context.report({+ node: node.value,+ messageId: 'hardcodedString',+ data: {value: JSON.stringify(val), name},+ });return;- const val = node.value.value;- if (!looksUserFacing(val)) return;+ }+ // Same walk as a JSX attribute value, so `label: `Create "${v}"``+ // and `title: open ? 'Close' : 'Open'` are caught like a literal.+ // Punctuation-only chunks (`${a}: ${b}`) are not English copy.+ reportUserFacingLiteralsIn(node.value, name, context, false, {+ requireEnglish: true,+ });+ },++ // 2b. Local binding of a text-sink name: `const thumbLabel = 'Minimum'`.+ // The value usually reaches `aria-label={thumbLabel}` a few lines+ // later, where the attribute walk only sees an identifier. The+ // binding name is the heuristic — no data-flow tracing.+ VariableDeclarator(node) {+ if (node.id.type !== 'Identifier' || node.init == null) return;+ const name = node.id.name;+ if (!isUserFacingName(name)) return;+ reportUserFacingLiteralsIn(node.init, name, context, false, {+ requireEnglish: true,+ });+ },++ // 2c. JSX children: `<span>{formatValue?.(x) ?? `${n} selected`}</span>`+ // and `<span>No results</span>`. Rendered children are visible text+ // exactly like a `label` prop.+ JSXExpressionContainer(node) {+ if (!isJSXChild(node)) return;+ reportUserFacingLiteralsIn(node.expression, 'children', context, false, {+ requireEnglish: true,+ });+ },++ JSXText(node) {+ if (!isJSXChild(node)) return;+ // Judge the text as React renders it, like a template chunk: the+ // space in `{count} items` is part of the output, so ` items` reads+ // as prose rather than as an identifier-shaped word.+ const val = renderedJSXText(node.value);+ if (!/[A-Za-z]/.test(val) || !looksUserFacing(val)) return;context.report({- node: node.value,+ node,messageId: 'hardcodedString',- data: {value: JSON.stringify(val), name},+ data: {value: JSON.stringify(val), name: 'children'},});},diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjsindex 82400822fd..1f08239094 100644--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs@@ -110,6 +110,59 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {},{code: "function formatLabel() { return 'READY_STATE'; }"},{code: "function formatLabel() { return '/assets/icon.svg'; }"},+ // --- JSX children ---+ {code: "<span>{t('a.b.c')}</span>"},+ {code: '<span>{count}</span>'},+ {code: "<span>{formatValue?.(items) ?? t('a.b.count', {count})}</span>"},+ // Punctuation and number layout between interpolations is not English+ {code: '<span>{valueLength}/{maxLength}</span>'},+ {code: '<span>{`${a} – ${b}`}</span>'},+ {code: '<span>×</span>'},+ {code: '<span> · </span>'},+ // Line-break whitespace is not rendered, so this is one identifier-shaped word+ {code: '<span>\n ok\n</span>'},+ // Attribute expression containers are not children+ {code: "<X data-state={open ? 'Open now' : 'Closed'} />"},+ // --- Object fields: punctuation-only template chunks ---+ {code: 'const x = {label: `${field}: ${value}`};'},+ {code: "const x = {label: t('a.b', {value})};"},+ // --- Local text-sink bindings ---+ {code: "const thumbLabel = isRange ? t('slider.min') : undefined;"},+ {code: 'const ariaLabel = `${prefix}: ${name}`;'},+ {code: 'const ariaLabel = label;'},+ // Non-sink names are not checked (no data-flow tracing)+ {code: "const status = 'Ready to go';"},+ {code: "const [label] = ['Destructured'];"},+ {+ code: "const displayPlaceholder = useMemo(() => placeholder ?? t('time.hint'), []);",+ },+ {+ code: "const thumbLabel = 'Minimum value';",+ filename: 'Slider.test.tsx',+ },+ // --- allowedStringsByFile ---+ {+ code: "const thumbLabel = 'Minimum value'; <span>Required</span>;",+ filename: '/repo/packages/core/src/Slider/Slider.tsx',+ options: [+ {+ allowedStringsByFile: {+ 'Slider/Slider.tsx': ['Minimum value', 'Required'],+ },+ },+ ],+ },+ {+ code: 'const ariaLabel = `Resize column ${key}`;',+ filename: 'C:\\repo\\Table\\useTableColumnResize.tsx',+ options: [+ {+ allowedStringsByFile: {+ 'Table/useTableColumnResize.tsx': ['Resize column '],+ },+ },+ ],+ },// --- Pre-existing surfaces still behave ---{code: "<button aria-label={t('dialog.close')}>x</button>"},],@@ -245,6 +298,191 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {code: "<X aria-label={`${open ? 'Close' : 'Open'}`} />",errors: [{messageId: 'hardcodedString'}, {messageId: 'hardcodedString'}],},+ // --- JSX children ---+ {+ // A rendered fallback count is visible text, like a `label` prop.+ code: '<span>{formatValue?.(items) ?? `${items.length} selected`}</span>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" selected"', name: 'children'},+ },+ ],+ },+ {+ code: "<span>{count === 1 ? '1 filter' : `${count} filters`}</span>",+ errors: [{messageId: 'hardcodedString'}, {messageId: 'hardcodedString'}],+ },+ // JSX text is judged as rendered: the space next to an expression child+ // is output, so a one-word count suffix reads like a template chunk.+ {+ code: '<span>{count} items</span>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" items"', name: 'children'},+ },+ ],+ },+ {+ code: '<span>+{n} more</span>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" more"', name: 'children'},+ },+ ],+ },+ {+ code: '<span>\n {count} items\n</span>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" items"', name: 'children'},+ },+ ],+ },+ {+ code: '<VisuallyHidden>Required</VisuallyHidden>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"Required"', name: 'children'},+ },+ ],+ },+ {+ code: '<>\n No results found\n</>',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"No results found"', name: 'children'},+ },+ ],+ },+ // --- Object fields walk templates and fallbacks ---+ {+ code: 'const row = {id, label: `Create "${trimmed}"`};',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"Create \\""', name: 'label'},+ },+ ],+ },+ {+ code: "const item = {title: open ? 'Close panel' : 'Open panel'};",+ errors: [{messageId: 'hardcodedString'}, {messageId: 'hardcodedString'}],+ },+ {+ code: 'const option = {label: `${amount} ${unit} ago`};',+ errors: [{messageId: 'hardcodedString'}],+ },+ // --- Local text-sink bindings ---+ {+ code: "const thumbLabel = isRange ? (index === 0 ? 'Minimum value' : 'Maximum value') : undefined;",+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"Minimum value"', name: 'thumbLabel'},+ },+ {+ messageId: 'hardcodedString',+ data: {value: '"Maximum value"', name: 'thumbLabel'},+ },+ ],+ },+ {+ code: 'const ariaLabel = `Resize column ${columnKey}`;',+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"Resize column "', name: 'ariaLabel'},+ },+ ],+ },+ {+ code: "const emptyText = trigger.emptySearchText ?? 'No results';",+ errors: [{messageId: 'hardcodedString'}],+ },+ // A function bound to a text-sink name returns text.+ {+ code: "const displayPlaceholder = useMemo(() => { if (focused) { return is12h ? 'e.g., 2:30 PM' : 'e.g., 14:30'; } return placeholder; }, []);",+ errors: [+ {+ messageId: 'hardcodedReturn',+ data: {value: '"e.g., 2:30 PM"', name: 'displayPlaceholder'},+ },+ {+ messageId: 'hardcodedReturn',+ data: {value: '"e.g., 14:30"', name: 'displayPlaceholder'},+ },+ ],+ },+ {+ code: "const emptyLabel = () => 'Nothing here';",+ errors: [{messageId: 'hardcodedReturn'}],+ },+ // allowedStringsByFile is exact-value and file-scoped.+ {+ code: "const thumbLabel = 'Minimum value'; const emptyText = 'No results';",+ filename: '/repo/packages/core/src/Slider/Slider.tsx',+ options: [+ {allowedStringsByFile: {'Slider/Slider.tsx': ['Minimum value']}},+ ],+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '"No results"', name: 'emptyText'},+ },+ ],+ },+ // An exempted chunk does not exempt the rest of its template.+ {+ code: 'const ariaLabel = `Resize column ${h} of ${total} total`;',+ filename: '/repo/Table/useTableColumnResize.tsx',+ options: [+ {+ allowedStringsByFile: {+ 'Table/useTableColumnResize.tsx': ['Resize column '],+ },+ },+ ],+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" of "', name: 'ariaLabel'},+ },+ ],+ },+ {+ code: 'const x = <span>{count} items</span>;',+ filename: '/repo/PowerSearch/PowerSearch.tsx',+ options: [+ {allowedStringsByFile: {'PowerSearch/PowerSearch.tsx': ['items']}},+ ],+ errors: [+ {+ messageId: 'hardcodedString',+ data: {value: '" items"', name: 'children'},+ },+ ],+ },+ {+ code: "const thumbLabel = 'Minimum value';",+ filename: '/repo/packages/core/src/OtherSlider/OtherSlider.tsx',+ options: [+ {allowedStringsByFile: {'Slider/Slider.tsx': ['Minimum value']}},+ ],+ errors: [{messageId: 'hardcodedString'}],+ },+ {+ code: "const thumbLabel = 'Minimum value';",+ // A key matches whole path segments: Slider.tsx is not RangeSlider.tsx.+ filename: '/repo/packages/core/src/RangeSlider/RangeSlider.tsx',+ options: [{allowedStringsByFile: {'Slider.tsx': ['Minimum value']}}],+ errors: [{messageId: 'hardcodedString'}],+ },// --- Pre-existing surfaces still behave ---{code: '<button aria-label="Close">x</button>',