124aa3c4 by Adam Heath

Add a 'contains' pseudo-class, used to match against text children of a

node.
1 parent ea13aa94
...@@ -96,6 +96,14 @@ const compileMatcher = (ast: AST, selector: string): MatcherProducer => { ...@@ -96,6 +96,14 @@ const compileMatcher = (ast: AST, selector: string): MatcherProducer => {
96 } 96 }
97 } 97 }
98 98
99 const getNodeText = (node) => {
100 if (node.type === TEXT_NODE) return node.value
101 if (node.type !== ELEMENT_NODE) return ''
102 const { children } = node
103 if (children.length === 0) return ''
104 return children.map(getNodeText).join('')
105 }
106
99 const getAttrValueMatch = (value: string, operator: string = '=', caseSensitive: boolean): AttrValueMatch => { 107 const getAttrValueMatch = (value: string, operator: string = '=', caseSensitive: boolean): AttrValueMatch => {
100 if (value === undefined) return (attrValue) => attrValue !== undefined 108 if (value === undefined) return (attrValue) => attrValue !== undefined
101 if (value[ 0 ] === '"' || value[ 0 ] === '\'') value = value.substring(1, value.length - 1) 109 if (value[ 0 ] === '"' || value[ 0 ] === '\'') value = value.substring(1, value.length - 1)
...@@ -267,6 +275,13 @@ const compileMatcher = (ast: AST, selector: string): MatcherProducer => { ...@@ -267,6 +275,13 @@ const compileMatcher = (ast: AST, selector: string): MatcherProducer => {
267 return nthChildMatcher(context, node, parent, pos + 1, debug || parent?.name === 'body') 275 return nthChildMatcher(context, node, parent, pos + 1, debug || parent?.name === 'body')
268 } 276 }
269 } 277 }
278 case 'contains': {
279 const contentValueMatch = getAttrValueMatch(ast.argument, '*=', false)
280 return (context, node, parent, i, debug) => {
281 const nodeText = getNodeText(node)
282 return contentValueMatch(nodeText)
283 }
284 }
270 default: 285 default:
271 console.error('pseudo-class', nodeUtil.inspect({ selector, ast }, { depth: null, colors: true })) 286 console.error('pseudo-class', nodeUtil.inspect({ selector, ast }, { depth: null, colors: true }))
272 throw new Error(`Unknown pseudo-class: ${ast.name}`) 287 throw new Error(`Unknown pseudo-class: ${ast.name}`)
......