You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

873 lines
20 KiB

4 years ago
  1. # API Documentation
  2. *Please use only this documented API when working with the parser. Methods
  3. not documented here are subject to change at any point.*
  4. ## `parser` function
  5. This is the module's main entry point.
  6. ```js
  7. const parser = require('postcss-selector-parser');
  8. ```
  9. ### `parser([transform], [options])`
  10. Creates a new `processor` instance
  11. ```js
  12. const processor = parser();
  13. ```
  14. Or, with optional transform function
  15. ```js
  16. const transform = selectors => {
  17. selectors.walkUniversals(selector => {
  18. selector.remove();
  19. });
  20. };
  21. const processor = parser(transform)
  22. // Example
  23. const result = processor.processSync('*.class');
  24. // => .class
  25. ```
  26. [See processor documentation](#processor)
  27. Arguments:
  28. * `transform (function)`: Provide a function to work with the parsed AST.
  29. * `options (object)`: Provide default options for all calls on the returned `Processor`.
  30. ### `parser.attribute([props])`
  31. Creates a new attribute selector.
  32. ```js
  33. parser.attribute({attribute: 'href'});
  34. // => [href]
  35. ```
  36. Arguments:
  37. * `props (object)`: The new node's properties.
  38. ### `parser.className([props])`
  39. Creates a new class selector.
  40. ```js
  41. parser.className({value: 'button'});
  42. // => .button
  43. ```
  44. Arguments:
  45. * `props (object)`: The new node's properties.
  46. ### `parser.combinator([props])`
  47. Creates a new selector combinator.
  48. ```js
  49. parser.combinator({value: '+'});
  50. // => +
  51. ```
  52. Arguments:
  53. * `props (object)`: The new node's properties.
  54. Notes:
  55. * **Descendant Combinators** The value of descendant combinators created by the
  56. parser always just a single space (`" "`). For descendant selectors with no
  57. comments, additional space is now stored in `node.spaces.before`. Depending
  58. on the location of comments, additional spaces may be stored in
  59. `node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`.
  60. * **Named Combinators** Although, nonstandard and unlikely to ever become a standard,
  61. named combinators like `/deep/` and `/for/` are parsed as combinators. The
  62. `node.value` is name after being unescaped and normalized as lowercase. The
  63. original value for the combinator name is stored in `node.raws.value`.
  64. ### `parser.comment([props])`
  65. Creates a new comment.
  66. ```js
  67. parser.comment({value: '/* Affirmative, Dave. I read you. */'});
  68. // => /* Affirmative, Dave. I read you. */
  69. ```
  70. Arguments:
  71. * `props (object)`: The new node's properties.
  72. ### `parser.id([props])`
  73. Creates a new id selector.
  74. ```js
  75. parser.id({value: 'search'});
  76. // => #search
  77. ```
  78. Arguments:
  79. * `props (object)`: The new node's properties.
  80. ### `parser.nesting([props])`
  81. Creates a new nesting selector.
  82. ```js
  83. parser.nesting();
  84. // => &
  85. ```
  86. Arguments:
  87. * `props (object)`: The new node's properties.
  88. ### `parser.pseudo([props])`
  89. Creates a new pseudo selector.
  90. ```js
  91. parser.pseudo({value: '::before'});
  92. // => ::before
  93. ```
  94. Arguments:
  95. * `props (object)`: The new node's properties.
  96. ### `parser.root([props])`
  97. Creates a new root node.
  98. ```js
  99. parser.root();
  100. // => (empty)
  101. ```
  102. Arguments:
  103. * `props (object)`: The new node's properties.
  104. ### `parser.selector([props])`
  105. Creates a new selector node.
  106. ```js
  107. parser.selector();
  108. // => (empty)
  109. ```
  110. Arguments:
  111. * `props (object)`: The new node's properties.
  112. ### `parser.string([props])`
  113. Creates a new string node.
  114. ```js
  115. parser.string();
  116. // => (empty)
  117. ```
  118. Arguments:
  119. * `props (object)`: The new node's properties.
  120. ### `parser.tag([props])`
  121. Creates a new tag selector.
  122. ```js
  123. parser.tag({value: 'button'});
  124. // => button
  125. ```
  126. Arguments:
  127. * `props (object)`: The new node's properties.
  128. ### `parser.universal([props])`
  129. Creates a new universal selector.
  130. ```js
  131. parser.universal();
  132. // => *
  133. ```
  134. Arguments:
  135. * `props (object)`: The new node's properties.
  136. ## Node types
  137. ### `node.type`
  138. A string representation of the selector type. It can be one of the following;
  139. `attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`,
  140. `root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience,
  141. these constants are exposed on the main `parser` as uppercased keys. So for
  142. example you can get `id` by querying `parser.ID`.
  143. ```js
  144. parser.attribute({attribute: 'href'}).type;
  145. // => 'attribute'
  146. ```
  147. ### `node.parent`
  148. Returns the parent node.
  149. ```js
  150. root.nodes[0].parent === root;
  151. ```
  152. ### `node.toString()`, `String(node)`, or `'' + node`
  153. Returns a string representation of the node.
  154. ```js
  155. const id = parser.id({value: 'search'});
  156. console.log(String(id));
  157. // => #search
  158. ```
  159. ### `node.next()` & `node.prev()`
  160. Returns the next/previous child of the parent node.
  161. ```js
  162. const next = id.next();
  163. if (next && next.type !== 'combinator') {
  164. throw new Error('Qualified IDs are not allowed!');
  165. }
  166. ```
  167. ### `node.replaceWith(node)`
  168. Replace a node with another.
  169. ```js
  170. const attr = selectors.first.first;
  171. const className = parser.className({value: 'test'});
  172. attr.replaceWith(className);
  173. ```
  174. Arguments:
  175. * `node`: The node to substitute the original with.
  176. ### `node.remove()`
  177. Removes the node from its parent node.
  178. ```js
  179. if (node.type === 'id') {
  180. node.remove();
  181. }
  182. ```
  183. ### `node.clone()`
  184. Returns a copy of a node, detached from any parent containers that the
  185. original might have had.
  186. ```js
  187. const cloned = parser.id({value: 'search'});
  188. String(cloned);
  189. // => #search
  190. ```
  191. ### `node.isAtPosition(line, column)`
  192. Return a `boolean` indicating whether this node includes the character at the
  193. position of the given line and column. Returns `undefined` if the nodes lack
  194. sufficient source metadata to determine the position.
  195. Arguments:
  196. * `line`: 1-index based line number relative to the start of the selector.
  197. * `column`: 1-index based column number relative to the start of the selector.
  198. ### `node.spaces`
  199. Extra whitespaces around the node will be moved into `node.spaces.before` and
  200. `node.spaces.after`. So for example, these spaces will be moved as they have
  201. no semantic meaning:
  202. ```css
  203. h1 , h2 {}
  204. ```
  205. For descendent selectors, the value is always a single space.
  206. ```css
  207. h1 h2 {}
  208. ```
  209. Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source.
  210. ### `node.source`
  211. An object describing the node's start/end, line/column source position.
  212. Within the following CSS, the `.bar` class node ...
  213. ```css
  214. .foo,
  215. .bar {}
  216. ```
  217. ... will contain the following `source` object.
  218. ```js
  219. source: {
  220. start: {
  221. line: 2,
  222. column: 3
  223. },
  224. end: {
  225. line: 2,
  226. column: 6
  227. }
  228. }
  229. ```
  230. ### `node.sourceIndex`
  231. The zero-based index of the node within the original source string.
  232. Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`.
  233. ```css
  234. .foo, .bar, .baz {}
  235. ```
  236. ## Container types
  237. The `root`, `selector`, and `pseudo` nodes have some helper methods for working
  238. with their children.
  239. ### `container.nodes`
  240. An array of the container's children.
  241. ```js
  242. // Input: h1 h2
  243. selectors.at(0).nodes.length // => 3
  244. selectors.at(0).nodes[0].value // => 'h1'
  245. selectors.at(0).nodes[1].value // => ' '
  246. ```
  247. ### `container.first` & `container.last`
  248. The first/last child of the container.
  249. ```js
  250. selector.first === selector.nodes[0];
  251. selector.last === selector.nodes[selector.nodes.length - 1];
  252. ```
  253. ### `container.at(index)`
  254. Returns the node at position `index`.
  255. ```js
  256. selector.at(0) === selector.first;
  257. selector.at(0) === selector.nodes[0];
  258. ```
  259. Arguments:
  260. * `index`: The index of the node to return.
  261. ### `container.atPosition(line, column)`
  262. Returns the node at the source position `index`.
  263. ```js
  264. selector.at(0) === selector.first;
  265. selector.at(0) === selector.nodes[0];
  266. ```
  267. Arguments:
  268. * `index`: The index of the node to return.
  269. ### `container.index(node)`
  270. Return the index of the node within its container.
  271. ```js
  272. selector.index(selector.nodes[2]) // => 2
  273. ```
  274. Arguments:
  275. * `node`: A node within the current container.
  276. ### `container.length`
  277. Proxy to the length of the container's nodes.
  278. ```js
  279. container.length === container.nodes.length
  280. ```
  281. ### `container` Array iterators
  282. The container class provides proxies to certain Array methods; these are:
  283. * `container.map === container.nodes.map`
  284. * `container.reduce === container.nodes.reduce`
  285. * `container.every === container.nodes.every`
  286. * `container.some === container.nodes.some`
  287. * `container.filter === container.nodes.filter`
  288. * `container.sort === container.nodes.sort`
  289. Note that these methods only work on a container's immediate children; recursive
  290. iteration is provided by `container.walk`.
  291. ### `container.each(callback)`
  292. Iterate the container's immediate children, calling `callback` for each child.
  293. You may return `false` within the callback to break the iteration.
  294. ```js
  295. let className;
  296. selectors.each((selector, index) => {
  297. if (selector.type === 'class') {
  298. className = selector.value;
  299. return false;
  300. }
  301. });
  302. ```
  303. Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding
  304. or removing nodes from the container.
  305. Arguments:
  306. * `callback (function)`: A function to call for each node, which receives `node`
  307. and `index` arguments.
  308. ### `container.walk(callback)`
  309. Like `container#each`, but will also iterate child nodes as long as they are
  310. `container` types.
  311. ```js
  312. selectors.walk((selector, index) => {
  313. // all nodes
  314. });
  315. ```
  316. Arguments:
  317. * `callback (function)`: A function to call for each node, which receives `node`
  318. and `index` arguments.
  319. This iterator is safe to use whilst mutating `container.nodes`,
  320. like `container#each`.
  321. ### `container.walk` proxies
  322. The container class provides proxy methods for iterating over types of nodes,
  323. so that it is easier to write modules that target specific selectors. Those
  324. methods are:
  325. * `container.walkAttributes`
  326. * `container.walkClasses`
  327. * `container.walkCombinators`
  328. * `container.walkComments`
  329. * `container.walkIds`
  330. * `container.walkNesting`
  331. * `container.walkPseudos`
  332. * `container.walkTags`
  333. * `container.walkUniversals`
  334. ### `container.split(callback)`
  335. This method allows you to split a group of nodes by returning `true` from
  336. a callback. It returns an array of arrays, where each inner array corresponds
  337. to the groups that you created via the callback.
  338. ```js
  339. // (input) => h1 h2>>h3
  340. const list = selectors.first.split(selector => {
  341. return selector.type === 'combinator';
  342. });
  343. // (node values) => [['h1', ' '], ['h2', '>>'], ['h3']]
  344. ```
  345. Arguments:
  346. * `callback (function)`: A function to call for each node, which receives `node`
  347. as an argument.
  348. ### `container.prepend(node)` & `container.append(node)`
  349. Add a node to the start/end of the container. Note that doing so will set
  350. the parent property of the node to this container.
  351. ```js
  352. const id = parser.id({value: 'search'});
  353. selector.append(id);
  354. ```
  355. Arguments:
  356. * `node`: The node to add.
  357. ### `container.insertBefore(old, new)` & `container.insertAfter(old, new)`
  358. Add a node before or after an existing node in a container:
  359. ```js
  360. selectors.walk(selector => {
  361. if (selector.type !== 'class') {
  362. const className = parser.className({value: 'theme-name'});
  363. selector.parent.insertAfter(selector, className);
  364. }
  365. });
  366. ```
  367. Arguments:
  368. * `old`: The existing node in the container.
  369. * `new`: The new node to add before/after the existing node.
  370. ### `container.removeChild(node)`
  371. Remove the node from the container. Note that you can also use
  372. `node.remove()` if you would like to remove just a single node.
  373. ```js
  374. selector.length // => 2
  375. selector.remove(id)
  376. selector.length // => 1;
  377. id.parent // undefined
  378. ```
  379. Arguments:
  380. * `node`: The node to remove.
  381. ### `container.removeAll()` or `container.empty()`
  382. Remove all children from the container.
  383. ```js
  384. selector.removeAll();
  385. selector.length // => 0
  386. ```
  387. ## Root nodes
  388. A root node represents a comma separated list of selectors. Indeed, all
  389. a root's `toString()` method does is join its selector children with a ','.
  390. Other than this, it has no special functionality and acts like a container.
  391. ### `root.trailingComma`
  392. This will be set to `true` if the input has a trailing comma, in order to
  393. support parsing of legacy CSS hacks.
  394. ## Selector nodes
  395. A selector node represents a single complex selector. For example, this
  396. selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes.
  397. It has no special functionality of its own.
  398. ## Pseudo nodes
  399. A pseudo selector extends a container node; if it has any parameters of its
  400. own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo
  401. `value` will always contain the colons preceding the pseudo identifier. This
  402. is so that both `:before` and `::before` are properly represented in the AST.
  403. ## Attribute nodes
  404. ### `attribute.quoted`
  405. Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not.
  406. Remains `undefined` if there is no attribute value.
  407. ```css
  408. [href=foo] /* false */
  409. [href='foo'] /* true */
  410. [href="foo"] /* true */
  411. [href] /* undefined */
  412. ```
  413. ### `attribute.qualifiedAttribute`
  414. Returns the attribute name qualified with the namespace if one is given.
  415. ### `attribute.offsetOf(part)`
  416. Returns the offset of the attribute part specified relative to the
  417. start of the node of the output string. This is useful in raising
  418. error messages about a specific part of the attribute, especially
  419. in combination with `attribute.sourceIndex`.
  420. Returns `-1` if the name is invalid or the value doesn't exist in this
  421. attribute.
  422. The legal values for `part` are:
  423. * `"ns"` - alias for "namespace"
  424. * `"namespace"` - the namespace if it exists.
  425. * `"attribute"` - the attribute name
  426. * `"attributeNS"` - the start of the attribute or its namespace
  427. * `"operator"` - the match operator of the attribute
  428. * `"value"` - The value (string or identifier)
  429. * `"insensitive"` - the case insensitivity flag
  430. ### `attribute.raws.unquoted`
  431. Returns the unquoted content of the attribute's value.
  432. Remains `undefined` if there is no attribute value.
  433. ```css
  434. [href=foo] /* foo */
  435. [href='foo'] /* foo */
  436. [href="foo"] /* foo */
  437. [href] /* undefined */
  438. ```
  439. ### `attribute.spaces`
  440. Like `node.spaces` with the `before` and `after` values containing the spaces
  441. around the element, the parts of the attribute can also have spaces before
  442. and after them. The for each of `attribute`, `operator`, `value` and
  443. `insensitive` there is corresponding property of the same nam in
  444. `node.spaces` that has an optional `before` or `after` string containing only
  445. whitespace.
  446. Note that corresponding values in `attributes.raws.spaces` contain values
  447. including any comments. If set, these values will override the
  448. `attribute.spaces` value. Take care to remove them if changing
  449. `attribute.spaces`.
  450. ### `attribute.raws`
  451. The raws object stores comments and other information necessary to re-render
  452. the node exactly as it was in the source.
  453. If a comment is embedded within the identifiers for the `namespace`, `attribute`
  454. or `value` then a property is placed in the raws for that value containing the full source of the propery including comments.
  455. If a comment is embedded within the space between parts of the attribute
  456. then the raw for that space is set accordingly.
  457. Setting an attribute's property `raws` value to be deleted.
  458. For now, changing the spaces required also updating or removing any of the
  459. raws values that override them.
  460. Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as:
  461. ```js
  462. {
  463. attribute: "href",
  464. operatator: "=",
  465. value: "test",
  466. spaces: {
  467. before: '',
  468. after: '',
  469. attribute: { before: ' ', after: ' ' },
  470. operator: { after: ' ' },
  471. value: { after: ' ' },
  472. insensitive: { after: ' ' }
  473. },
  474. raws: {
  475. spaces: {
  476. attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' },
  477. operator: { after: ' /* after-operator */ ' },
  478. value: { after: '/* wow */ /*omg*/' },
  479. insensitive: { after: '/*bbq*/ /*whodoesthis*/' }
  480. },
  481. unquoted: 'test',
  482. value: 'te/*inside-value*/st'
  483. }
  484. }
  485. ```
  486. ## `Processor`
  487. ### `ProcessorOptions`
  488. * `lossless` - When `true`, whitespace is preserved. Defaults to `true`.
  489. * `updateSelector` - When `true`, if any processor methods are passed a postcss
  490. `Rule` node instead of a string, then that Rule's selector is updated
  491. with the results of the processing. Defaults to `true`.
  492. ### `process|processSync(selectors, [options])`
  493. Processes the `selectors`, returning a string from the result of processing.
  494. Note: when the `updateSelector` option is set, the rule's selector
  495. will be updated with the resulting string.
  496. **Example:**
  497. ```js
  498. const parser = require("postcss-selector-parser");
  499. const processor = parser();
  500. let result = processor.processSync(' .class');
  501. console.log(result);
  502. // => .class
  503. // Asynchronous operation
  504. let promise = processor.process(' .class').then(result => {
  505. console.log(result)
  506. // => .class
  507. });
  508. // To have the parser normalize whitespace values, utilize the options
  509. result = processor.processSync(' .class ', {lossless: false});
  510. console.log(result);
  511. // => .class
  512. // For better syntax errors, pass a PostCSS Rule node.
  513. const postcss = require('postcss');
  514. rule = postcss.rule({selector: ' #foo > a, .class '});
  515. processor.process(rule, {lossless: false, updateSelector: true}).then(result => {
  516. console.log(result);
  517. // => #foo>a,.class
  518. console.log("rule:", rule.selector);
  519. // => rule: #foo>a,.class
  520. })
  521. ```
  522. Arguments:
  523. * `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule
  524. node.
  525. * `[options] (object)`: Process options
  526. ### `ast|astSync(selectors, [options])`
  527. Like `process()` and `processSync()` but after
  528. processing the `selectors` these methods return the `Root` node of the result
  529. instead of a string.
  530. Note: when the `updateSelector` option is set, the rule's selector
  531. will be updated with the resulting string.
  532. ### `transform|transformSync(selectors, [options])`
  533. Like `process()` and `processSync()` but after
  534. processing the `selectors` these methods return the value returned by the
  535. processor callback.
  536. Note: when the `updateSelector` option is set, the rule's selector
  537. will be updated with the resulting string.
  538. ### Error Handling Within Selector Processors
  539. The root node passed to the selector processor callback
  540. has a method `error(message, options)` that returns an
  541. error object. This method should always be used to raise
  542. errors relating to the syntax of selectors. The options
  543. to this method are passed to postcss's error constructor
  544. ([documentation](http://api.postcss.org/Container.html#error)).
  545. #### Async Error Example
  546. ```js
  547. let processor = (root) => {
  548. return new Promise((resolve, reject) => {
  549. root.walkClasses((classNode) => {
  550. if (/^(.*)[-_]/.test(classNode.value)) {
  551. let msg = "classes may not have underscores or dashes in them";
  552. reject(root.error(msg, {
  553. index: classNode.sourceIndex + RegExp.$1.length + 1,
  554. word: classNode.value
  555. }));
  556. }
  557. });
  558. resolve();
  559. });
  560. };
  561. const postcss = require("postcss");
  562. const parser = require("postcss-selector-parser");
  563. const selectorProcessor = parser(processor);
  564. const plugin = postcss.plugin('classValidator', (options) => {
  565. return (root) => {
  566. let promises = [];
  567. root.walkRules(rule => {
  568. promises.push(selectorProcessor.process(rule));
  569. });
  570. return Promise.all(promises);
  571. };
  572. });
  573. postcss(plugin()).process(`
  574. .foo-bar {
  575. color: red;
  576. }
  577. `.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
  578. // CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
  579. //
  580. // > 1 | .foo-bar {
  581. // | ^
  582. // 2 | color: red;
  583. // 3 | }
  584. ```
  585. #### Synchronous Error Example
  586. ```js
  587. let processor = (root) => {
  588. root.walkClasses((classNode) => {
  589. if (/.*[-_]/.test(classNode.value)) {
  590. let msg = "classes may not have underscores or dashes in them";
  591. throw root.error(msg, {
  592. index: classNode.sourceIndex,
  593. word: classNode.value
  594. });
  595. }
  596. });
  597. };
  598. const postcss = require("postcss");
  599. const parser = require("postcss-selector-parser");
  600. const selectorProcessor = parser(processor);
  601. const plugin = postcss.plugin('classValidator', (options) => {
  602. return (root) => {
  603. root.walkRules(rule => {
  604. selectorProcessor.processSync(rule);
  605. });
  606. };
  607. });
  608. postcss(plugin()).process(`
  609. .foo-bar {
  610. color: red;
  611. }
  612. `.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));
  613. // CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
  614. //
  615. // > 1 | .foo-bar {
  616. // | ^
  617. // 2 | color: red;
  618. // 3 | }
  619. ```