selector.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 (e) {
  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 (e) {
  39. if (e instanceof SelectorError) {
  40. context.report({
  41. loc: { line: 0, column: 0 },
  42. message: e.message
  43. })
  44. return {
  45. test: () => false
  46. }
  47. }
  48. throw e
  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. * Clean and get the selector child nodes.
  69. * @param {parser.Selector} selector
  70. * @returns {ChildNode[]}
  71. */
  72. function cleanSelectorChildren(selector) {
  73. /** @type {ChildNode[]} */
  74. const nodes = []
  75. /** @type {ChildNode|null} */
  76. let last = null
  77. for (const node of selector.nodes) {
  78. if (node.type === 'root') {
  79. throw new SelectorError('Unexpected state type=root')
  80. }
  81. if (node.type === 'comment') {
  82. continue
  83. }
  84. if (
  85. (last == null || last.type === 'combinator') &&
  86. isDescendantCombinator(node)
  87. ) {
  88. // Ignore descendant combinator
  89. continue
  90. }
  91. if (isDescendantCombinator(last) && node.type === 'combinator') {
  92. // Replace combinator
  93. nodes.pop()
  94. }
  95. nodes.push(node)
  96. last = node
  97. }
  98. if (isDescendantCombinator(last)) {
  99. nodes.pop()
  100. }
  101. return nodes
  102. /**
  103. * @param {parser.Node|null} node
  104. * @returns {node is parser.Combinator}
  105. */
  106. function isDescendantCombinator(node) {
  107. return Boolean(node && node.type === 'combinator' && !node.value.trim())
  108. }
  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) => {
  357. return !selectors(element, subject)
  358. }
  359. }
  360. case ':is':
  361. case ':where':
  362. // https://developer.mozilla.org/en-US/docs/Web/CSS/:is
  363. // https://developer.mozilla.org/en-US/docs/Web/CSS/:where
  364. return selectorsToVElementMatcher(selector.nodes)
  365. case ':has':
  366. // https://developer.mozilla.org/en-US/docs/Web/CSS/:has
  367. return pseudoHasSelectorsToVElementMatcher(selector.nodes)
  368. case ':empty':
  369. // https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
  370. return (element) =>
  371. element.children.every(
  372. (child) => child.type === 'VText' && !child.value.trim()
  373. )
  374. case ':nth-child': {
  375. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
  376. const nth = parseNth(selector)
  377. return buildPseudoNthVElementMatcher(nth)
  378. }
  379. case ':nth-last-child': {
  380. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
  381. const nth = parseNth(selector)
  382. return buildPseudoNthVElementMatcher((index, length) =>
  383. nth(length - index - 1)
  384. )
  385. }
  386. case ':first-child':
  387. // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child
  388. return buildPseudoNthVElementMatcher((index) => index === 0)
  389. case ':last-child':
  390. // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child
  391. return buildPseudoNthVElementMatcher(
  392. (index, length) => index === length - 1
  393. )
  394. case ':only-child':
  395. // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child
  396. return buildPseudoNthVElementMatcher(
  397. (index, length) => index === 0 && length === 1
  398. )
  399. case ':nth-of-type': {
  400. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
  401. const nth = parseNth(selector)
  402. return buildPseudoNthOfTypeVElementMatcher(nth)
  403. }
  404. case ':nth-last-of-type': {
  405. // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type
  406. const nth = parseNth(selector)
  407. return buildPseudoNthOfTypeVElementMatcher((index, length) =>
  408. nth(length - index - 1)
  409. )
  410. }
  411. case ':first-of-type':
  412. // https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type
  413. return buildPseudoNthOfTypeVElementMatcher((index) => index === 0)
  414. case ':last-of-type':
  415. // https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
  416. return buildPseudoNthOfTypeVElementMatcher(
  417. (index, length) => index === length - 1
  418. )
  419. case ':only-of-type':
  420. // https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type
  421. return buildPseudoNthOfTypeVElementMatcher(
  422. (index, length) => index === 0 && length === 1
  423. )
  424. default:
  425. throw new SelectorError(`Unsupported pseudo selector: ${pseudo}.`)
  426. }
  427. }
  428. /**
  429. * Convert :has() selector nodes to VElementMatcher
  430. * @param {parser.Selector[]} selectorNodes
  431. * @returns {VElementMatcher}
  432. */
  433. function pseudoHasSelectorsToVElementMatcher(selectorNodes) {
  434. const selectors = selectorNodes.map((n) =>
  435. pseudoHasSelectorToVElementMatcher(n)
  436. )
  437. return (element, subject) => selectors.some((sel) => sel(element, subject))
  438. }
  439. /**
  440. * Convert :has() selector node to VElementMatcher
  441. * @param {parser.Selector} selector
  442. * @returns {VElementMatcher}
  443. */
  444. function pseudoHasSelectorToVElementMatcher(selector) {
  445. const nodes = cleanSelectorChildren(selector)
  446. const selectors = selectorToVElementMatcher(nodes)
  447. const firstNode = nodes[0]
  448. if (
  449. firstNode.type === 'combinator' &&
  450. (firstNode.value === '+' || firstNode.value === '~')
  451. ) {
  452. // adjacent or sibling
  453. return buildVElementMatcher(selectors, (element) =>
  454. getAfterElements(element)
  455. )
  456. }
  457. // descendant or child
  458. return buildVElementMatcher(selectors, (element) =>
  459. element.children.filter(isVElement)
  460. )
  461. /**
  462. * @param {VElementMatcher} selectors
  463. * @param {(element: VElement) => VElement[]} getStartElements
  464. * @returns {VElementMatcher}
  465. */
  466. function buildVElementMatcher(selectors, getStartElements) {
  467. return (element) => {
  468. const elements = [...getStartElements(element)]
  469. /** @type {VElement|undefined} */
  470. let curr
  471. while ((curr = elements.shift())) {
  472. const el = curr
  473. if (selectors(el, element)) {
  474. return true
  475. }
  476. elements.push(...el.children.filter(isVElement))
  477. }
  478. return false
  479. }
  480. }
  481. }
  482. /**
  483. * Parse <nth>
  484. * @param {parser.Pseudo} pseudoNode
  485. * @returns {(index: number)=>boolean}
  486. */
  487. function parseNth(pseudoNode) {
  488. const argumentsText = pseudoNode
  489. .toString()
  490. .slice(pseudoNode.value.length)
  491. .toLowerCase()
  492. const openParenIndex = argumentsText.indexOf('(')
  493. const closeParenIndex = argumentsText.lastIndexOf(')')
  494. if (openParenIndex < 0 || closeParenIndex < 0) {
  495. throw new SelectorError(
  496. `Cannot parse An+B micro syntax (:nth-xxx() argument): ${argumentsText}.`
  497. )
  498. }
  499. const argument = argumentsText
  500. .slice(openParenIndex + 1, closeParenIndex)
  501. .trim()
  502. try {
  503. return nthCheck(argument)
  504. } catch (e) {
  505. throw new SelectorError(
  506. `Cannot parse An+B micro syntax (:nth-xxx() argument): '${argument}'.`
  507. )
  508. }
  509. }
  510. /**
  511. * Build VElementMatcher for :nth-xxx()
  512. * @param {(index: number, length: number)=>boolean} testIndex
  513. * @returns {VElementMatcher}
  514. */
  515. function buildPseudoNthVElementMatcher(testIndex) {
  516. return (element) => {
  517. const elements = element.parent.children.filter(isVElement)
  518. return testIndex(elements.indexOf(element), elements.length)
  519. }
  520. }
  521. /**
  522. * Build VElementMatcher for :nth-xxx-of-type()
  523. * @param {(index: number, length: number)=>boolean} testIndex
  524. * @returns {VElementMatcher}
  525. */
  526. function buildPseudoNthOfTypeVElementMatcher(testIndex) {
  527. return (element) => {
  528. const elements = element.parent.children
  529. .filter(isVElement)
  530. .filter((e) => e.rawName === element.rawName)
  531. return testIndex(elements.indexOf(element), elements.length)
  532. }
  533. }
  534. /**
  535. * @param {VElement} element
  536. */
  537. function getBeforeElement(element) {
  538. return getBeforeElements(element).pop() || null
  539. }
  540. /**
  541. * @param {VElement} element
  542. */
  543. function getBeforeElements(element) {
  544. const parent = element.parent
  545. const index = parent.children.indexOf(element)
  546. return parent.children.slice(0, index).filter(isVElement)
  547. }
  548. /**
  549. * @param {VElement} element
  550. */
  551. function getAfterElements(element) {
  552. const parent = element.parent
  553. const index = parent.children.indexOf(element)
  554. return parent.children.slice(index + 1).filter(isVElement)
  555. }
  556. /**
  557. * @param {VElementMatcher} a
  558. * @param {VElementMatcher} b
  559. * @returns {VElementMatcher}
  560. */
  561. function compound(a, b) {
  562. return (element, subject) => a(element, subject) && b(element, subject)
  563. }
  564. /**
  565. * Get attribute value from given element.
  566. * @param {VElement} element The element node.
  567. * @param {string} attribute The attribute name.
  568. */
  569. function getAttributeValue(element, attribute) {
  570. const attr = getAttribute(element, attribute)
  571. if (attr) {
  572. return (attr.value && attr.value.value) || ''
  573. }
  574. return null
  575. }