3497e932 by Adam Heath

Add options when parsing html, and if for react use, map certain

attributes.
1 parent 3f061832
......@@ -307,9 +307,17 @@ export const createMatcher = (selector: string): Matcher => {
return newMatcherCreater()
}
const reactAttributeMap = {
'class': 'className',
'srcset': 'srcSet',
'maxlength': 'maxLength',
}
class NodeProxyHandler {
#options
#cache
constructor() {
constructor(options = {}) {
this.#options = options
this.#cache = {}
}
......@@ -321,13 +329,18 @@ class NodeProxyHandler {
switch (prop) {
case 'attributes':
return this.#cache[ prop ] = (origValue ? Object.fromEntries(Object.entries(origValue).map(([ key, value ]) => {
return [ key, decode(value) ]
const decoded = decode(value)
if (this.#options.react) {
const { [ key ]: newKey } = reactAttributeMap
if (newKey) return [ newKey, decoded ]
}
return [ key, decoded ]
})) : origValue)
return newValue
case 'parent':
return this.#cache[ prop ] = proxyNode(origValue)
return this.#cache[ prop ] = proxyNode(origValue, this.#options)
case 'children':
return this.#cache[ prop ] = origValue.map((child) => proxyNode(child))
return this.#cache[ prop ] = origValue.map((child) => proxyNode(child, this.#options))
default:
if (typeof origValue === 'function') {
return this.#cache[ prop ] = (...args) => {
......@@ -339,16 +352,16 @@ class NodeProxyHandler {
}
}
const proxyNode = (node) => {
return new Proxy(node, new NodeProxyHandler())
const proxyNode = (node, options) => {
return new Proxy(node, new NodeProxyHandler(options))
}
export const parseHtml = (html: string): NodeType => {
export const parseHtml = (html: string, options): NodeType => {
const cached = parsedHtmlCache.get(html)
if (cached) return proxyNode(cached)
if (cached) return proxyNode(cached, options)
const doc = ultraParse(html)
parsedHtmlCache.set(html, doc)
return proxyNode(doc)
return proxyNode(doc, options)
}
export const findNode = (doc: NodeType, selector: string): NodeType => {
......