Skip to content

selector-resolve-nested #1254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions packages/selector-resolve-nested/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
package-lock.json
yarn.lock
*.result.css
*.result.css.map
*.result.html
1 change: 1 addition & 0 deletions packages/selector-resolve-nested/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.2.0
5 changes: 5 additions & 0 deletions packages/selector-resolve-nested/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changes to Selector Resolve Nested

### Unreleased (major)

- Initial version
18 changes: 18 additions & 0 deletions packages/selector-resolve-nested/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
MIT No Attribution (MIT-0)

Copyright © CSSTools Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 33 additions & 0 deletions packages/selector-resolve-nested/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Selector Resolve Nested

[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/selector-resolve-nested.svg" height="20">][npm-url]
[<img alt="Build Status" src="https://github.com/csstools/postcss-plugins/workflows/test/badge.svg" height="20">][cli-url]
[<img alt="Discord" src="https://shields.io/badge/Discord-5865F2?logo=discord&logoColor=white">][discord]

## API

[Read the API docs](./docs/selector-resolve-nested.md)

## Usage

Add [Selector Resolve Nested] to your project:

```bash
npm install @csstools/selector-resolve-nested --save-dev
```

```js
import { resolveNestedSelector } from '@csstools/selector-resolve-nested';
import parser from 'postcss-selector-parser';

const a = parser().astSync('.foo &');
const b = parser().astSync('.bar');

resolveNestedSelector(a, b); // '.foo .bar'
```

[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test
[discord]: https://discord.gg/bUadyRwkJS
[npm-url]: https://www.npmjs.com/package/@csstools/selector-resolve-nested

[Selector Resolve Nested]: https://github.com/csstools/postcss-plugins/tree/main/packages/selector-resolve-nested
7 changes: 7 additions & 0 deletions packages/selector-resolve-nested/api-extractor.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"extends": "../../api-extractor.json",
"docModel": {
"enabled": true
}
}
1 change: 1 addition & 0 deletions packages/selector-resolve-nested/dist/index.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";var e=require("postcss-selector-parser");function sortCompoundSelectorsInsideComplexSelector(t){const o=[];let r=[];t.each((t=>{if("combinator"===t.type)return o.push(r,[t]),void(r=[]);if(e.isPseudoElement(t))return o.push(r),void(r=[t]);if("universal"===t.type&&r.find((e=>"universal"===e.type)))t.remove();else{if("tag"===t.type&&r.find((e=>"tag"===e.type))){t.remove();const o=e.pseudo({value:":is"});return o.append(e.selector({nodes:[t],value:""})),void r.push(o)}r.push(t)}})),o.push(r);const n=[];for(let e=0;e<o.length;e++){const t=o[e];t.sort(((e,t)=>selectorTypeOrder(e)-selectorTypeOrder(t))),n.push(...t)}t.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),t.prepend(n[e])}function selectorTypeOrder(o){return e.isPseudoElement(o)?t.pseudoElement:t[o.type]}const t={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function prepareParentSelectors(t,o=!1){return o||!isCompoundSelector(t.nodes)?[e.pseudo({value:":is",nodes:t.nodes.map((e=>e.clone()))})]:t.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(t){return 1===t.length&&!t[0].nodes.some((t=>"combinator"===t.type||e.isPseudoElement(t)))}exports.resolveNestedSelector=function resolveNestedSelector(t,o){const r=[];for(let n=0;n<t.nodes.length;n++){const s=t.nodes[n].clone();{let t=!1;s.walkNesting((()=>(t=!0,!1))),t?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({})):(s.prepend(e.combinator({value:" "})),s.prepend(e.nesting({})))}{const e=new Set;s.walkNesting((t=>{const r=t.parent;e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?t.replaceWith(...prepareParentSelectors(o,!0)):t.replaceWith(...prepareParentSelectors(o))}));for(const t of e)sortCompoundSelectorsInsideComplexSelector(t)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}return e.root({nodes:r,value:""})};
33 changes: 33 additions & 0 deletions packages/selector-resolve-nested/dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Resolve nested selectors following the CSS nesting specification.
*
* @example
*
* ```js
* import { resolveNestedSelector } from '@csstools/selector-resolve-nested';
* import parser from 'postcss-selector-parser';
*
* const selector = parser().astSync('.foo &');
* const parent = parser().astSync('.bar');
*
* // .foo .bar
* console.log(
* resolveNestedSelector(selector, parent).toString()
* )
* ```
*
* @packageDocumentation
*/

import type { Root } from 'postcss-selector-parser';

/**
* Resolve a nested selector against a given parent selector.
*
* @param selector - The selector to resolve.
* @param parentSelector - The parent selector to resolve against.
* @returns The resolved selector.
*/
export declare function resolveNestedSelector(selector: Root, parentSelector: Root): Root;

export { }
1 change: 1 addition & 0 deletions packages/selector-resolve-nested/dist/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import e from"postcss-selector-parser";function sortCompoundSelectorsInsideComplexSelector(o){const t=[];let r=[];o.each((o=>{if("combinator"===o.type)return t.push(r,[o]),void(r=[]);if(e.isPseudoElement(o))return t.push(r),void(r=[o]);if("universal"===o.type&&r.find((e=>"universal"===e.type)))o.remove();else{if("tag"===o.type&&r.find((e=>"tag"===e.type))){o.remove();const t=e.pseudo({value:":is"});return t.append(e.selector({nodes:[o],value:""})),void r.push(t)}r.push(o)}})),t.push(r);const n=[];for(let e=0;e<t.length;e++){const o=t[e];o.sort(((e,o)=>selectorTypeOrder(e)-selectorTypeOrder(o))),n.push(...o)}o.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),o.prepend(n[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function resolveNestedSelector(o,t){const r=[];for(let n=0;n<o.nodes.length;n++){const s=o.nodes[n].clone();{let o=!1;s.walkNesting((()=>(o=!0,!1))),o?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({})):(s.prepend(e.combinator({value:" "})),s.prepend(e.nesting({})))}{const e=new Set;s.walkNesting((o=>{const r=o.parent;e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?o.replaceWith(...prepareParentSelectors(t,!0)):o.replaceWith(...prepareParentSelectors(t))}));for(const o of e)sortCompoundSelectorsInsideComplexSelector(o)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}return e.root({nodes:r,value:""})}function prepareParentSelectors(o,t=!1){return t||!isCompoundSelector(o.nodes)?[e.pseudo({value:":is",nodes:o.nodes.map((e=>e.clone()))})]:o.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(o){return 1===o.length&&!o[0].nodes.some((o=>"combinator"===o.type||e.isPseudoElement(o)))}export{resolveNestedSelector};
12 changes: 12 additions & 0 deletions packages/selector-resolve-nested/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md)

## API Reference

## Packages

| Package | Description |
| --- | --- |
| [@csstools/selector-resolve-nested](./selector-resolve-nested.md) | Resolve nested selectors following the CSS nesting specification. |

Loading