|
| 1 | +import { VChild } from './type'; |
| 2 | + |
| 3 | +const { slice } = Array.prototype; |
| 4 | + |
| 5 | +export function create(vNode: VChild) { |
| 6 | + if (typeof vNode === 'string') return document.createTextNode(vNode); |
| 7 | + |
| 8 | + const { tagName, childNodes, ...props } = vNode; |
| 9 | + |
| 10 | + return Object.assign(document.createElement(tagName), props); |
| 11 | +} |
| 12 | + |
| 13 | +const cache = new WeakMap(); |
| 14 | + |
| 15 | +function save(root: Node, id: string, child: Node) { |
| 16 | + var map = cache.get(root); |
| 17 | + |
| 18 | + if (!map) cache.set(root, (map = {})); |
| 19 | + |
| 20 | + map[id] = child; |
| 21 | +} |
| 22 | + |
| 23 | +export function update(node: Element, vNode: VChild) { |
| 24 | + if (typeof vNode === 'string') return node.replaceWith(vNode); |
| 25 | + |
| 26 | + const { tagName, childNodes, ...props } = vNode; |
| 27 | + |
| 28 | + if (node.tagName?.toLowerCase() !== tagName) { |
| 29 | + const tag = document.createElement(tagName); |
| 30 | + |
| 31 | + node.replaceWith(tag); |
| 32 | + |
| 33 | + node = tag; |
| 34 | + } |
| 35 | + |
| 36 | + const prop_map = Object.entries(props); |
| 37 | + |
| 38 | + for (const { name } of node.attributes) { |
| 39 | + const [key] = |
| 40 | + prop_map.find(([key]) => key.toLowerCase() === name) || []; |
| 41 | + |
| 42 | + if (!key) node.removeAttribute(name); |
| 43 | + } |
| 44 | + |
| 45 | + for (const [key, value] of prop_map) |
| 46 | + if (value !== node[key]) node[key] = value; |
| 47 | + |
| 48 | + const children = node.childNodes; |
| 49 | + |
| 50 | + vNode.childNodes.forEach((child, index) => { |
| 51 | + var old = children[index]; |
| 52 | + |
| 53 | + if (!old) { |
| 54 | + old = create(child); |
| 55 | + |
| 56 | + if (child.id) save(node, child.id, old); |
| 57 | + |
| 58 | + node.append(old); |
| 59 | + } else { |
| 60 | + const cached = cache.get(node)?.[child.id]; |
| 61 | + |
| 62 | + if (cached) { |
| 63 | + old.before(cached); |
| 64 | + |
| 65 | + old = cached; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + update(old as Element, child); |
| 70 | + }); |
| 71 | + |
| 72 | + for (const child of slice.call(children, vNode.childNodes.length)) |
| 73 | + child.remove(); |
| 74 | +} |
0 commit comments