node-attributes.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Return attributes and values of a node in a convenient way:
  2. /* example:
  3. <ExampleElement attr1="15" attr2>
  4. { attr1: {
  5. hasValue: true,
  6. value: 15
  7. },
  8. attr2: {
  9. hasValue: false
  10. }
  11. Inclusion of hasValue is in case an eslint rule cares about boolean values
  12. explicitly assigned to attribute vs the attribute being used as a flag
  13. */
  14. class NodeAttributes {
  15. constructor(ASTnode) {
  16. this.attributes = {}
  17. ASTnode.attributes.forEach((attribute) => {
  18. if (!attribute.type || attribute.type !== 'JSXAttribute') {
  19. return
  20. }
  21. this.attributes[attribute.name.name] = {
  22. hasValue: !!attribute.value,
  23. }
  24. if (attribute.value) {
  25. if (attribute.value.value) {
  26. this.attributes[attribute.name.name].value = attribute.value.value
  27. } else if (attribute.value.expression) {
  28. this.attributes[attribute.name.name].value =
  29. typeof attribute.value.expression.value !== 'undefined'
  30. ? attribute.value.expression.value
  31. : attribute.value.expression.properties
  32. }
  33. }
  34. })
  35. }
  36. hasAny() {
  37. return !!Object.keys(this.attributes).length
  38. }
  39. has(attrName) {
  40. return !!this.attributes[attrName]
  41. }
  42. hasValue(attrName) {
  43. return !!this.attributes[attrName].hasValue
  44. }
  45. value(attrName) {
  46. if (!this.attributes[attrName]) {
  47. return true
  48. }
  49. return this.attributes[attrName].value
  50. }
  51. }
  52. module.exports = NodeAttributes