82b35ef4 by Adam Heath

Allow for finding multiple matching nodes.

1 parent 3312ebad
Showing 1 changed file with 18 additions and 13 deletions
......@@ -396,24 +396,29 @@ export const parseHtml = (html: string, options): NodeType => {
return proxyNode(cached, options)
}
export const findNode = (doc: NodeType, selector: string): NodeType => {
export const findNode = (doc: NodeType, selector: string, options = { single: true }): NodeType => {
if (!selector) return doc
let docCache = findNodeCache.get(doc)
if (!docCache) {
docCache = new TTLCache({ ttl: 10*60 })
findNodeCache.set(doc, docCache)
}
const found = docCache.get(selector)
if (found !== undefined) return found[0]
//console.log('cache miss', {selector})
const matcher = createMatcher(selector)
try {
walkSync(doc, (node, parent, index) => {
if (matcher(node, parent, index)) throw node
})
} catch (e) {
if (e instanceof Error) throw e
docCache.set(selector, [ e ])
return e
let found = docCache.get(selector)
if (found === undefined) {
const matcher = createMatcher(selector)
found = []
try {
walkSync(doc, (node, parent, index) => {
if (node && node.type !== ELEMENT_NODE) return
if (matcher(node, parent, index)) {
found.push(node)
if (options.single) throw node
}
})
} catch (e) {
if (e instanceof Error) throw e
}
docCache.set(selector, found)
}
return options.single ? found[ 0 ] : found
}
......