extract-namespaces-to-root.js 745 B

1234567891011121314151617181920212223242526272829303132333435
  1. const { getRoot } = require('../utils');
  2. /**
  3. * @return {Function} PostHTML plugin
  4. */
  5. function extractNamespacesToRoot() {
  6. return (tree) => {
  7. const namespaces = {};
  8. tree.match({ tag: /.*/ }, (node) => {
  9. const attrs = node.attrs || {};
  10. Object.keys(attrs).forEach((attr) => {
  11. if (attr.startsWith('xmlns')) {
  12. if (attr in namespaces === false) {
  13. namespaces[attr] = attrs[attr];
  14. }
  15. delete node.attrs[attr];
  16. }
  17. });
  18. return node;
  19. });
  20. const root = getRoot(tree);
  21. root.attrs = root.attrs || {};
  22. Object.keys(namespaces).forEach(name => root.attrs[name] = namespaces[name]);
  23. return tree;
  24. };
  25. }
  26. module.exports = extractNamespacesToRoot;