no-boolean-default.js 2.2 KB

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