3f061832 by Adam Heath

Convert the nodeProxyHandler to a class.

1 parent eaa705ab
Showing 1 changed file with 16 additions and 10 deletions
......@@ -307,34 +307,40 @@ export const createMatcher = (selector: string): Matcher => {
return newMatcherCreater()
}
const nodeProxyHandler = {
class NodeProxyHandler {
#cache
constructor() {
this.#cache = {}
}
get(target, prop, receiver) {
const { _proxy } = target
if (prop in _proxy) return _proxy[ prop ]
if (prop in this.#cache) return this.#cache[ prop ]
const { [ prop ]: origValue } = target
if (!origValue) return origValue
switch (prop) {
case 'attributes':
return _proxy[ prop ] = (origValue ? Object.fromEntries(Object.entries(origValue).map(([ key, value ]) => {
return this.#cache[ prop ] = (origValue ? Object.fromEntries(Object.entries(origValue).map(([ key, value ]) => {
return [ key, decode(value) ]
})) : origValue)
return newValue
case 'parent':
return _proxy[ prop ] = proxyNode(origValue)
return this.#cache[ prop ] = proxyNode(origValue)
case 'children':
return _proxy[ prop ] = origValue.map((child) => proxyNode(child))
return this.#cache[ prop ] = origValue.map((child) => proxyNode(child))
default:
if (typeof origValue === 'function') {
return this.#cache[ prop ] = (...args) => {
origValue.apply(target, ...args)
}
}
return origValue
}
}
}
const proxyNode = (node) => {
const { _proxy: { proxy } = {} } = node
if (proxy) return proxy
const newProxy = new Proxy(node, nodeProxyHandler)
node._proxy = { proxy: newProxy }
return newProxy
return new Proxy(node, new NodeProxyHandler())
}
export const parseHtml = (html: string): NodeType => {
......