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