|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0 and the Server Side Public License, v 1; you may not use this file except |
| 5 | + * in compliance with, at your election, the Elastic License 2.0 or the Server |
| 6 | + * Side Public License, v 1. |
| 7 | + */ |
| 8 | + |
| 9 | +import { TSESTree, ESLintUtils } from '@typescript-eslint/utils'; |
| 10 | + |
| 11 | +import { hasSpread } from '../utils/has_spread'; |
| 12 | + |
| 13 | +export const RequireHrefForLink = ESLintUtils.RuleCreator.withoutDocs({ |
| 14 | + create(context) { |
| 15 | + return { |
| 16 | + JSXOpeningElement(node: TSESTree.JSXOpeningElement): void { |
| 17 | + if ( |
| 18 | + node.name.type !== 'JSXIdentifier' || |
| 19 | + node.name.name !== 'EuiLink' |
| 20 | + ) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + // Bail out if props are spread — we can't statically determine |
| 25 | + // whether `href` is provided via the spread |
| 26 | + if (hasSpread(node.attributes)) { |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + // Check if the node has `href` and `onClick` attributes |
| 31 | + const hasHref = node.attributes.some( |
| 32 | + (attr) => attr.type === 'JSXAttribute' && attr.name.name === 'href' |
| 33 | + ); |
| 34 | + const hasOnClick = node.attributes.some( |
| 35 | + (attr) => attr.type === 'JSXAttribute' && attr.name.name === 'onClick' |
| 36 | + ); |
| 37 | + |
| 38 | + // Report an issue if `onClick` is present without `href` |
| 39 | + if (hasOnClick && !hasHref) { |
| 40 | + context.report({ |
| 41 | + node, |
| 42 | + messageId: 'requireHrefForLink', |
| 43 | + data: { |
| 44 | + name: node.name.name, |
| 45 | + }, |
| 46 | + }); |
| 47 | + } |
| 48 | + }, |
| 49 | + }; |
| 50 | + }, |
| 51 | + meta: { |
| 52 | + type: 'suggestion', |
| 53 | + docs: { |
| 54 | + description: |
| 55 | + 'Recommend including `href` alongside `onClick` on EuiLink so that Ctrl/Cmd+Click (open link in new tab) works.', |
| 56 | + }, |
| 57 | + schema: [], |
| 58 | + messages: { |
| 59 | + requireHrefForLink: |
| 60 | + '<{{name}}> has `onClick` but no `href`. Consider adding `href` so that the component renders as a link and supports Ctrl/Cmd+Click / "Open link in new tab".', |
| 61 | + }, |
| 62 | + }, |
| 63 | + defaultOptions: [], |
| 64 | +}); |
0 commit comments