A local-first personal finance app
expand eslint untranslated string rule (#5827)
Matt Fiddaman0ea8bc1fb40e
diff --git a/packages/desktop-client/src/components/manager/ManagementApp.tsx b/packages/desktop-client/src/components/manager/ManagementApp.tsxindex cd895ade58..fa1e314018 100644--- a/packages/desktop-client/src/components/manager/ManagementApp.tsx+++ b/packages/desktop-client/src/components/manager/ManagementApp.tsx@@ -1,4 +1,5 @@import React, { useEffect } from 'react';+import { Trans } from 'react-i18next';import { Navigate, Route, Routes } from 'react-router';import { useResponsive } from '@actual-app/components/hooks/useResponsive';@@ -55,7 +56,10 @@ function Version() {},}}>- {`App: v${window.Actual.ACTUAL_VERSION} | Server: ${version}`}+ <Trans>+ App: v{{ appVersion: window.Actual.ACTUAL_VERSION }} | Server:{' '}+ {{ serverVersion: version }}+ </Trans></Text>);}diff --git a/packages/desktop-client/src/components/modals/CreateAccountModal.tsx b/packages/desktop-client/src/components/modals/CreateAccountModal.tsxindex 089627dcfc..defa805ed4 100644--- a/packages/desktop-client/src/components/modals/CreateAccountModal.tsx+++ b/packages/desktop-client/src/components/modals/CreateAccountModal.tsx@@ -590,7 +590,7 @@ export function CreateAccountModal({</Trans>{' '}{[isGoCardlessSetupComplete ? '' : 'GoCardless',- isSimpleFinSetupComplete ? '' : 'SimpleFin',+ isSimpleFinSetupComplete ? '' : 'SimpleFIN',isPluggyAiSetupComplete ? '' : 'Pluggy.ai',].filter(Boolean)diff --git a/packages/desktop-client/src/components/modals/LoadBackupModal.tsx b/packages/desktop-client/src/components/modals/LoadBackupModal.tsxindex 8dc1ff9c27..65d7128f77 100644--- a/packages/desktop-client/src/components/modals/LoadBackupModal.tsx+++ b/packages/desktop-client/src/components/modals/LoadBackupModal.tsx@@ -30,6 +30,8 @@ type BackupTableProps = {};function BackupTable({ backups, onSelect }: BackupTableProps) {+ const { t } = useTranslation();+return (<View style={{ flex: 1, maxHeight: 200, overflow: 'auto' }}>{backups.map((backup, idx) => (@@ -41,7 +43,7 @@ function BackupTable({ backups, onSelect }: BackupTableProps) {><Cellwidth="flex"- value={backup.date ? backup.date : 'Revert to Latest'}+ value={backup.date ? backup.date : t('Revert to Latest')}valueStyle={{ paddingLeft: 20 }}/></Row>diff --git a/packages/desktop-client/src/components/payees/ManagePayees.tsx b/packages/desktop-client/src/components/payees/ManagePayees.tsxindex 7eadae4ac4..05e368e66b 100644--- a/packages/desktop-client/src/components/payees/ManagePayees.tsx+++ b/packages/desktop-client/src/components/payees/ManagePayees.tsx@@ -39,6 +39,8 @@ import { useDispatch } from '@desktop-client/redux';const getPayeesById = memoizeOne((payees: PayeeEntity[]) => groupById(payees));function PayeeTableHeader() {+ const { t } = useTranslation();+const dispatchSelected = useSelectedDispatch();const selectedItems = useSelectedItems();@@ -62,7 +64,7 @@ function PayeeTableHeader() {dispatchSelected({ type: 'select-all', isRangeSelect: e.shiftKey })}/>- <Cell value="Name" width="flex" />+ <Cell value={t('Name')} width="flex" /></TableHeader></View>);diff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsxindex d4ef6c7b79..21c93b3ad9 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx@@ -354,6 +354,8 @@ function IntervalSelector({interval: 'Daily' | 'Weekly' | 'Monthly' | 'Yearly';onChange: (val: 'Daily' | 'Weekly' | 'Monthly' | 'Yearly') => void;}) {+ const { t } = useTranslation();+const triggerRef = useRef<HTMLButtonElement | null>(null);const [isOpen, setIsOpen] = useState(false);@@ -367,7 +369,7 @@ function IntervalSelector({ref={triggerRef}variant="bare"onPress={() => setIsOpen(true)}- aria-label="Change interval"+ aria-label={t('Change interval')}><SvgCalendar style={{ width: 12, height: 12 }} /><span style={{ marginLeft: 5 }}>{currentLabel}</span>diff --git a/packages/eslint-plugin-actual/lib/rules/no-untranslated-strings.js b/packages/eslint-plugin-actual/lib/rules/no-untranslated-strings.jsindex db2ec376b6..2234967cca 100644--- a/packages/eslint-plugin-actual/lib/rules/no-untranslated-strings.js+++ b/packages/eslint-plugin-actual/lib/rules/no-untranslated-strings.js@@ -1,3 +1,5 @@+const { ensureImport } = require('../utils/import-helpers');+/** @type {import('eslint').Rule.RuleModule} */module.exports = {meta: {@@ -6,9 +8,11 @@ module.exports = {description: 'Disallow non-translated English strings',recommended: true,},+ fixable: 'code',schema: [],messages: {- noHardcoded: 'Non-translated English string. Wrap in <Trans>.',+ useTrans: 'Non-translated English string. Wrap in <Trans>.',+ useT: 'Non-translated English string. Wrap in t().',},},create(context) {@@ -62,27 +66,198 @@ module.exports = {return true;}}+ // Check if inside a translation function call like t()+ if (parent.type === 'CallExpression') {+ const callee = parent.callee;+ if (+ (callee.type === 'Identifier' && callee.name === 't') ||+ (callee.type === 'MemberExpression' &&+ callee.property.type === 'Identifier' &&+ callee.property.name === 't')+ ) {+ return true;+ }+ }+ parent = parent.parent;+ }+ return false;+ }++ function isProgrammaticString(node) {+ const parent = node.parent;+ if (!parent) return false;++ const programmaticTypes = [+ 'BinaryExpression',+ 'SwitchCase',+ 'ArrayExpression',+ 'TSAsExpression',+ 'TSLiteralType',+ 'CallExpression',+ ];++ if (programmaticTypes.includes(parent.type)) {+ return true;+ }++ // Property values are context-dependent, let JSX context check handle them+ if (parent.type === 'Property' && parent.value === node) {+ return false;+ }++ return false;+ }++ function isUserFacingJSXAttribute(node) {+ const userFacingAttributes = [+ 'aria-label',+ 'aria-description',+ 'aria-placeholder',+ 'aria-roledescription',+ 'aria-valuetext',+ 'title',+ 'placeholder',+ 'alt',+ 'label',+ 'value',+ 'header',+ 'content',+ 'message',+ 'text',+ 'description',+ ];++ let parent = node.parent;+ while (parent) {+ if (parent.type === 'JSXAttribute') {+ const attrName = parent.name?.name;+ return userFacingAttributes.includes(attrName);+ }parent = parent.parent;}return false;}+ function isInJSXContext(node) {+ let p = node.parent;+ while (p) {+ if (p.type === 'JSXAttribute') {+ return isUserFacingJSXAttribute(node);+ }+ p = p.parent;+ }++ // Not in an attribute, check if we're in JSX content+ let parent = node.parent;+ while (parent) {+ // JSX text content and fragments are always user-facing+ if (+ parent.type === 'JSXElement' ||+ parent.type === 'JSXFragment' ||+ parent.type === 'JSXExpressionContainer'+ ) {+ return true;+ }++ // Stop at function boundaries to avoid false positives+ if (+ parent.type === 'FunctionDeclaration' ||+ parent.type === 'FunctionExpression' ||+ parent.type === 'ArrowFunctionExpression'+ ) {+ // But keep going if this function is directly in a JSX context+ // (e.g., inline arrow functions in JSX)+ const grandparent = parent.parent;+ if (+ !grandparent ||+ (grandparent.type !== 'JSXExpressionContainer' &&+ grandparent.type !== 'JSXAttribute' &&+ grandparent.type !== 'CallExpression')+ ) {+ return false;+ }+ }+ parent = parent.parent;+ }+ return false;+ }++ function isInJSXAttribute(node) {+ let parent = node.parent;+ while (parent) {+ if (parent.type === 'JSXAttribute') {+ return true;+ }+ parent = parent.parent;+ }+ return false;+ }++ function getFix(node, isJSXText = false) {+ const sourceCode = context.getSourceCode();++ return fixer => {+ const fixes = [];++ if (isJSXText) {+ // For JSX text, wrap with <Trans>+ fixes.push(fixer.replaceText(node, `<Trans>${node.value}</Trans>`));+ ensureImport(fixes, sourceCode, fixer, 'Trans', 'react-i18next');+ } else {+ // For string literals+ const text = sourceCode.getText(node);++ if (isInJSXAttribute(node)) {+ fixes.push(fixer.replaceText(node, `{t(${text})}`));+ } else {+ fixes.push(fixer.replaceText(node, `t(${text})`));+ }+ }++ return fixes;+ };+ }+return {JSXText(node) {if (isProbablyEnglish(node.value) && !isInsideTrans(node)) {- context.report({ node, messageId: 'noHardcoded' });+ context.report({+ node,+ messageId: 'useTrans',+ fix: getFix(node, true),+ });}},Literal(node) {if (- node.parent &&- node.parent.type === 'JSXExpressionContainer' &&typeof node.value === 'string' &&isProbablyEnglish(node.value) &&+ !isProgrammaticString(node) &&+ isInJSXContext(node) &&!isInsideTrans(node)) {- context.report({ node, messageId: 'noHardcoded' });+ context.report({+ node,+ messageId: 'useT',+ fix: getFix(node, false),+ });+ }+ },+ TemplateLiteral(node) {+ if (isProgrammaticString(node)) {+ return;}++ node.quasis.forEach(quasi => {+ if (+ isProbablyEnglish(quasi.value.cooked) &&+ isInJSXContext(node) &&+ !isInsideTrans(node)+ ) {+ // Template literals are harder to auto-fix, so skip for now+ context.report({ node: quasi, messageId: 'useT' });+ }+ });},};},diff --git a/packages/eslint-plugin-actual/lib/rules/prefer-logger-over-console.js b/packages/eslint-plugin-actual/lib/rules/prefer-logger-over-console.jsindex 33ed508554..ffb781a2b8 100644--- a/packages/eslint-plugin-actual/lib/rules/prefer-logger-over-console.js+++ b/packages/eslint-plugin-actual/lib/rules/prefer-logger-over-console.js@@ -1,5 +1,7 @@/* eslint-disable actual/typography */+const { getImportFix } = require('../utils/import-helpers');+/** @type {import('eslint').Rule.RuleModule} */module.exports = {meta: {@@ -86,8 +88,6 @@ module.exports = {data: { method },fix(fixer) {const sourceCode = context.getSourceCode();- const program = sourceCode.ast;-const { decl, localName } = getLoggerImportInfo();const loggerIdent = localName || 'logger';const fixes = [@@ -98,6 +98,8 @@ module.exports = {];if (!localName) {+ const importPath = getLoggerImportPath();+// If the module is already imported, append { logger } to itif (decl && decl.specifiers && decl.specifiers.length > 0) {const lastSpec = decl.specifiers[decl.specifiers.length - 1];@@ -105,7 +107,6 @@ module.exports = {fixes.unshift(fixer.insertTextAfter(lastSpec, ', logger'));} else {// Fallback: separate import if default/namespace import only- const importPath = getLoggerImportPath();fixes.unshift(fixer.insertTextAfter(decl,@@ -113,35 +114,14 @@ module.exports = {),);}- } else if (decl) {- // No specifiers at all; insert a fresh named import after it- const importPath = getLoggerImportPath();- fixes.unshift(- fixer.insertTextAfter(- decl,- `\nimport { logger } from '${importPath}';`,- ),- );} else {- const importPath = getLoggerImportPath();- const firstImport = program.body.find(- n => n.type === 'ImportDeclaration',- );- if (firstImport) {- fixes.unshift(- fixer.insertTextAfter(- firstImport,- `\nimport { logger } from '${importPath}';`,- ),- );- } else {- fixes.unshift(- fixer.insertTextBefore(- program.body[0],- `import { logger } from '${importPath}';\n`,- ),- );- }+ // Use shared utility to add the import+ const importFix = getImportFix(+ sourceCode,+ 'logger',+ importPath,+ )(fixer);+ if (importFix) fixes.unshift(importFix);}}diff --git a/packages/eslint-plugin-actual/lib/rules/prefer-trans-over-t.js b/packages/eslint-plugin-actual/lib/rules/prefer-trans-over-t.jsindex ef345b6b00..2e616a3c49 100644--- a/packages/eslint-plugin-actual/lib/rules/prefer-trans-over-t.js+++ b/packages/eslint-plugin-actual/lib/rules/prefer-trans-over-t.js@@ -1,3 +1,5 @@+const { ensureImport } = require('../utils/import-helpers');+/** @type {import('eslint').Rule.RuleModule} */module.exports = {meta: {@@ -126,22 +128,10 @@ module.exports = {fix(fixer) {const text = node.arguments[0].value;const sourceCode = context.getSourceCode();- const program = sourceCode.ast;-const fixes = [fixer.replaceText(node, `<Trans>${text}</Trans>`)];- const firstImport = program.body.find(- n => n.type === 'ImportDeclaration',- );- if (firstImport) {- fixes.unshift(- fixer.insertTextAfter(- firstImport,- // eslint-disable-next-line actual/typography- "\nimport { Trans } from 'react-i18next';",- ),- );- }+ // Add Trans import if needed+ ensureImport(fixes, sourceCode, fixer, 'Trans', 'react-i18next');return fixes;},diff --git a/packages/eslint-plugin-actual/lib/utils/import-helpers.js b/packages/eslint-plugin-actual/lib/utils/import-helpers.jsnew file mode 100644index 0000000000..384795e026--- /dev/null+++ b/packages/eslint-plugin-actual/lib/utils/import-helpers.js@@ -0,0 +1,91 @@+/* eslint-disable actual/typography */++/**+ * Shared utilities for managing imports in ESLint rules+ */++/**+ * Check if a specific import exists from a module+ * @param {import('eslint').SourceCode} sourceCode+ * @param {string} importName - The name to import (e.g., 't', 'Trans')+ * @param {string} moduleName - The module to import from (e.g., 'react-i18next')+ * @returns {boolean}+ */+function hasImport(sourceCode, importName, moduleName) {+ const ast = sourceCode.ast;+ return ast.body.some(node => {+ if (node.type !== 'ImportDeclaration') return false;+ if (node.source.value !== moduleName) return false;++ return node.specifiers.some(spec => {+ if (spec.type === 'ImportSpecifier') {+ return spec.imported.name === importName;+ }+ return false;+ });+ });+}++/**+ * Get a fixer function to add an import+ * @param {import('eslint').SourceCode} sourceCode+ * @param {string} importName - The name to import (e.g., 't', 'Trans')+ * @param {string} moduleName - The module to import from (e.g., 'react-i18next')+ * @returns {(fixer: import('eslint').Rule.RuleFixer) => import('eslint').Rule.Fix}+ */+function getImportFix(sourceCode, importName, moduleName) {+ const ast = sourceCode.ast;++ // Find existing import from the same module+ const existingImport = ast.body.find(+ node =>+ node.type === 'ImportDeclaration' && node.source.value === moduleName,+ );++ if (existingImport) {+ if (existingImport.specifiers.length === 0) {+ const importStatement = `import { ${importName} } from '${moduleName}';\n`;+ return fixer =>+ fixer.insertTextAfter(existingImport, `\n${importStatement}`);+ }++ // Add to existing import+ const lastSpecifier =+ existingImport.specifiers[existingImport.specifiers.length - 1];+ return fixer => fixer.insertTextAfter(lastSpecifier, `, ${importName}`);+ } else {+ // Add new import statement+ // Find the first import to insert after, or the first node if no imports exist+ const firstImport = ast.body.find(n => n.type === 'ImportDeclaration');+ const targetNode = firstImport || ast.body[0];++ const importStatement = `import { ${importName} } from '${moduleName}';\n`;++ if (firstImport) {+ return fixer => fixer.insertTextAfter(targetNode, `\n${importStatement}`);+ } else {+ return fixer => fixer.insertTextBefore(targetNode, importStatement);+ }+ }+}++/**+ * Add an import to the fixes array if it doesn't exist+ * @param {Array} fixes - Array of fixes to add to+ * @param {import('eslint').SourceCode} sourceCode+ * @param {import('eslint').Rule.RuleFixer} fixer+ * @param {string} importName - The name to import+ * @param {string} moduleName - The module to import from (e.g., 'react-i18next')+ */+function ensureImport(fixes, sourceCode, fixer, importName, moduleName) {+ if (!hasImport(sourceCode, importName, moduleName)) {+ const importFix = getImportFix(sourceCode, importName, moduleName)(fixer);+ if (importFix) fixes.push(importFix);+ }+}++module.exports = {+ hasImport,+ getImportFix,+ ensureImport,+};diff --git a/upcoming-release-notes/5827.md b/upcoming-release-notes/5827.mdnew file mode 100644index 0000000000..f79f465ff4--- /dev/null+++ b/upcoming-release-notes/5827.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [matt-fidd]+---++Expand eslint untranslated string rule