8161f92a2bd13bacee8286b56073f53ca690bb5c10ab8c12bba4632afd2aba9d27f384248b4310f76690bfcb334618c7a590e9f793cb7a87eec9da5b2725b5 19 KB

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