|
| 1 | +const {elementType, getProp, getPropValue} = require('jsx-ast-utils') |
| 2 | + |
| 3 | +const bannedLinkText = ['read more', 'here', 'click here', 'learn more', 'more', 'here'] |
| 4 | + |
| 5 | +/* Downcase and strip extra whitespaces and punctuation */ |
| 6 | +const stripAndDowncaseText = text => { |
| 7 | + return text |
| 8 | + .toLowerCase() |
| 9 | + .replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '') |
| 10 | + .replace(/\s{2,}/g, ' ') |
| 11 | + .trim() |
| 12 | +} |
| 13 | + |
| 14 | +module.exports = { |
| 15 | + meta: { |
| 16 | + docs: { |
| 17 | + description: 'disallow generic link text', |
| 18 | + url: require('../url')(module) |
| 19 | + }, |
| 20 | + schema: [] |
| 21 | + }, |
| 22 | + |
| 23 | + create(context) { |
| 24 | + return { |
| 25 | + JSXOpeningElement: node => { |
| 26 | + if (elementType(node) !== 'a') return |
| 27 | + if (getProp(node.attributes, 'aria-labelledby')) return |
| 28 | + |
| 29 | + const ariaLabel = getPropValue(getProp(node.attributes, 'aria-label')) |
| 30 | + const cleanAriaLabelValue = ariaLabel && stripAndDowncaseText(ariaLabel) |
| 31 | + |
| 32 | + if (ariaLabel) { |
| 33 | + if (bannedLinkText.includes(cleanAriaLabelValue)) { |
| 34 | + context.report({ |
| 35 | + node, |
| 36 | + message: |
| 37 | + 'Avoid setting generic link text like `Here`, `Click here`, `Read more`. Make sure that your link text is both descriptive and concise.' |
| 38 | + }) |
| 39 | + } |
| 40 | + } else { |
| 41 | + const parent = node.parent |
| 42 | + if (parent.children && parent.children.length === 1 && parent.children[0].type === 'JSXText') { |
| 43 | + const textContent = stripAndDowncaseText(parent.children[0].value) |
| 44 | + if (!bannedLinkText.includes(textContent)) return |
| 45 | + context.report({ |
| 46 | + node, |
| 47 | + message: |
| 48 | + 'Avoid setting generic link text like `Here`, `Click here`, `Read more`. Make sure that your link text is both descriptive and concise.' |
| 49 | + }) |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments