from-definition.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import attributes from './attributes';
  2. import condition from './condition';
  3. import explicitRole from './explicit-role';
  4. import implicitRole from './implicit-role';
  5. import nodeName from './node-name';
  6. import properties from './properties';
  7. import semanticRole from './semantic-role';
  8. import AbstractVirtualNode from '../../core/base/virtual-node/abstract-virtual-node';
  9. import { getNodeFromTree, matches } from '../../core/utils';
  10. const matchers = {
  11. attributes,
  12. condition,
  13. explicitRole,
  14. implicitRole,
  15. nodeName,
  16. properties,
  17. semanticRole
  18. };
  19. /**
  20. * Check if a virtual node matches some definition
  21. *
  22. * Note: matches.fromDefinition(vNode, definition) can be indirectly used through
  23. * matches(vNode, definition)
  24. *
  25. * Example:
  26. * ```js
  27. * matches.fromDefinition(vNode, {
  28. * nodeName: ['div', 'span']
  29. * attributes: {
  30. * 'aria-live': 'assertive'
  31. * }
  32. * })
  33. * ```
  34. *
  35. * @deprecated HTMLElement is deprecated, use VirtualNode instead
  36. *
  37. * @private
  38. * @param {HTMLElement|VirtualNode} vNode
  39. * @param {Object|Array<Object>} definition
  40. * @returns {Boolean}
  41. */
  42. function fromDefinition(vNode, definition) {
  43. if (!(vNode instanceof AbstractVirtualNode)) {
  44. vNode = getNodeFromTree(vNode);
  45. }
  46. if (Array.isArray(definition)) {
  47. return definition.some(definitionItem =>
  48. fromDefinition(vNode, definitionItem)
  49. );
  50. }
  51. if (typeof definition === 'string') {
  52. return matches(vNode, definition);
  53. }
  54. return Object.keys(definition).every(matcherName => {
  55. if (!matchers[matcherName]) {
  56. throw new Error(`Unknown matcher type "${matcherName}"`);
  57. }
  58. // Find the specific matches method to.
  59. // matches.attributes, matches.nodeName, matches.properties, etc.
  60. const matchMethod = matchers[matcherName];
  61. // Find the matcher that goes into the matches method.
  62. // 'div', /^div$/, (str) => str === 'div', etc.
  63. const matcher = definition[matcherName];
  64. return matchMethod(vNode, matcher);
  65. });
  66. }
  67. export default fromDefinition;