8000 implement composes support #116 · tbela99/css-parser@270f4a2 · GitHub
Skip to content

Commit 270f4a2

Browse files
committed
implement composes support #116
1 parent ccc738f commit 270f4a2

File tree

249 files changed

+12744
-9379
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

249 files changed

+12744
-9379
lines changed

CHANGELOG.md

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,23 @@
77
### CSS Module
88

99
- [x] scoped name generation
10-
- [ ] @values
1110
- [ ] :import
12-
- [ ] composes: https://github.com/css-modules/css-modules/blob/master/docs/composition.md
13-
- [ ] compose from local selector
14-
- [ ] compose from other files
15-
- [ ] compose from global selector
11+
- [ ] :export
12+
- [x] composes: https://github.com/css-modules/css-modules/blob/master/docs/composition.md
13+
- [x] compose from local selector
14+
- [x] compose from other files
15+
- [x] compose from global selector
1616
- [x] :local
1717
- [x] :global
1818
- [x] :local()
1919
- [x] :global()
2020
- [x] selector
21+
- [x] css variables
22+
- [ ] css at-rule values
23+
- [ ] css at-rule property
2124
- [ ] keyframe
2225
- [x] grid-template-areas
23-
- [x] dashed ident
26+
- [x] dashed ident (custom properties)
2427
- [ ] animations
2528
- [ ] pure
2629
- [ ] default mode

dist/index-umd-web.js

Lines changed: 578 additions & 17 deletions
Large diffs are not rendered by default.

dist/index.cjs

Lines changed: 578 additions & 17 deletions
Large diffs are not rendered by default.

dist/index.d.ts

Lines changed: 98 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,10 @@ declare enum EnumToken {
422422
* invalid declaration node type
423423
*/
424424< B875 /code>
InvalidDeclarationNodeType = 94,
425+
/**
426+
* composes token node type
427+
*/
428+
ComposesSelectorNodeType = 95,
425429
/**
426430
* alias for time token type
427431
*/
@@ -1693,6 +1697,16 @@ export declare interface ListToken extends BaseToken {
16931697
chi: Token$1[];
16941698
}
16951699

1700+
/**
1701+
* Composes selector token
1702+
*/
1703+
export declare interface ComposesSelectorToken extends BaseToken {
1704+
1705+
typ: EnumToken.ComposesSelectorTokenType;
1706+
l: Token$1[];
1707+
r: Token$1 | null;
1708+
}
1709+
16961710
/**
16971711
* Unary expression node
16981712
*/
@@ -1784,6 +1798,7 @@ export declare type Token$1 =
17841798
| ContainMatchToken
17851799
| MatchExpressionToken
17861800
| NameSpaceAttributeToken
1801+
| ComposesSelectorToken
17871802
|
17881803
DashMatchToken
17891804
| EqualMatchToken
@@ -2502,7 +2517,7 @@ export declare interface VisitorNodeMap {
25022517
* // body {color:#f3fff0}
25032518
* ```
25042519
*/
2505-
[key: keyof typeof EnumToken]: GenericVisitorAstNodeHandlerMap<Token> | GenericVisitorAstNodeHandlerMap<AstNode>;
2520+
[key : keyof typeof EnumToken]: GenericVisitorAstNodeHandlerMap<Token> | GenericVisitorAstNodeHandlerMap<AstNode>;
25062521
}
25072522

25082523
export declare interface PropertyListOptions {
@@ -3074,9 +3089,9 @@ export declare type WalkerOption = WalkerOptionEnum | AstNode$1 | Token$1 | null
30743089
export declare type WalkerFilter = (node: AstNode$1) => WalkerOption;
30753090

30763091
/**
3077-
* filter nod
3092+
* filter nodes
30783093
*/
3079-
export declare type WalkerValueFilter = (node: AstNode$1 | Token$1, parent?: AstNode$1 | Token$1 | null, event?: WalkerEvent) => WalkerOption | null;
3094+
export declare type WalkerValueFilter = (node: AstNode$1 | Token$1, parent?: AstNode$1 | Token$1 | AstNode$1[] | Token$1[] | null, event?: WalkerEvent) => WalkerOption | null;
30803095

30813096
export declare interface WalkResult {
30823097
node: AstNode$1;
@@ -3268,6 +3283,61 @@ export declare type LoadResult =
32683283
| string
32693284
| Promise<string>;
32703285

3286+
export declare interface ModuleOptions {
3287+
3288+
3289+
/**
3290+
* use local scope vs global scope
3291+
*/
3292+
scoped?: boolean;
3293+
3294+
/**
3295+
* module output file path
3296+
*/
3297+
filePath?: string;
3298+
3299+
/**
3300+
* module hash length
3301+
*/
3302+
hashLength?: number;
3303+
3304+
/**
3305+
* scoped name pattern. the supported placeholders are:
3306+
* - name: the file base name without the extension
3307+
* - hash: the file path hash
3308+
* - local: the local name
3309+
* - path: the file path
3310+
* - folder: the file folder
3311+
* - ext: the file extension
3312+
*
3313+
* pattern can optionally have a maximum number of characters: `pattern: '[name:2]-[hash:5]'`.
3314+
* the hash pattern can take an algorithm, a maximum number of characters or both: `pattern: '[name]-[hash:base64:5]'` or `pattern: '[name]-[hash:5]'` or `pattern: '[name]-[hash:sha1]'`.
3315+
* supported hash algorithms are:
3316+
* - base64
3317+
* - hex
3318+
* - base64url
3319+
* - sha1
3320+
* - sha256
3321+
* - sha384
3322+
* - sha512
3323+
*/
3324+
pattern?: string;
3325+
3326+
/**
3327+
* optional function to generate scoped name
3328+
* @param localName
3329+
* @param filePath
3330+
* @param hashLength
3331+
* @param pattern see {@link ParserOptions.module.pattern}
3332+
*/
3333+
generateScopedName?: (
3334+
localName: string,
3335+
filePath: string,
3336+
pattern: string,
3337+
hashLength?: number
3338+
) => string | Promise<string>;
3339+
}
3340+
32713341
/**
32723342
* parser options
32733343
*/
@@ -3306,7 +3376,7 @@ export declare interface ParserOptions extends MinifyOptions, MinifyFeatureOptio
33063376
* @param asStream
33073377
*
33083378
*/
3309-
load?: (url: string, currentUrl: string, asStream?: boolean) => LoadResult;
3379+
load?: (url: string, currentUrl?: string, asStream?: boolean) => LoadResult;
33103380
/**
33113381
* get directory name
33123382
* @param path
@@ -3360,6 +3430,11 @@ export declare interface ParserOptions extends MinifyOptions, MinifyFeatureOptio
33603430
* @private
33613431
*/
33623432
cache?: WeakMap<AstNode$1, string>;
3433+
3434+
/**
3435+
* css modules options
3436+
*/
3437+
module?: boolean | ModuleOptions
33633438
}
33643439

33653440
/**
@@ -3536,13 +3611,17 @@ export declare interface ParseResultStats {
35363611
*/
35373612
importedBytesIn: number;
35383613
/**
3539-
* parse time
3614+
* parse processing time
35403615
*/
35413616
parse: string;
35423617
/**
3543-
* minify time
3618+
* minify processing time
35443619
*/
35453620
minify: string;
3621+
/**
3622+
* module processing time
3623+
*/
3624+
module?: string;
35463625
/**
35473626
* total time
35483627
*/
@@ -3578,7 +3657,18 @@ export declare interface ParseResult {
35783657
/**
35793658
* parse stats
35803659
*/
3581-
stats: ParseResultStats
3660+
stats: ParseResultStats;
3661+
3662+
/**
3663+
* css module mapping
3664+
*/
3665+
mapping?: Record<string, string>;
3666+
3667+
/**
3668+
* css module reverse mapping
3669+
* @private
3670+
*/
3671+
revMapping?: Record<string, string>;
35823672
}
35833673

35843674
/**
@@ -3958,4 +4048,4 @@ declare function transformFile(file: string, options?: TransformOptions, asStrea
39584048
declare function transform(css: string | ReadableStream<Uint8Array>, options?: TransformOptions): Promise<TransformResult>;
39594049

39604050
export { ColorType, EnumToken, FeatureWalkMode, SourceMap, ValidationLevel, WalkerEvent, WalkerOptionEnum, convertColor, dirname, expand, isOkLabClose, load, mathFuncs, minify, okLabDistance, parse, parseDeclarations, parseFile, parseString, parseTokens, render, renderToken, resolve, transform, transformFile, transformFunctions, walk, walkValues };
3961-
export type { AddToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyFrameRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstRule, AstRuleList, AstStyleSheet, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ConstraintsMapping, ContainMatchToken, Context, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorHandler, GenericVisitorResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, ImportantToken, IncludeMatchToken, InvalidAttrToken, InvalidClassSelectorToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Location, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureAndToken, MediaFeatureNotToken, MediaFeatureOnlyToken, MediaFeatureOrToken, MediaFeatureToken, MediaQueryConditionToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, MulToken, NameSpaceAttributeToken, NestingSelectorToken, NextSiblingCombinatorToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo, ParseResult, ParseResultStats, ParseTokenOptions, ParserOptions, PercentageToken, Position, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenizeResult, TransformOptions, TransformResult, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, Value, ValueVisitorHandler, VariableScopeInfo, VisitorNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerValueFilter, WhitespaceToken };
4051+
export type { AddToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyFrameRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstRule, AstRuleList, AstStyleSheet, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ComposesSelectorToken, ConstraintsMapping, ContainMatchToken, Context, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorHandler, GenericVisitorResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, ImportantToken, IncludeMatchToken, InvalidAttrToken, InvalidClassSelectorToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Location, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureAndToken, MediaFeatureNotToken, MediaFeatureOnlyToken, MediaFeatureOrToken, MediaFeatureToken, MediaQueryConditionToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleOptions, MulToken, NameSpaceAttributeToken, NestingSelectorToken, NextSiblingCombinatorToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo, ParseResult, ParseResultStats, ParseTokenOptions, ParserOptions, PercentageToken, Position, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenizeResult, TransformOptions, TransformResult, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, Value, ValueVisitorHandler, VariableScopeInfo, VisitorNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerValueFilter, WhitespaceToken };

dist/lib/ast/types.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,10 @@ var EnumToken;
427427
* invalid declaration node type
428428
*/
429429
EnumToken[EnumToken["InvalidDeclarationNodeType"] = 94] = "InvalidDeclarationNodeType";
430+
/**
431+
* composes token node type
432+
*/
433+
EnumToken[EnumToken["ComposesSelectorNodeType"] = 95] = "ComposesSelectorNodeType";
430434
/* aliases */
431435
/**
432436
* alias for time token type

dist/lib/ast/walk.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -221,8 +221,13 @@ function* walkValues(values, root = null, filter, reverse) {
221221
continue;
222222
}
223223
// @ts-ignore
224-
if (option != null && typeof option == 'object' && 'typ' in option) {
225-
map.set(option, map.get(value) ?? root);
224+
if (option != null && typeof option == 'object' && ('typ' in option || Array.isArray(option))) {
225+
const op = Array.isArray(option) ? option : [option];
226+
for (const o of op) {
227+
map.set(o, map.get(value) ?? root);
228+
}
229+
stack[reverse ? 'push' : 'unshift'](...op);
230+
console.error({ op, s: stack[0] });
226231
}
227232
}
228233
}
@@ -281,8 +286,12 @@ function* walkValues(values, root = null, filter, reverse) {
281286
if (isValid) {
282287
option = filter.fn(value, map.get(value), WalkerEvent.Leave);
283288
// @ts-ignore
284-
if (option != null && 'typ' in option) {
285-
map.set(option, map.get(value) ?? root);
289+
if (option != null && ('typ' in option || Array.isArray(option))) {
290+
const op = Array.isArray(option) ? option : [option];
291+
for (const o of op) {
292+
map.set(o, map.get(value) ?? root);
293+
}
294+
stack[reverse ? 'push' : 'unshift'](...op);
286295
}
287296
}
288297
}

dist/lib/parser/declaration/list.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,12 @@ class PropertyList {
2525
});
2626
}
2727
add(...declarations) {
28+
let name;
2829
for (const declaration of declarations) {
30+
name = declaration.typ != EnumToken.DeclarationNodeType ? null : declaration.nam.toLowerCase();
2931
if (declaration.typ != EnumToken.DeclarationNodeType ||
30-
(typeof this.options.removeDuplicateDeclarations === 'string' && this.options.removeDuplicateDeclarations === declaration.nam.toLowerCase()) ||
32+
'composes' === name ||
33+
(typeof this.options.removeDuplicateDeclarations === 'string' && this.options.removeDuplicateDeclarations === name) ||
3134
(Array.isArray(this.options.removeDuplicateDeclarations) ? this.options.removeDuplicateDeclarations.includes(declaration.nam) : !this.options.removeDuplicateDeclarations)) {
3235
this.declarations.set(Number(Math.random().toString().slice(2)).toString(36), declaration);
3336
continue;

0 commit comments

Comments
 (0)