|
| 1 | +/** |
| 2 | + * @fileoverview Prevents boolean defaults from being set |
| 3 | + * @author Hiroki Osame |
| 4 | + */ |
| 5 | +'use strict' |
| 6 | + |
| 7 | +const utils = require('../utils') |
| 8 | + |
| 9 | +// ------------------------------------------------------------------------------ |
| 10 | +// Rule Definition |
| 11 | +// ------------------------------------------------------------------------------ |
| 12 | + |
| 13 | +function isBooleanProp (prop) { |
| 14 | + return ( |
| 15 | + prop.type === 'Property' && |
| 16 | + prop.key.type === 'Identifier' && |
| 17 | + prop.key.name === 'type' && |
| 18 | + prop.value.type === 'Identifier' && |
| 19 | + prop.value.name === 'Boolean' |
| 20 | + ) |
| 21 | +} |
| 22 | + |
| 23 | +function getBooleanProps (props) { |
| 24 | + return props |
| 25 | + .filter(prop => ( |
| 26 | + prop.value && |
| 27 | + prop.value.properties && |
| 28 | + prop.value.properties.find(isBooleanProp) |
| 29 | + )) |
| 30 | +} |
| 31 | + |
| 32 | +function getDefaultNode (propDef) { |
| 33 | + return propDef.value.properties.find(p => { |
| 34 | + return ( |
| 35 | + p.type === 'Property' && |
| 36 | + p.key.type === 'Identifier' && |
| 37 | + p.key.name === 'default' |
| 38 | + ) |
| 39 | + }) |
| 40 | +} |
| 41 | + |
| 42 | +module.exports = { |
| 43 | + meta: { |
| 44 | + type: 'suggestion', |
| 45 | + docs: { |
| 46 | + description: 'disallow boolean defaults', |
| 47 | + category: undefined, |
| 48 | + url: 'https://eslint.vuejs.org/rules/no-boolean-default.html' |
| 49 | + }, |
| 50 | + fixable: 'code', |
| 51 | + schema: [ |
| 52 | + { |
| 53 | + enum: ['default-false', 'no-default'] |
| 54 | + } |
| 55 | + ] |
| 56 | + }, |
| 57 | + |
| 58 | + create (context) { |
| 59 | + return utils.executeOnVueComponent(context, (obj) => { |
| 60 | + const props = utils.getComponentProps(obj) |
| 61 | + const booleanProps = getBooleanProps(props) |
| 62 | + |
| 63 | + if (!booleanProps.length) return |
| 64 | + |
| 65 | + const booleanType = context.options[0] || 'no-default' |
| 66 | + |
| 67 | + booleanProps.forEach((propDef) => { |
| 68 | + const defaultNode = getDefaultNode(propDef) |
| 69 | + |
| 70 | + switch (booleanType) { |
| 71 | + case 'no-default': |
| 72 | + if (defaultNode) { |
| 73 | + context.report({ |
| 74 | + node: defaultNode, |
| 75 | + message: 'Boolean prop should not set a default (Vue defaults it to false).' |
| 76 | + }) |
| 77 | + } |
| 78 | + break |
| 79 | + |
| 80 | + case 'default-false': |
| 81 | + if (defaultNode.value.value !== false) { |
| 82 | + context.report({ |
| 83 | + node: defaultNode, |
| 84 | + message: 'Boolean prop should be defaulted to false.' |
| 85 | + }) |
| 86 | + } |
| 87 | + break |
| 88 | + } |
| 89 | + }) |
| 90 | + }) |
| 91 | + } |
| 92 | +} |
0 commit comments