|
| 1 | +/** |
| 2 | + * @fileoverview Prevent JSX prop spreading the same expression multiple times |
| 3 | + * @author Simon Schick |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +const docsUrl = require('../util/docsUrl'); |
| 9 | +const report = require('../util/report'); |
| 10 | + |
| 11 | +// ------------------------------------------------------------------------------ |
| 12 | +// Rule Definition |
| 13 | +// ------------------------------------------------------------------------------ |
| 14 | + |
| 15 | +const messages = { |
| 16 | + noMultiSpreading: 'Spreading the same expression multiple times is forbidden', |
| 17 | +}; |
| 18 | + |
| 19 | +const ignoredAstProperties = new Set(['parent', 'range', 'loc', 'start', 'end', '_babelType']); |
| 20 | + |
| 21 | +/** |
| 22 | + * Filter for JSON.stringify that omits circular and position structures. |
| 23 | + * |
| 24 | + * @param {string} key |
| 25 | + * @param {*} value |
| 26 | + * @returns {*} |
| 27 | + */ |
| 28 | +const propertyFilter = (key, value) => (ignoredAstProperties.has(key) ? undefined : value); |
| 29 | + |
| 30 | +module.exports = { |
| 31 | + meta: { |
| 32 | + docs: { |
| 33 | + description: 'Disallow JSX prop spreading the same expression multiple times', |
| 34 | + category: 'Best Practices', |
| 35 | + recommended: false, |
| 36 | + url: docsUrl('jsx-props-no-spread-multi'), |
| 37 | + }, |
| 38 | + messages, |
| 39 | + }, |
| 40 | + |
| 41 | + create(context) { |
| 42 | + return { |
| 43 | + JSXOpeningElement(node) { |
| 44 | + const spreads = node.attributes.filter((attr) => attr.type === 'JSXSpreadAttribute'); |
| 45 | + if (spreads.length < 2) { |
| 46 | + return; |
| 47 | + } |
| 48 | + // We detect duplicate expressions by hashing the ast nodes |
| 49 | + const argumentHashes = new Set(); |
| 50 | + for (const spread of spreads) { |
| 51 | + // TODO: Deep compare ast function? |
| 52 | + const hash = JSON.stringify(spread.argument, propertyFilter); |
| 53 | + if (argumentHashes.has(hash)) { |
| 54 | + report(context, messages.noMultiSpreading, 'noMultiSpreading', { |
| 55 | + node: spread, |
| 56 | + }); |
| 57 | + } |
| 58 | + argumentHashes.add(hash); |
| 59 | + } |
| 60 | + }, |
| 61 | + }; |
| 62 | + }, |
| 63 | +}; |
0 commit comments