tovnode.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { addNS } from "./h.js";
  2. import { vnode } from "./vnode.js";
  3. import { htmlDomApi } from "./htmldomapi.js";
  4. export function toVNode(node, domApi) {
  5. const api = domApi !== undefined ? domApi : htmlDomApi;
  6. let text;
  7. if (api.isElement(node)) {
  8. const id = node.id ? "#" + node.id : "";
  9. const cn = node.getAttribute("class");
  10. const c = cn ? "." + cn.split(" ").join(".") : "";
  11. const sel = api.tagName(node).toLowerCase() + id + c;
  12. const attrs = {};
  13. const dataset = {};
  14. const data = {};
  15. const children = [];
  16. let name;
  17. let i, n;
  18. const elmAttrs = node.attributes;
  19. const elmChildren = node.childNodes;
  20. for (i = 0, n = elmAttrs.length; i < n; i++) {
  21. name = elmAttrs[i].nodeName;
  22. if (name.startsWith("data-")) {
  23. dataset[name.slice(5)] = elmAttrs[i].nodeValue || "";
  24. }
  25. else if (name !== "id" && name !== "class") {
  26. attrs[name] = elmAttrs[i].nodeValue;
  27. }
  28. }
  29. for (i = 0, n = elmChildren.length; i < n; i++) {
  30. children.push(toVNode(elmChildren[i], domApi));
  31. }
  32. if (Object.keys(attrs).length > 0)
  33. data.attrs = attrs;
  34. if (Object.keys(dataset).length > 0)
  35. data.dataset = dataset;
  36. if (sel.startsWith("svg") &&
  37. (sel.length === 3 || sel[3] === "." || sel[3] === "#")) {
  38. addNS(data, children, sel);
  39. }
  40. return vnode(sel, data, children, undefined, node);
  41. }
  42. else if (api.isText(node)) {
  43. text = api.getTextContent(node);
  44. return vnode(undefined, undefined, undefined, text, node);
  45. }
  46. else if (api.isComment(node)) {
  47. text = api.getTextContent(node);
  48. return vnode("!", {}, [], text, node);
  49. }
  50. else {
  51. return vnode("", {}, [], undefined, node);
  52. }
  53. }
  54. //# sourceMappingURL=tovnode.js.map