The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
add eslint rule to catch missing key prop inside components passed to jt (#63063)
Nicolò Pretto8a71067f33ba
diff --git a/.eslintrc.js b/.eslintrc.jsindex cdb1d59ff48..bf1041df178 100644--- a/.eslintrc.js+++ b/.eslintrc.js@@ -180,6 +180,7 @@ module.exports = {{files: ["*.js", "*.jsx", "*.ts", "*.tsx"],rules: {+ "jtag-missing-key": "error","no-unconditional-metabase-links-render": "error","no-color-literals": "error","no-literal-metabase-strings": "error",diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsxindex 5d7a541c938..ff06dc0fc4a 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx@@ -402,7 +402,7 @@ const TargetName = ({ policy, policyTable, target }: TargetNameProps) => {<span>{c("{0} is a name of a variable being used by row and column security",- ).jt`${(<strong>{target[1][1]}</strong>)} variable`}+ ).jt`${(<strong key="strong">{target[1][1]}</strong>)} variable`}</span>);} else if (target[0] === "dimension") {@@ -442,7 +442,8 @@ const TargetName = ({ policy, policyTable, target }: TargetNameProps) => {<span>{c("{0} is a name of a field being used by row and column security",- ).jt`${(<strong>{columnInfo.displayName}</strong>)} field`}+ )+ .jt`${(<strong key="strong">{columnInfo.displayName}</strong>)} field`}</span>);}}diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformPage/TargetSection/UpdateTargetModal/UpdateTargetModal.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformPage/TargetSection/UpdateTargetModal/UpdateTargetModal.tsxindex b150eb0c579..2d1d84df9c8 100644--- a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformPage/TargetSection/UpdateTargetModal/UpdateTargetModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformPage/TargetSection/UpdateTargetModal/UpdateTargetModal.tsx@@ -122,7 +122,7 @@ function UpdateTargetForm({value={shouldDeleteTarget.toString()}label={t`Keep the old target table, or delete it?`}description={jt`You can keep or delete ${(- <strong>{target.name}</strong>+ <strong key="strong">{target.name}</strong>)}. Deleting it can’t be undone, and will break queries that used it. Please be careful!`}onChange={(value) => setShouldDeleteTarget(value === "true")}>diff --git a/frontend/lint/eslint-rules/jtag-missing-key.js b/frontend/lint/eslint-rules/jtag-missing-key.jsnew file mode 100644index 00000000000..e644b400f63--- /dev/null+++ b/frontend/lint/eslint-rules/jtag-missing-key.js@@ -0,0 +1,165 @@+/**+ * Rule to require key props for JSX elements in jt`` tagged templates+ * jt`Something ${(<div>hello</div>)}` is an error as react will complain about the missing key prop+ */++const ERROR_MESSAGE =+ "JSX elements in jt`` tagged templates must have a key prop. Add key='unique-identifier' to the JSX element.";++// eslint-disable-next-line import/no-commonjs+module.exports = {+ meta: {+ type: "problem",+ docs: {+ description:+ "require key props for JSX elements in jt`` tagged templates",+ },+ schema: [], // no options+ fixable: null,+ },++ create(context) {+ // Track fragments that have reported errors to avoid double reporting+ const fragmentsWithErrors = new Set();++ /**+ * Check if a JSX element has a key prop+ * @param {Object} node - JSX element node+ * @returns {boolean} - true if element has key prop, false otherwise+ */+ function hasKeyProp(node) {+ if (!node.openingElement || !node.openingElement.attributes) {+ return false;+ }+ return node.openingElement.attributes.some(+ (attr) =>+ attr.type === "JSXAttribute" && attr.name && attr.name.name === "key",+ );+ }++ /**+ * Check if a JSX element is a direct child of a template expression+ */+ function isDirectChildOfTemplateExpression(node) {+ let current = node.parent;++ while (current) {+ // If we encounter another JSX element before reaching a template,+ // then we're nested inside JSX, not a direct template child+ if (current.type === "JSXElement" || current.type === "JSXFragment") {+ return false;+ }++ // If we find a template literal, we're a direct child+ if (current.type === "TemplateLiteral") {+ return true;+ }++ current = current.parent;+ }++ return false;+ }++ /**+ * Check if we're inside a jt`` tagged template and are a direct child+ */+ function isInJtTaggedTemplate(node) {+ // Only check direct children of template expressions+ if (!isDirectChildOfTemplateExpression(node)) {+ return false;+ }++ let current = node.parent;++ while (current) {+ // If we find a template literal, check if it's a jt tagged template+ if (current.type === "TemplateLiteral") {+ const templateParent = current.parent;+ if (+ templateParent &&+ templateParent.type === "TaggedTemplateExpression"+ ) {+ // Check if the tag is a member expression ending with 'jt' (like .jt``)+ if (+ templateParent.tag.type === "MemberExpression" &&+ templateParent.tag.property &&+ templateParent.tag.property.name === "jt"+ ) {+ return true;+ }+ // Check if the tag is an identifier 'jt' (like jt``)+ if (+ templateParent.tag.type === "Identifier" &&+ templateParent.tag.name === "jt"+ ) {+ return true;+ }+ }+ return false; // Template literal but not jt tagged+ }++ current = current.parent;+ }++ return false;+ }++ /**+ * Check if a JSX element is within a fragment that has errors+ */+ function isInFragmentWithErrors(node) {+ let current = node.parent;+ while (current) {+ if (+ current.type === "JSXFragment" &&+ fragmentsWithErrors.has(current)+ ) {+ return true;+ }+ current = current.parent;+ }+ return false;+ }++ return {+ JSXElement(node) {+ // Only check JSX elements that are inside jt`` tagged templates+ // Skip if the element is within a fragment that already has errors reported+ if (+ isInJtTaggedTemplate(node) &&+ !hasKeyProp(node) &&+ !isInFragmentWithErrors(node)+ ) {+ context.report({+ node,+ message: ERROR_MESSAGE,+ });+ }+ },++ JSXFragment(node) {+ // Check JSX fragments - they're allowed if all children have keys+ if (isInJtTaggedTemplate(node)) {+ const allChildrenHaveKeys = node.children.every((child) => {+ if (child.type === "JSXElement") {+ return hasKeyProp(child);+ }+ // JSXText, JSXExpressionContainer, etc. are fine+ return true;+ });++ if (!allChildrenHaveKeys) {+ // Track this fragment as having errors to prevent double reporting+ fragmentsWithErrors.add(node);+ context.report({+ node,+ message:+ "JSX fragments in jt`` tagged templates must have all JSX element children with key props.",+ });+ }+ }+ },+ };+ },+};diff --git a/frontend/lint/tests/jtag-missing-key.unit.spec.js b/frontend/lint/tests/jtag-missing-key.unit.spec.jsnew file mode 100644index 00000000000..4ebc1ae29e1--- /dev/null+++ b/frontend/lint/tests/jtag-missing-key.unit.spec.js@@ -0,0 +1,109 @@+import { RuleTester } from "eslint";++import jtagKey from "../eslint-rules/jtag-missing-key";++const ruleTester = new RuleTester({+ parserOptions: {+ ecmaVersion: 2015,+ sourceType: "module",+ ecmaFeatures: { jsx: true },+ },+});++const VALID_CASES = [+ {+ // JSX with key prop in jt`` tagged template+ code: `+const message = c("Context").jt\`Get started with \${(<EmbeddingTypeDropdown key="dropdown" />)}\`;`,+ },+ {+ // JSX with key prop in jt`` tagged template (direct jt)+ code: `+const message = jt\`Welcome \${(<div key="test-div">test</div>)}\`;`,+ },+ {+ // Multiple JSX elements with key props+ code: `+const message = t.jt\`Click \${(<button key="btn">here</button>)} or \${(<a key="link" href="#">there</a>)}\`;`,+ },+ {+ // JSX not in jt tagged template should be ignored+ code: `+const element = <div>Not in jt template</div>;`,+ },+ {+ // Regular template literal without JSX+ code: `+const message = jt\`Just a regular template with \${variable}\`;`,+ },+ {+ // Regular template literal not tagged with jt+ code: `+const message = \`Template with \${(<div>JSX</div>)}\`;`,+ },+ {+ // JSX fragment with all children having keys - valid+ code: `+const message = jt\`Fragment \${(<><Icon key="icon" name="test" /><span key="text">content</span></>)}\`;`,+ },+ {+ // JSX elements within props should be ignored - valid+ code: `+const message = jt\`Select time \${(<Select key="select" leftSection={<Icon name="calendar" />} />)}\`;`,+ },+ {+ // Nested JSX with outer key is valid - inner elements don't need keys for templates+ code: `+const message = jt\`rows in the \${(<strong key="table-name"><EntityName entityType="tables" entityId={id} /></strong>)} table\`;`,+ },+];++const INVALID_CASES = [+ {+ name: "JSX element without key in jt`` tagged template (member expression)",+ code: `+const message = jt\`Get started with \${(<EmbeddingTypeDropdown />)}\`;`,+ error: /JSX elements in jt`` tagged templates must have a key prop/,+ },+ {+ name: "JSX element without key in jt`` tagged template (direct identifier)",+ code: `+const message = jt\`Welcome \${(<div>test</div>)}\`;`,+ error: /JSX elements in jt`` tagged templates must have a key prop/,+ },+ {+ name: "Multiple JSX elements, one missing key",+ code: `+const message = jt\`Click \${(<button key="btn">here</button>)} or \${(<a href="#">there</a>)}\`;`,+ error: /JSX elements in jt`` tagged templates must have a key prop/,+ },+ {+ name: "JSX element without key (only direct children flagged)",+ code: `+const message = jt\`Hello \${(<div><span>nested</span></div>)}\`;`,+ error: /JSX elements in jt`` tagged templates must have a key prop/,+ errorCount: 1, // Only the direct child (div) needs key, nested span is React's responsibility+ },+ {+ name: "JSX fragment with missing keys on children",+ code: `+const message = jt\`Fragment \${(<><Icon name="test" /><span>content</span></>)}\`;`,+ error:+ /JSX fragments in jt`` tagged templates must have all JSX element children with key props/,+ },+];++ruleTester.run("jtag-key", jtagKey, {+ valid: VALID_CASES,+ invalid: INVALID_CASES.map((invalidCase) => {+ const errorCount = invalidCase.errorCount || 1;+ return {+ code: invalidCase.code,+ errors: Array(errorCount)+ .fill()+ .map(() => ({+ message: invalidCase.error,+ })),+ };+ }),+});diff --git a/frontend/src/metabase/admin/permissions/components/DataPermissionsHelp/DataPermissionsHelp.tsx b/frontend/src/metabase/admin/permissions/components/DataPermissionsHelp/DataPermissionsHelp.tsxindex 76d4a9ddec6..b752241ec64 100644--- a/frontend/src/metabase/admin/permissions/components/DataPermissionsHelp/DataPermissionsHelp.tsx+++ b/frontend/src/metabase/admin/permissions/components/DataPermissionsHelp/DataPermissionsHelp.tsx@@ -225,7 +225,7 @@ export const DataPermissionsHelp = () => {<Text component="footer" ta="center" py="1.5rem" fw={600}>{jt`${(- <ExternalLink href={docsUrl}>{t`Learn more`}</ExternalLink>+ <ExternalLink key="link" href={docsUrl}>{t`Learn more`}</ExternalLink>)} about data permissions`}</Text></Flex>diff --git a/frontend/src/metabase/admin/settings/auth/components/AuthCard/AuthCard.tsx b/frontend/src/metabase/admin/settings/auth/components/AuthCard/AuthCard.tsxindex a3d5f825093..6691574659f 100644--- a/frontend/src/metabase/admin/settings/auth/components/AuthCard/AuthCard.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/AuthCard/AuthCard.tsx@@ -64,7 +64,7 @@ export const AuthCard = ({const footer = isEnvSetting ? (<Text>{c("{0} is the name of a variable")- .jt`Set with env var ${(<Anchor href={docsUrl} target="_blank">{`$${setting.env_name}`}</Anchor>)}`}+ .jt`Set with env var ${(<Anchor key="anchor" href={docsUrl} target="_blank">{`$${setting.env_name}`}</Anchor>)}`}</Text>) : null;diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/QuestionMoveConfirmModal.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/QuestionMoveConfirmModal.tsxindex 02f1e1c1b5b..0bf230b6558 100644--- a/frontend/src/metabase/collections/components/CollectionBulkActions/QuestionMoveConfirmModal.tsx+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/QuestionMoveConfirmModal.tsx@@ -147,11 +147,11 @@ export const QuestionMoveConfirmModal = ({return (<List.Item key={`card-${cd.card_id}`}><Text>{jt`${(- <Text component="span" fw={700}>+ <Text key="name" component="span" fw={700}>{card?.name}</Text>)} will be removed from ${(- <DashboardNames names={dashboardNames} />+ <DashboardNames key="names" names={dashboardNames} />)}`}</Text></List.Item>);diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsxindex 77d55080a1c..7d21dec198e 100644--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx@@ -102,7 +102,9 @@ const DashCardLoadingView = ({}if (expectedDuration) {return jt`This usually takes around ${(- <span className={CS.textNoWrap}>{duration(expectedDuration)}</span>+ <span key="duration" className={CS.textNoWrap}>+ {duration(expectedDuration)}+ </span>)}.`;}};diff --git a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsxindex 108ec9bfe41..c86b436d4f1 100644--- a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx@@ -77,6 +77,7 @@ const DashboardMoveToast = ({.jt`Dashboard moved to ${collection ? (<Link+ key="link"className={S.CollectionLink}to={Urls.collection(collection)}style={{ marginInlineStart: ".25em" }}diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActions.tsxindex c1b899a5503..18174248b53 100644--- a/frontend/src/metabase/models/components/ModelActions/ModelActions.tsx+++ b/frontend/src/metabase/models/components/ModelActions/ModelActions.tsx@@ -18,7 +18,7 @@ function ModelActions({ model, shouldShowActionsUI }: Props) {<Title order={2}><Group gap="sm">{jt`Actions for ${(- <Group gap="xs">+ <Group key="group" gap="xs"><Icon name="model" size={24} /><Link variant="brand" to={Urls.model({ id: model.id() })}>{model.displayName()}diff --git a/frontend/src/metabase/query_builder/components/MoveQuestionModal/MoveQuestionModal.tsx b/frontend/src/metabase/query_builder/components/MoveQuestionModal/MoveQuestionModal.tsxindex 8df83531b2e..69e537d4d7c 100644--- a/frontend/src/metabase/query_builder/components/MoveQuestionModal/MoveQuestionModal.tsx+++ b/frontend/src/metabase/query_builder/components/MoveQuestionModal/MoveQuestionModal.tsx@@ -162,8 +162,13 @@ export const MoveQuestionModal = ({"{0} is the dashboard name the question currently has dashcards in",).jt`Do you still want this question to appear in ${(<>- <Icon name="dashboard" style={{ marginBottom: -2 }} size={20} />{" "}- <Dashboards.Name id={question.dashboardId()} />+ <Icon+ key="icon"+ name="dashboard"+ style={{ marginBottom: -2 }}+ size={20}+ />{" "}+ <Dashboards.Name key="name" id={question.dashboardId()} /></>)}?`}</Title>@@ -208,8 +213,13 @@ export const MoveQuestionModal = ({{c("{0} is the name of a dashboard").jt`Moving this question to another dashboard will remove it from ${(<>- <Icon name="dashboard" style={{ marginBottom: -2 }} size={20} />{" "}- <Dashboards.Name id={question.dashboardId()} />+ <Icon+ key="icon"+ name="dashboard"+ style={{ marginBottom: -2 }}+ size={20}+ />{" "}+ <Dashboards.Name key="name" id={question.dashboardId()} /></>)}`}</Title>diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.jsxindex 27c20edb393..601aedc4bf0 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx@@ -145,7 +145,7 @@ const MapNotFound = () => {{isAdmin && (<Text component="p" className={CS.mt1}>{jt`To add a new map, visit ${(- <Link to="/admin/settings/maps" className={CS.link}>+ <Link key="link" to="/admin/settings/maps" className={CS.link}>{t`Admin settings > Maps`}</Link>)}.`}