selector.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. 'use strict'
  2. const parser = require('postcss-selector-parser')
  3. const { default: nthCheck } = require('nth-check')
  4. const { getAttribute, isVElement } = require('.')
  5. /**
  6. * @typedef {object} VElementSelector
  7. * @property {(element: VElement)=>boolean} test
  8. */
  9. module.exports = {
  10. parseSelector
  11. }
  12. /**
  13. * Parses CSS selectors and returns an object with a function that tests VElement.
  14. * @param {string} selector CSS selector
  15. * @param {RuleContext} context - The rule context.
  16. * @returns {VElementSelector}
  17. */
  18. function parseSelector(selector, context) {
  19. let astSelector
  20. try {
  21. astSelector = parser().astSync(selector)
  22. } catch (error) {
  23. context.report({
  24. loc: { line: 0, column: 0 },
  25. message: `Cannot parse selector: ${selector}.`
  26. })
  27. return {
  28. test: () => false
  29. }
  30. }
  31. try {
  32. const test = selectorsToVElementMatcher(astSelector.nodes)
  33. return {
  34. test(element) {
  35. return test(element, null)
  36. }
  37. }
  38. } catch (error) {
  39. if (error instanceof SelectorError) {
  40. context.report({
  41. loc: { line: 0, column: 0 },
  42. message: error.message
  43. })
  44. return {
  45. test: () => false
  46. }
  47. }
  48. throw error
  49. }
  50. }
  51. class SelectorError extends Error {}
  52. /**
  53. * @typedef {(element: VElement, subject: VElement | null )=>boolean} VElementMatcher
  54. * @typedef {Exclude<parser.Selector['nodes'][number], {type:'comment'|'root'}>} ChildNode
  55. */
  56. /**
  57. * Convert nodes to VElementMatcher
  58. * @param {parser.Selector[]} selectorNodes
  59. * @returns {VElementMatcher}
  60. */
  61. function selectorsToVElementMatcher(selectorNodes) {
  62. const selectors = selectorNodes.map((n) =>
  63. selectorToVElementMatcher(cleanSelectorChildren(n))
  64. )
  65. return (element, subject) => selectors.some((sel) => sel(element, subject))
  66. }
  67. /**
  68. * @param {parser.Node|null} node
  69. * @returns {node is parser.Combinator}
  70. */
  71. function isDescendantCombinator(node) {
  72. return Boolean(node && node.type === 'combinator' && !node.value.trim())
  73. }
  74. /**
  75. * Clean and get the selector child nodes.
  76. * @param {parser.Selector} selector
  77. * @returns {ChildNode[]}
  78. */
  79. function cleanSelectorChildren(selector) {
  80. /** @type {ChildNode[]} */
  81. const nodes = []
  82. /** @type {ChildNode|null} */
  83. let last = null
  84. for (const node of selector.nodes) {
  85. if (node.type === 'root') {
  86. throw new SelectorError('Unexpected state type=root')
  87. }
  88. if (node.type === 'comment') {
  89. continue
  90. }
  91. if (
  92. (last == null || last.type === 'combinator') &&
  93. isDescendantCombinator(node)
  94. ) {
  95. // Ignore descendant combinator
  96. continue
  97. }
  98. if (isDescendantCombinator(last) && node.type === 'combinator') {
  99. // Replace combinator
  100. nodes.pop()
  101. }
  102. nodes.push(node)
  103. last = node
  104. }
  105. if (isDescendantCombinator(last)) {
  106. nodes.pop()
  107. }
  108. return nodes
  109. }
  110. /**
  111. * Convert Selector child nodes to VElementMatcher
  112. * @param {ChildNode[]} selectorChildren
  113. * @returns {VElementMatcher}
  114. */
  115. function selectorToVElementMatcher(selectorChildren) {
  116. const nodes = [...selectorChildren]
  117. let node = nodes.shift()
  118. /**
  119. * @type {VElementMatcher | null}
  120. */
  121. let result = null
  122. while (node) {
  123. if (node.type === 'combinator') {
  124. const combinator = node.value
  125. node = nodes.shift()
  126. if (!node) {
  127. throw new SelectorError(`Expected selector after '${combinator}'.`)
  128. }
  129. if (node.type === 'combinator') {
  130. throw new SelectorError(`Unexpected combinator '${node.value}'.`)
  131. }
  132. const right = nodeToVElementMatcher(node)
  133. result = combination(
  134. result ||
  135. // for :has()
  136. ((element, subject) => element === subject),
  137. combinator,
  138. right
  139. )
  140. } else {
  141. const sel = nodeToVElementMatcher(node)
  142. result = result ? compound(result, sel) : sel
  143. }
  144. node = nodes.shift()
  145. }
  146. if (!result) {
  147. throw new SelectorError(`Unexpected empty selector.`)
  148. }
  149. return result
  150. }
  151. /**
  152. * @param {VElementMatcher} left
  153. * @param {string} combinator
  154. * @param {VElementMatcher} right
  155. * @returns {VElementMatcher}
  156. */
  157. function combination(left, combinator, right) {
  158. switch (combinator.trim()) {
  159. case '':
  160. // descendant
  161. return (element, subject) => {
  162. if (right(element, null)) {
  163. let parent = element.parent
  164. while (parent.type === 'VElement') {
  165. if (left(parent, subject)) {
  166. return true
  167. }
  168. parent = parent.parent
  169. }
  170. }
  171. return false
  172. }
  173. case '>':
  174. // child
  175. return (element, subject) => {
  176. if (right(element, null)) {
  177. const parent = element.parent
  178. if (parent.type === 'VElement') {
  179. return left(parent, subject)
  180. }
  181. }
  182. return false
  183. }
  184. case '+':
  185. // adjacent
  186. return (element, subject) => {
  187. if (right(element, null)) {
  188. const before = getBeforeElement(element)
  189. if (before) {
  190. return left(before, subject)
  191. }
  192. }
  193. return false
  194. }
  195. case '~':
  196. // sibling
  197. return (element, subject) => {
  198. if (right(element, null)) {
  199. for (const before of getBeforeElements(element)) {
  200. if (left(before, subject)) {
  201. return true
  202. }
  203. }
  204. }
  205. return false
  206. }
  207. default:
  208. throw new SelectorError(`Unknown combinator: ${combinator}.`)
  209. }
  210. }
  211. /**
  212. * Convert node to VElementMatcher
  213. * @param {Exclude<parser.Node, {type:'combinator'|'comment'|'root'|'selector'}>} selector
  214. * @returns {VElementMatcher}
  215. */
  216. function nodeToVElementMatcher(selector) {
  217. switch (selector.type) {
  218. case 'attribute':
  219. return attributeNodeToVElementMatcher(selector)
  220. case 'class':
  221. return classNameNodeToVElementMatcher(selector)
  222. case 'id':
  223. return identifierNodeToVElementMatcher(selector)
  224. case 'tag':
  225. return tagNodeToVElementMatcher(selector)
  226. case 'universal':
  227. return universalNodeToVElementMatcher(selector)
  228. case 'pseudo':
  229. return pseudoNodeToVElementMatcher(selector)
  230. case 'nesting':
  231. throw new SelectorError('Unsupported nesting selector.')
  232. case 'string':
  233. throw new SelectorError(`Unknown selector: ${selector.value}.`)
  234. default:
  235. throw new SelectorError(
  236. `Unknown selector: ${/** @type {any}*/ (selector).value}.`
  237. )
  238. }
  239. }
  240. /**
  241. * Convert Attribute node to VElementMatcher
  242. * @param {parser.Attribute} selector
  243. * @returns {VElementMatcher}
  244. */
  245. function attributeNodeToVElementMatcher(selector) {
  246. const key = selector.attribute
  247. if (!selector.operator) {
  248. return (element) => getAttributeValue(element, key) != null
  249. }
  250. const value = selector.value || ''
  251. switch (selector.operator) {
  252. case '=':
  253. return buildVElementMatcher(value, (attr, val) => attr === val)
  254. case '~=':
  255. // words
  256. return buildVElementMatcher(value, (attr, val) =>
  257. attr.split(/\s+/gu).includes(val)
  258. )
  259. case '|=':
  260. // immediately followed by hyphen
  261. return buildVElementMatcher(
  262. value,
  263. (attr, val) => attr === val || attr.startsWith(`${val}-`)
  264. )
  265. case '^=':
  266. // prefixed
  267. return buildVElementMatcher(value, (attr, val) => attr.startsWith(val))
  268. case '$=':
  269. // suffixed
  270. return buildVElementMatcher(value, (attr, val) => attr.endsWith(val))
  271. case '*=':
  272. // contains
  273. return buildVElementMatcher(value, (attr, val) => attr.includes(val))
  274. default:
  275. throw new SelectorError(`Unsupported operator: ${selector.operator}.`)
  276. }
  277. /**
  278. * @param {string} selectorValue
  279. * @param {(attrValue:string, selectorValue: string)=>boolean} test
  280. * @returns {VElementMatcher}
  281. */
  282. function buildVElementMatcher(selectorValue, test) {
  283. const val = selector.insensitive
  284. ? selectorValue.toLowerCase()
  285. : selectorValue
  286. return (element) => {
  287. const attrValue = getAttributeValue(element, key)
  288. if (attrValue == null) {
  289. return false
  290. }
  291. return test(
  292. selector.insensitive ? attrValue.toLowerCase() : attrValue,
  293. val
  294. )
  295. }
  296. }
  297. }
  298. /**
  299. * Convert ClassName node to VElementMatcher
  300. * @param {parser.ClassName} selector
  301. * @returns {VElementMatcher}
  302. */
  303. function classNameNodeToVElementMatcher(selector) {
  304. const className = selector.value
  305. return (element) => {
  306. const attrValue = getAttributeValue(element, 'class')
  307. if (attrValue == null) {
  308. return false
  309. }
  310. return attrValue.split(/\s+/gu).includes(className)
  311. }
  312. }
  313. /**
  314. * Convert Identifier node to VElementMatcher
  315. * @param {parser.Identifier} selector
  316. * @returns {VElementMatcher}
  317. */
  318. function identifierNodeToVElementMatcher(selector) {
  319. const id = selector.value
  320. return (element) => {
  321. const attrValue = getAttributeValue(element, 'id')
  322. if (attrValue == null) {
  323. return false
  324. }
  325. return attrValue === id
  326. }
  327. }
  328. /**
  329. * Convert Tag node to VElementMatcher
  330. * @param {parser.Tag} selector
  331. * @returns {VElementMatcher}
  332. */
  333. function tagNodeToVElementMatcher(selector) {
  334. const name = selector.value
  335. return (element) => element.rawName === name
  336. }
  337. /**
  338. * Convert Universal node to VElementMatcher
  339. * @param {parser.Universal} _selector
  340. * @returns {VElementMatcher}
  341. */
  342. function universalNodeToVElementMatcher(_selector) {
  343. return () => true
  344. }
  345. /**
  346. * Convert Pseudo node to VElementMatcher
  347. * @param {parser.Pseudo} selector
  348. * @returns {VElementMatcher}
  349. */
  350. function pseudoNodeToVElementMatcher(selector) {
  351. const pseudo = selector.value
  352. switch (pseudo) {
  353. case ':not': {
  354. // https://developer.mozilla.org/en-US/docs/Web/CSS/:not
  355. const selectors = selectorsToVElementMatcher(selector.nodes)
  356. return (element, subject) => !selectors(element, subject)
  357. }
  358. case ':is':
  359. case ':where':
  360. // https://developer.mozilla.org/en-US/docs/Web/CSS/:is
  361. // https://developer.mozilla.org/en-US/docs/Web/CSS/:where
  362. return selectorsToVElementMatcher(selector.nodes)
  363. case ':has':
  364. // https://developer.mozilla.org/en-US/docs/Web/CSS/:has
  365. return pseudoHasSelectorsToVElementMatcher(selector.nodes)
  366. case ':empty':
  367. // https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
  368. return (element) =>
  369. element.children.every(
  370. (child) => child.type === 'VText' && !child.value.trim()
  371. )
  372. case ':nth-child': {
  373. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
  374. const nth = parseNth(selector)
  375. return buildPseudoNthVElementMatcher(nth)
  376. }
  377. case ':nth-last-child': {
  378. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
  379. const nth = parseNth(selector)
  380. return buildPseudoNthVElementMatcher((index, length) =>
  381. nth(length - index - 1)
  382. )
  383. }
  384. case ':first-child':
  385. // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child
  386. return buildPseudoNthVElementMatcher((index) => index === 0)
  387. case ':last-child':
  388. // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child
  389. return buildPseudoNthVElementMatcher(
  390. (index, length) => index === length - 1
  391. )
  392. case ':only-child':
  393. // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child
  394. return buildPseudoNthVElementMatcher(
  395. (index, length) => index === 0 && length === 1
  396. )
  397. case ':nth-of-type': {
  398. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
  399. const nth = parseNth(selector)
  400. return buildPseudoNthOfTypeVElementMatcher(nth)
  401. }
  402. case ':nth-last-of-type': {
  403. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type
  404. const nth = parseNth(selector)
  405. return buildPseudoNthOfTypeVElementMatcher((index, length) =>
  406. nth(length - index - 1)
  407. )
  408. }
  409. case ':first-of-type':
  410. // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type
  411. return buildPseudoNthOfTypeVElementMatcher((index) => index === 0)
  412. case ':last-of-type':
  413. // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
  414. return buildPseudoNthOfTypeVElementMatcher(
  415. (index, length) => index === length - 1
  416. )
  417. case ':only-of-type':
  418. // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type
  419. return buildPseudoNthOfTypeVElementMatcher(
  420. (index, length) => index === 0 && length === 1
  421. )
  422. default:
  423. throw new SelectorError(`Unsupported pseudo selector: ${pseudo}.`)
  424. }
  425. }
  426. /**
  427. * Convert :has() selector nodes to VElementMatcher
  428. * @param {parser.Selector[]} selectorNodes
  429. * @returns {VElementMatcher}
  430. */
  431. function pseudoHasSelectorsToVElementMatcher(selectorNodes) {
  432. const selectors = selectorNodes.map((n) =>
  433. pseudoHasSelectorToVElementMatcher(n)
  434. )
  435. return (element, subject) => selectors.some((sel) => sel(element, subject))
  436. }
  437. /**
  438. * Convert :has() selector node to VElementMatcher
  439. * @param {parser.Selector} selector
  440. * @returns {VElementMatcher}
  441. */
  442. function pseudoHasSelectorToVElementMatcher(selector) {
  443. const nodes = cleanSelectorChildren(selector)
  444. const selectors = selectorToVElementMatcher(nodes)
  445. const firstNode = nodes[0]
  446. if (
  447. firstNode.type === 'combinator' &&
  448. (firstNode.value === '+' || firstNode.value === '~')
  449. ) {
  450. // adjacent or sibling
  451. return buildVElementMatcher(selectors, (element) =>
  452. getAfterElements(element)
  453. )
  454. }
  455. // descendant or child
  456. return buildVElementMatcher(selectors, (element) =>
  457. element.children.filter(isVElement)
  458. )
  459. }
  460. /**
  461. * @param {VElementMatcher} selectors
  462. * @param {(element: VElement) => VElement[]} getStartElements
  463. * @returns {VElementMatcher}
  464. */
  465. function buildVElementMatcher(selectors, getStartElements) {
  466. return (element) => {
  467. const elements = [...getStartElements(element)]
  468. /** @type {VElement|undefined} */
  469. let curr
  470. while ((curr = elements.shift())) {
  471. const el = curr
  472. if (selectors(el, element)) {
  473. return true
  474. }
  475. elements.push(...el.children.filter(isVElement))
  476. }
  477. return false
  478. }
  479. }
  480. /**
  481. * Parse <nth>
  482. * @param {parser.Pseudo} pseudoNode
  483. * @returns {(index: number)=>boolean}
  484. */
  485. function parseNth(pseudoNode) {
  486. const argumentsText = pseudoNode
  487. .toString()
  488. .slice(pseudoNode.value.length)
  489. .toLowerCase()
  490. const openParenIndex = argumentsText.indexOf('(')
  491. const closeParenIndex = argumentsText.lastIndexOf(')')
  492. if (openParenIndex < 0 || closeParenIndex < 0) {
  493. throw new SelectorError(
  494. `Cannot parse An+B micro syntax (:nth-xxx() argument): ${argumentsText}.`
  495. )
  496. }
  497. const argument = argumentsText
  498. .slice(openParenIndex + 1, closeParenIndex)
  499. .trim()
  500. try {
  501. return nthCheck(argument)
  502. } catch (error) {
  503. throw new SelectorError(
  504. `Cannot parse An+B micro syntax (:nth-xxx() argument): '${argument}'.`
  505. )
  506. }
  507. }
  508. /**
  509. * Build VElementMatcher for :nth-xxx()
  510. * @param {(index: number, length: number)=>boolean} testIndex
  511. * @returns {VElementMatcher}
  512. */
  513. function buildPseudoNthVElementMatcher(testIndex) {
  514. return (element) => {
  515. const elements = element.parent.children.filter(isVElement)
  516. return testIndex(elements.indexOf(element), elements.length)
  517. }
  518. }
  519. /**
  520. * Build VElementMatcher for :nth-xxx-of-type()
  521. * @param {(index: number, length: number)=>boolean} testIndex
  522. * @returns {VElementMatcher}
  523. */
  524. function buildPseudoNthOfTypeVElementMatcher(testIndex) {
  525. return (element) => {
  526. const elements = element.parent.children
  527. .filter(isVElement)
  528. .filter((e) => e.rawName === element.rawName)
  529. return testIndex(elements.indexOf(element), elements.length)
  530. }
  531. }
  532. /**
  533. * @param {VElement} element
  534. */
  535. function getBeforeElement(element) {
  536. return getBeforeElements(element).pop() || null
  537. }
  538. /**
  539. * @param {VElement} element
  540. */
  541. function getBeforeElements(element) {
  542. const parent = element.parent
  543. const index = parent.children.indexOf(element)
  544. return parent.children.slice(0, index).filter(isVElement)
  545. }
  546. /**
  547. * @param {VElement} element
  548. */
  549. function getAfterElements(element) {
  550. const parent = element.parent
  551. const index = parent.children.indexOf(element)
  552. return parent.children.slice(index + 1).filter(isVElement)
  553. }
  554. /**
  555. * @param {VElementMatcher} a
  556. * @param {VElementMatcher} b
  557. * @returns {VElementMatcher}
  558. */
  559. function compound(a, b) {
  560. return (element, subject) => a(element, subject) && b(element, subject)
  561. }
  562. /**
  563. * Get attribute value from given element.
  564. * @param {VElement} element The element node.
  565. * @param {string} attribute The attribute name.
  566. */
  567. function getAttributeValue(element, attribute) {
  568. const attr = getAttribute(element, attribute)
  569. if (attr) {
  570. return (attr.value && attr.value.value) || ''
  571. }
  572. return null
  573. }