Skip to content

cascade-layer-name-parser #755

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
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
27 changes: 27 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"workspaces": [
"packages/css-tokenizer",
"packages/css-parser-algorithms",
"packages/cascade-layer-name-parser",
"packages/media-query-list-parser",
"packages/*",
"plugins/postcss-progressive-custom-properties",
Expand Down
6 changes: 6 additions & 0 deletions packages/cascade-layer-name-parser/.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.json
1 change: 1 addition & 0 deletions packages/cascade-layer-name-parser/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v16.13.1
3 changes: 3 additions & 0 deletions packages/cascade-layer-name-parser/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### 1.0.0 (Unreleased)

- Initial version
20 changes: 20 additions & 0 deletions packages/cascade-layer-name-parser/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright 2022 Romain Menke, Antonio Laguna <[email protected]>

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,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.
32 changes: 32 additions & 0 deletions packages/cascade-layer-name-parser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Cascade Layer Name Parser

[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/cascade-layer-name-parser.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]

## Usage

Add [Cascade Layer Name Parser] to your project:

```bash
npm install postcss @csstools/cascade-layer-name-parser @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev
```

[Cascade Layer Name Parser] depends on our CSS tokenizer and parser algorithms.
It must be used together with `@csstools/css-tokenizer` and `@csstools/css-parser-algorithms`.

```ts
import { parse } from '@csstools/cascade-layer-name-parser';

const layerNames = parse('layer-name, foo.bar');
layerNames.forEach((layerName) => {
console.log(layerName.name()) // "foo.bar"
console.log(layerName.segments()) // ["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/cascade-layer-name-parser

[Cascade Layer Name Parser]: https://github.com/csstools/postcss-plugins/tree/main/packages/cascade-layer-name-parser
1 change: 1 addition & 0 deletions packages/cascade-layer-name-parser/dist/index.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"use strict";var e=require("@csstools/css-tokenizer"),t=require("@csstools/css-parser-algorithms");class LayerName{parts;constructor(e){this.parts=e}tokens(){return[...this.parts]}slice(t,n){const r=[];for(let t=0;t<this.parts.length;t++)this.parts[t][0]===e.TokenType.Ident&&r.push(t);const s=r.slice(t,n);return new LayerName(this.parts.slice(s[0],s[s.length-1]+1))}concat(t){const n=[e.TokenType.Delim,".",-1,-1,{value:"."}];return new LayerName([...this.parts.filter((t=>t[0]===e.TokenType.Ident||t[0]===e.TokenType.Delim)),n,...t.parts.filter((t=>t[0]===e.TokenType.Ident||t[0]===e.TokenType.Delim))])}segments(){return this.parts.filter((t=>t[0]===e.TokenType.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((t=>t[0]===e.TokenType.Ident||t[0]===e.TokenType.Delim)).map((e=>e[1])).join("")}equal(e){const t=this.segments(),n=e.segments();if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++){if(t[e]!==n[e])return!1}return!0}toString(){return e.stringify(...this.parts)}toJSON(){return{parts:this.parts,segments:this.segments(),name:this.name()}}}function parseFromTokens(n,r){const s=t.parseCommaSeparatedListOfComponentValues(n,{onParseError:null==r?void 0:r.onParseError}),o=(null==r?void 0:r.onParseError)??(()=>{}),genericError=e=>({message:`Invalid cascade layer name. ${e}`,start:n[0][2],end:n[n.length-1][3],state:["6.4.2. Layer Naming and Nesting","Layer name syntax","<layer-name> = <ident> [ '.' <ident> ]*"]}),a=[];for(let n=0;n<s.length;n++){const r=s[n];for(let e=0;e<r.length;e++){const n=r[e];if(!t.isTokenNode(n)&&!t.isCommentNode(n)&&!t.isWhitespaceNode(n))return o(genericError(`Invalid layer name part "${n.toString()}"`)),[]}const i=r.flatMap((e=>e.tokens()));let p,l=!1,m=!1;for(let t=0;t<i.length;t++){const n=i[t];if(n[0]!==e.TokenType.Comment&&n[0]!==e.TokenType.Whitespace&&n[0]!==e.TokenType.Ident&&(n[0]!==e.TokenType.Delim||"."!==n[4].value))return o(genericError(`Invalid character "${n[1]}"`)),[];if(!l&&n[0]===e.TokenType.Delim)return o(genericError("Layer names can not start with a dot.")),[];if(l){if(n[0]===e.TokenType.Whitespace){m=!0;continue}if(m&&n[0]===e.TokenType.Comment)continue;if(m)return o(genericError("Encountered unexpected whitespace between layer name parts.")),[];if(p[0]===e.TokenType.Ident&&n[0]===e.TokenType.Ident)return o(genericError("Layer name parts must be separated by dots.")),[];if(p[0]===e.TokenType.Delim&&n[0]===e.TokenType.Delim)return o(genericError("Layer name parts must not be empty.")),[]}n[0]===e.TokenType.Ident&&(l=!0),n[0]!==e.TokenType.Ident&&n[0]!==e.TokenType.Delim||(p=n)}if(!p)return o(genericError("Empty layer name.")),[];if(p[0]===e.TokenType.Delim)return o(genericError("Layer name must not end with a dot.")),[];a.push(new LayerName(i))}return a}exports.LayerName=LayerName,exports.addLayerToModel=function addLayerToModel(e,t){return t.forEach((t=>{const n=t.segments();e:for(let r=0;r<n.length;r++){const n=t.slice(0,r+1),s=n.segments();let o=-1,a=0;for(let t=0;t<e.length;t++){const n=e[t].segments();let r=0;t:for(let e=0;e<n.length;e++){const t=n[e],o=s[e];if(o===t&&e+1===s.length)continue e;if(o!==t){if(o!==t)break t}else r++}r>=a&&(o=t,a=r)}-1===o?e.push(n):e.splice(o+1,0,n)}})),e},exports.parse=function parse(t,n){const r=e.tokenizer({css:t},{commentsAreTokens:!0,onParseError:null==n?void 0:n.onParseError}),s=[];for(;!r.endOfFile();)s.push(r.nextToken());return s.push(r.nextToken()),parseFromTokens(s,n)},exports.parseFromTokens=parseFromTokens;
3 changes: 3 additions & 0 deletions packages/cascade-layer-name-parser/dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { LayerName } from './nodes/layer-name';
export { addLayerToModel } from './util/model';
export { parse, parseFromTokens } from './parser/parse';
1 change: 1 addition & 0 deletions packages/cascade-layer-name-parser/dist/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import{TokenType as e,stringify as t,tokenizer as n}from"@csstools/css-tokenizer";import{parseCommaSeparatedListOfComponentValues as r,isTokenNode as s,isCommentNode as a,isWhitespaceNode as o}from"@csstools/css-parser-algorithms";class LayerName{parts;constructor(e){this.parts=e}tokens(){return[...this.parts]}slice(t,n){const r=[];for(let t=0;t<this.parts.length;t++)this.parts[t][0]===e.Ident&&r.push(t);const s=r.slice(t,n);return new LayerName(this.parts.slice(s[0],s[s.length-1]+1))}concat(t){const n=[e.Delim,".",-1,-1,{value:"."}];return new LayerName([...this.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim)),n,...t.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim))])}segments(){return this.parts.filter((t=>t[0]===e.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim)).map((e=>e[1])).join("")}equal(e){const t=this.segments(),n=e.segments();if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++){if(t[e]!==n[e])return!1}return!0}toString(){return t(...this.parts)}toJSON(){return{parts:this.parts,segments:this.segments(),name:this.name()}}}function addLayerToModel(e,t){return t.forEach((t=>{const n=t.segments();e:for(let r=0;r<n.length;r++){const n=t.slice(0,r+1),s=n.segments();let a=-1,o=0;for(let t=0;t<e.length;t++){const n=e[t].segments();let r=0;t:for(let e=0;e<n.length;e++){const t=n[e],a=s[e];if(a===t&&e+1===s.length)continue e;if(a!==t){if(a!==t)break t}else r++}r>=o&&(a=t,o=r)}-1===a?e.push(n):e.splice(a+1,0,n)}})),e}function parseFromTokens(t,n){const i=r(t,{onParseError:null==n?void 0:n.onParseError}),l=(null==n?void 0:n.onParseError)??(()=>{}),genericError=e=>({message:`Invalid cascade layer name. ${e}`,start:t[0][2],end:t[t.length-1][3],state:["6.4.2. Layer Naming and Nesting","Layer name syntax","<layer-name> = <ident> [ '.' <ident> ]*"]}),m=[];for(let t=0;t<i.length;t++){const n=i[t];for(let e=0;e<n.length;e++){const t=n[e];if(!s(t)&&!a(t)&&!o(t))return l(genericError(`Invalid layer name part "${t.toString()}"`)),[]}const r=n.flatMap((e=>e.tokens()));let c,u=!1,p=!1;for(let t=0;t<r.length;t++){const n=r[t];if(n[0]!==e.Comment&&n[0]!==e.Whitespace&&n[0]!==e.Ident&&(n[0]!==e.Delim||"."!==n[4].value))return l(genericError(`Invalid character "${n[1]}"`)),[];if(!u&&n[0]===e.Delim)return l(genericError("Layer names can not start with a dot.")),[];if(u){if(n[0]===e.Whitespace){p=!0;continue}if(p&&n[0]===e.Comment)continue;if(p)return l(genericError("Encountered unexpected whitespace between layer name parts.")),[];if(c[0]===e.Ident&&n[0]===e.Ident)return l(genericError("Layer name parts must be separated by dots.")),[];if(c[0]===e.Delim&&n[0]===e.Delim)return l(genericError("Layer name parts must not be empty.")),[]}n[0]===e.Ident&&(u=!0),n[0]!==e.Ident&&n[0]!==e.Delim||(c=n)}if(!c)return l(genericError("Empty layer name.")),[];if(c[0]===e.Delim)return l(genericError("Layer name must not end with a dot.")),[];m.push(new LayerName(r))}return m}function parse(e,t){const r=n({css:e},{commentsAreTokens:!0,onParseError:null==t?void 0:t.onParseError}),s=[];for(;!r.endOfFile();)s.push(r.nextToken());return s.push(r.nextToken()),parseFromTokens(s,t)}export{LayerName,addLayerToModel,parse,parseFromTokens};
17 changes: 17 additions & 0 deletions packages/cascade-layer-name-parser/dist/nodes/layer-name.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { CSSToken } from '@csstools/css-tokenizer';
export declare class LayerName {
parts: Array<CSSToken>;
constructor(parts: Array<CSSToken>);
tokens(): Array<CSSToken>;
slice(start: number, end: number): LayerName;
concat(other: LayerName): LayerName;
segments(): Array<string>;
name(): string;
equal(other: LayerName): boolean;
toString(): string;
toJSON(): {
parts: CSSToken[];
segments: string[];
name: string;
};
}
8 changes: 8 additions & 0 deletions packages/cascade-layer-name-parser/dist/parser/parse.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ParserError } from '@csstools/css-parser-algorithms/dist/interfaces/error';
import { CSSToken } from '@csstools/css-tokenizer';
import { LayerName } from '../nodes/layer-name';
export type Options = {
onParseError?: (error: ParserError) => void;
};
export declare function parseFromTokens(tokens: Array<CSSToken>, options?: Options): LayerName[];
export declare function parse(source: string, options?: Options): LayerName[];
2 changes: 2 additions & 0 deletions packages/cascade-layer-name-parser/dist/util/model.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { LayerName } from '../nodes/layer-name';
export declare function addLayerToModel(layers: Array<LayerName>, currentLayerNames: Array<LayerName>): LayerName[];
72 changes: 72 additions & 0 deletions packages/cascade-layer-name-parser/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"name": "@csstools/cascade-layer-name-parser",
"description": "Parse CSS Cascade Layer names.",
"version": "1.0.0",
"contributors": [
{
"name": "Antonio Laguna",
"email": "[email protected]",
"url": "https://antonio.laguna.es"
},
{
"name": "Romain Menke",
"email": "[email protected]"
}
],
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/csstools"
},
"engines": {
"node": "^14 || ^16 || >=18"
},
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"default": "./dist/index.mjs"
}
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist"
],
"peerDependencies": {
"@csstools/css-parser-algorithms": "^1.0.0",
"@csstools/css-tokenizer": "^1.0.0"
},
"scripts": {
"prebuild": "npm run clean",
"build": "rollup -c ../../rollup/default.mjs",
"clean": "node -e \"fs.rmSync('./dist', { recursive: true, force: true }); fs.mkdirSync('./dist');\"",
"lint": "npm run lint:eslint && npm run lint:package-json",
"lint:eslint": "eslint ./src --ext .js --ext .ts --ext .mjs --no-error-on-unmatched-pattern",
"lint:package-json": "node ../../.github/bin/format-package-json.mjs",
"prepublishOnly": "npm run clean && npm run build && npm run test",
"stryker": "stryker run --logLevel error",
"test": "node ./test/test.mjs",
"test:exports": "node ./test/_import.mjs && node ./test/_require.cjs",
"test:rewrite-expects": "REWRITE_EXPECTS=true node ./test/test.mjs"
},
"homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/cascade-layer-name-parser#readme",
"repository": {
"type": "git",
"url": "https://github.com/csstools/postcss-plugins.git",
"directory": "packages/cascade-layer-name-parser"
},
"bugs": "https://github.com/csstools/postcss-plugins/issues",
"keywords": [
"cascade-layer",
"css",
"parser"
],
"volta": {
"extends": "../../package.json"
}
}
3 changes: 3 additions & 0 deletions packages/cascade-layer-name-parser/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { LayerName } from './nodes/layer-name';
export { addLayerToModel } from './util/model';
export { parse, parseFromTokens } from './parser/parse';
94 changes: 94 additions & 0 deletions packages/cascade-layer-name-parser/src/nodes/layer-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { TokenDelim } from '@csstools/css-tokenizer';
import { CSSToken, stringify, TokenIdent, TokenType } from '@csstools/css-tokenizer';

export class LayerName {
parts: Array<CSSToken>;

constructor(parts: Array<CSSToken>) {
this.parts = parts;
}

tokens(): Array<CSSToken> {
return [
...this.parts,
];
}

slice(start: number, end: number): LayerName {
const indices = [];
for (let i = 0; i < this.parts.length; i++) {
if (this.parts[i][0] === TokenType.Ident) {
indices.push(i);
}
}

const slice = indices.slice(start, end);
return new LayerName(this.parts.slice(slice[0], slice[slice.length-1]+1));
}

concat(other: LayerName): LayerName {
const dot: TokenDelim = [
TokenType.Delim,
'.',
-1,
-1,
{ value: '.' },
];

return new LayerName([
...this.parts.filter((x) => {
return x[0] === TokenType.Ident || x[0] === TokenType.Delim;
}),
dot,
...other.parts.filter((x) => {
return x[0] === TokenType.Ident || x[0] === TokenType.Delim;
}),
]);
}

segments(): Array<string> {
return this.parts.filter((x) => {
return x[0] === TokenType.Ident;
}).map((x: TokenIdent) => {
return x[4].value;
});
}

name(): string {
return this.parts.filter((x) => {
return x[0] === TokenType.Ident || x[0] === TokenType.Delim;
}).map((x: TokenIdent) => {
return x[1];
}).join('');
}

equal(other: LayerName): boolean {
const a = this.segments();
const b = other.segments();
if (a.length !== b.length) {
return false;
}

for (let i = 0; i < a.length; i++) {
const aa = a[i];
const bb = b[i];
if (aa !== bb) {
return false;
}
}

return true;
}

toString(): string {
return stringify(...this.parts);
}

toJSON() {
return {
parts: this.parts,
segments: this.segments(),
name: this.name(),
};
}
}
Loading