@tbela99/css-parser 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +118 -2
  2. package/README.md +4 -3
  3. package/dist/index-umd-web.js +1629 -467
  4. package/dist/index.cjs +1629 -467
  5. package/dist/index.d.ts +72 -7
  6. package/dist/lib/ast/features/prefix.js +9 -1
  7. package/dist/lib/ast/features/shorthand.js +1 -1
  8. package/dist/lib/ast/features/transform.js +1 -1
  9. package/dist/lib/ast/math/expression.js +175 -5
  10. package/dist/lib/ast/minify.js +84 -10
  11. package/dist/lib/ast/transform/compute.js +24 -55
  12. package/dist/lib/ast/transform/minify.js +1 -1
  13. package/dist/lib/ast/types.js +12 -0
  14. package/dist/{config.json.js → lib/data/properties.json.js} +106 -0
  15. package/dist/lib/{validation/config.json.js → data/validation.json.js} +11 -8
  16. package/dist/lib/parser/declaration/list.js +8 -10
  17. package/dist/lib/parser/parse.js +8 -14
  18. package/dist/lib/parser/tokenize.js +89 -58
  19. package/dist/lib/parser/utils/at-rule-font-feature-values.js +1 -1
  20. package/dist/lib/parser/utils/at-rule-media.js +66 -0
  21. package/dist/lib/parser/utils/at-rule-when-else.js +2 -2
  22. package/dist/lib/parser/utils/base64.js +14 -0
  23. package/dist/lib/parser/utils/config.js +1 -1
  24. package/dist/lib/parser/utils/declaration.js +18 -17
  25. package/dist/lib/parser/utils/eq.js +6 -0
  26. package/dist/lib/parser/utils/hash.js +1 -0
  27. package/dist/lib/parser/utils/selector.js +99 -89
  28. package/dist/lib/parser/utils/text.js +16 -0
  29. package/dist/lib/renderer/render.js +20 -6
  30. package/dist/lib/renderer/sourcemap/lib/codec.js +8 -3
  31. package/dist/lib/renderer/sourcemap/sourcemap.js +35 -5
  32. package/dist/lib/syntax/color/alpha.js +57 -22
  33. package/dist/lib/syntax/color/cmyk.js +4 -3
  34. package/dist/lib/syntax/color/color-mix.js +18 -18
  35. package/dist/lib/syntax/color/srgb.js +11 -5
  36. package/dist/lib/syntax/color/utils/components.js +1 -1
  37. package/dist/lib/syntax/color/utils/distance.js +2 -2
  38. package/dist/lib/syntax/color/utils/matrix.js +1 -0
  39. package/dist/lib/syntax/color/xyz.js +5 -0
  40. package/dist/lib/syntax/color/xyzd50.js +17 -0
  41. package/dist/lib/syntax/constants.js +1 -1
  42. package/dist/lib/syntax/syntax.js +549 -13
  43. package/dist/lib/validation/config.js +27 -1
  44. package/dist/lib/validation/match.js +16 -4
  45. package/dist/lib/validation/parser/parse.js +7 -3
  46. package/dist/node.js +8 -14
  47. package/dist/web.js +8 -14
  48. package/package.json +4 -4
package/dist/index.d.ts CHANGED
@@ -653,6 +653,18 @@ declare enum EnumToken {
653
653
  * wrapped values token type like {Arial, sans-serif}
654
654
  */
655
655
  WrappedValuesTokenType = 140,
656
+ /**
657
+ * infinity token
658
+ */
659
+ NaNTokenType = 141,
660
+ /**
661
+ * infinity token
662
+ */
663
+ InfinityTokenType = 142,
664
+ /**
665
+ * negative infinity token
666
+ */
667
+ NegativeInfinityTokenType = 143,
656
668
  /**
657
669
  * alias for time token type
658
670
  */
@@ -1146,6 +1158,27 @@ export declare interface NumberToken extends BaseToken {
1146
1158
  val: number | FractionToken;
1147
1159
  }
1148
1160
 
1161
+ export declare interface NaNToken extends BaseToken {
1162
+ /**
1163
+ * @inheritdoc
1164
+ */
1165
+ typ: EnumToken.NaNTokenType;
1166
+ }
1167
+
1168
+ export declare interface InfinityToken extends BaseToken {
1169
+ /**
1170
+ * @inheritdoc
1171
+ */
1172
+ typ: EnumToken.InfinityTokenType;
1173
+ }
1174
+
1175
+ export declare interface NegativeInfinityToken extends BaseToken {
1176
+ /**
1177
+ * @inheritdoc
1178
+ */
1179
+ typ: EnumToken.NegativeInfinityTokenType;
1180
+ }
1181
+
1149
1182
  /**
1150
1183
  * At rule token
1151
1184
  */
@@ -2649,6 +2682,9 @@ export declare type Token$1 =
2649
2682
  | FunctionDefToken
2650
2683
  | RawNodeToken
2651
2684
  | InvalidMediaQueryToken
2685
+ | NaNToken
2686
+ | InfinityToken
2687
+ | NegativeInfinityToken
2652
2688
  | EOFToken;
2653
2689
 
2654
2690
  /**
@@ -3936,6 +3972,35 @@ export declare interface VisitorNodeMap {
3936
3972
 
3937
3973
  /**
3938
3974
  * Generate and parse source map
3975
+ *
3976
+ * ```ts
3977
+ * const sourcemap = new SourceMap();
3978
+ *
3979
+ * // you can also pass an input sourcemap
3980
+ * // const sourcemap = new SourceMap(sourcemapObjectOrJSONString);
3981
+ *
3982
+ * sourcemap.addSourceContent(0, '/css/styles.css', null);
3983
+ * sourcemap.addSourceContent(1, '/css/typography.css', null);
3984
+ *
3985
+ * const maps = [];
3986
+ *
3987
+ * maps.add([
3988
+ 1, 1, 0, 1, 1]);
3989
+ * maps.add([
3990
+ 2, 1, 1, 1, 1
3991
+ ]);
3992
+
3993
+ sourcemap.add(maps);
3994
+
3995
+ // convert to inline sourcemap
3996
+ sourcemap.toUrl();
3997
+
3998
+ // convert to JSON
3999
+ sourcemap.toJSON();
4000
+
4001
+ // find the original file, line and column
4002
+ sourcemap.find(2, 1);
4003
+ ```
3939
4004
  */
3940
4005
  declare class SourceMap {
3941
4006
  /**
@@ -3995,9 +4060,9 @@ declare class SourceMap {
3995
4060
  constructor(sourcemaps: string | SourceMapObject);
3996
4061
  /**
3997
4062
  * add source
3998
- * @param id
3999
- * @param fileName
4000
- * @param content
4063
+ * @param id source id
4064
+ * @param fileName source file
4065
+ * @param content source content
4001
4066
  * @returns
4002
4067
  */
4003
4068
  addSourceContent(id: number, fileName: string | null, content: string | null): void;
@@ -6247,7 +6312,7 @@ declare function expand(ast: AstStyleSheet | AstAtRule | AstRule): AstNode$1;
6247
6312
  * console.log(declarations);
6248
6313
  * ```
6249
6314
  */
6250
- declare function parseDeclarations(declaration: string): Promise<Array<AstDeclaration | AstComment>>;
6315
+ declare function parseDeclarations(declaration: string): Array<AstDeclaration | AstComment>;
6251
6316
  /**
6252
6317
  * Parse css string and return an array of tokens
6253
6318
  * @param src
@@ -6304,11 +6369,11 @@ declare function convertColor(token: ColorToken, to: ColorType$1): ColorToken |
6304
6369
 
6305
6370
  /**
6306
6371
  * Calculate the distance between two okLab colors.
6307
- * @param okLab1
6308
- * @param okLab2
6309
6372
  *
6310
6373
  * @private
6311
6374
  * {@link https://drafts.csswg.org/css-color-4/#comparing-color-values}
6375
+ * @param color1
6376
+ * @param color2
6312
6377
  */
6313
6378
  declare function okLabDistance(color1: ColorToken, color2: ColorToken): number | null;
6314
6379
  /**
@@ -6938,4 +7003,4 @@ declare function transform(options: ParseInputStreamOptions & TransformOptions):
6938
7003
  declare function transform(options: ParseInputFileOptions & TransformOptions): Promise<TransformResult>;
6939
7004
 
6940
7005
  export { ColorType$1 as ColorType, EnumAstNodeStatus$1 as EnumAstNodeStatus, EnumToken, FeatureWalkMode, ModuleCaseTransformEnum, ModuleScopeEnumOptions, ResponseType, SourceMap, ValidationLevel, WalkerEvent, WalkerOptionEnum, cloneNode, convertColor, dirname, expand, find, findAll, findByValue, findLast, getNodeProperty, isOkLabClose, load, minify, okLabDistance, parse, parseDeclarations, parseFile, parseString, parseSync, render, renderValue as renderToken, replaceNodeOrValue, resolve, setNodeProperty, transform, transformFile, transformSync, walk, walkValues };
6941
- export type { AddToken, AndToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstNodeStatus, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, 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, ContainerStyleRangeToken, CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, DoubleColonToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription$1 as ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorAstNodeSyncHandlerMap, GenericVisitorAsyncResult, GenericVisitorHandler, GenericVisitorResult, GenericVisitorSyncHandler, GenericVisitorSyncResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InvalidAttrToken, InvalidClassSelectorToken, InvalidMediaQueryToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleAsyncOptions, ModuleSyncOptions, MulToken, NameSpaceAttributeToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseInputFileOptions, ParseInputOptions, ParseInputStreamOptions, ParseResult, ParseResultStats, ParseSourceOptions, ParseTokenOptions, ParserOptions, ParserSourceMapOptions, ParserSyncOptions, PercentageToken, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SinglePropertyType, SinglePropertyTypeMapping, SourceLocation, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenSearchResult, TokenizeResult, TransformOptions, TransformResult, TransformSyncOptions, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, ValueVisitorSyncHandler, VariableScopeInfo, VisitorNodeMap, VisitorSyncNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerOptions, WalkerValueFilter, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken, WrappedValuesToken };
7006
+ export type { AddToken, AndToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstNodeStatus, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, 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, ContainerStyleRangeToken, CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, DoubleColonToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription$1 as ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorAstNodeSyncHandlerMap, GenericVisitorAsyncResult, GenericVisitorHandler, GenericVisitorResult, GenericVisitorSyncHandler, GenericVisitorSyncResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InfinityToken, InvalidAttrToken, InvalidClassSelectorToken, InvalidMediaQueryToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleAsyncOptions, ModuleSyncOptions, MulToken, NaNToken, NameSpaceAttributeToken, NegativeInfinityToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseInputFileOptions, ParseInputOptions, ParseInputStreamOptions, ParseResult, ParseResultStats, ParseSourceOptions, ParseTokenOptions, ParserOptions, ParserSourceMapOptions, ParserSyncOptions, PercentageToken, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SinglePropertyType, SinglePropertyTypeMapping, SourceLocation, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenSearchResult, TokenizeResult, TransformOptions, TransformResult, TransformSyncOptions, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, ValueVisitorSyncHandler, VariableScopeInfo, VisitorNodeMap, VisitorSyncNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerOptions, WalkerValueFilter, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken, WrappedValuesToken };
@@ -37,7 +37,6 @@ function replaceAstNodes(tokens, root) {
37
37
  token.val = pseudoAliasMap[token.val];
38
38
  if ((equalsIgnoreCase(token.val, "min-resolution") ||
39
39
  equalsIgnoreCase(token.val, "max-resolution")) &&
40
- // ["min-resolution", "max-resolution"].includes((token as IdentToken).val) &&
41
40
  value.r?.[0]?.typ == EnumToken.NumberTokenType) {
42
41
  Object.assign(value.r?.[0], {
43
42
  typ: EnumToken.ResolutionTokenType,
@@ -45,6 +44,14 @@ function replaceAstNodes(tokens, root) {
45
44
  });
46
45
  result = true;
47
46
  }
47
+ let isMin = token.val.startsWith("min-");
48
+ let isMax = token.val.startsWith("max-");
49
+ if (isMin || isMax) {
50
+ token.val = token.val.slice(4);
51
+ value.op.typ = isMax
52
+ ? EnumToken.LteTokenType
53
+ : EnumToken.GteTokenType;
54
+ }
48
55
  }
49
56
  }
50
57
  }
@@ -77,6 +84,7 @@ function replaceAstNodes(tokens, root) {
77
84
  }
78
85
  }
79
86
  }
87
+ // remove duplicate tokens
80
88
  if (tokens.find((t) => t.typ == EnumToken.CommaTokenType) != null) {
81
89
  const set = new Set();
82
90
  const split = splitTokenList(tokens, [EnumToken.CommaTokenType]);
@@ -21,7 +21,7 @@ class ComputeShorthandFeature {
21
21
  }
22
22
  }
23
23
  run(ast, options) {
24
- if (!("chi" in ast)) {
24
+ if (!("chi" in ast || ast.chi?.length == 0)) {
25
25
  return null;
26
26
  }
27
27
  // @ts-ignore
@@ -53,7 +53,7 @@ class TransformCssFeature {
53
53
  minified: null,
54
54
  };
55
55
  if (matrix == null || cumulative == null || minified == null) {
56
- node.val = children;
56
+ node.val = children.map((t) => t.typ == EnumToken.TransformFunctionTokenType ? minifyTransformFunctions(t) : t);
57
57
  continue;
58
58
  }
59
59
  let r = [filterValues(children)];
@@ -1,3 +1,4 @@
1
+ import { equalsIgnoreCase } from '../../parser/utils/text.js';
1
2
  import { mathFuncs, LOCEND, LOCSTA, LOCSRCID } from '../../syntax/constants.js';
2
3
  import { EnumToken } from '../types.js';
3
4
  import { rem, compute } from './math.js';
@@ -155,6 +156,35 @@ function doEvaluate(l, r, op) {
155
156
  if (!isScalarToken(l) || !isScalarToken(r) || (l.typ == r.typ && "unit" in l && "unit" in r && l.unit != r.unit)) {
156
157
  return defaultReturn;
157
158
  }
159
+ if (l.typ == EnumToken.IdenTokenType) {
160
+ if (equalsIgnoreCase(l.val, "Infinity")) {
161
+ Object.assign(l, { typ: EnumToken.InfinityTokenType });
162
+ }
163
+ else if (equalsIgnoreCase(l.val, "-Infinity")) {
164
+ Object.assign(l, { typ: EnumToken.NegativeInfinityTokenType });
165
+ }
166
+ else if (equalsIgnoreCase(l.val, "NaN")) {
167
+ Object.assign(l, { typ: EnumToken.NaNTokenType });
168
+ }
169
+ }
170
+ if (r.typ == EnumToken.IdenTokenType) {
171
+ if (equalsIgnoreCase(r.val, "Infinity")) {
172
+ Object.assign(r, { typ: EnumToken.InfinityTokenType });
173
+ }
174
+ else if (equalsIgnoreCase(r.val, "-Infinity")) {
175
+ Object.assign(r, { typ: EnumToken.NegativeInfinityTokenType });
176
+ }
177
+ }
178
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/calc-keyword#notes
179
+ if (l.typ == EnumToken.NaNTokenType || r.typ == EnumToken.NaNTokenType) {
180
+ return computeNaN(l, r, defaultReturn);
181
+ }
182
+ if (l.typ == EnumToken.InfinityTokenType ||
183
+ l.typ == EnumToken.NegativeInfinityTokenType ||
184
+ r.typ == EnumToken.InfinityTokenType ||
185
+ r.typ == EnumToken.NegativeInfinityTokenType) {
186
+ return computeInfinity(l, r, op, defaultReturn);
187
+ }
158
188
  if (r.typ == EnumToken.FunctionTokenType || r.typ == EnumToken.MathFunctionTokenType) {
159
189
  const val = evaluateFunc(r);
160
190
  if (val == null) {
@@ -225,6 +255,18 @@ function doEvaluate(l, r, op) {
225
255
  }
226
256
  }
227
257
  }
258
+ if (op == EnumToken.Div && v2 == 0) {
259
+ if (v1 == 0) {
260
+ return Object.assign(l, { typ: EnumToken.IdenTokenType, val: "NaN" });
261
+ }
262
+ let sign = Math.sign(v1) * Math.sign(v2);
263
+ sign = Object.is(sign, -0) ? -1 : 1;
264
+ Object.assign(l, {
265
+ typ: l.typ == EnumToken.IdenTokenType ? EnumToken.NumberTokenType : l.typ,
266
+ val: Object.is(sign, -0) ? -1 : sign,
267
+ });
268
+ return defaultReturn;
269
+ }
228
270
  // @ts-ignore
229
271
  const val = compute(v1, v2, op);
230
272
  const token = {
@@ -241,6 +283,112 @@ function doEvaluate(l, r, op) {
241
283
  }
242
284
  return token;
243
285
  }
286
+ /**
287
+ *
288
+ * @param l
289
+ * @param r
290
+ * @param defaultReturn
291
+ * @returns
292
+ */
293
+ function computeNaN(l, r, defaultReturn) {
294
+ if (l.typ == EnumToken.NaNTokenType) {
295
+ if (r.typ == EnumToken.NumberTokenType ||
296
+ // @ts-expect-error
297
+ (r.typ == EnumToken.IdenTokenType && typeof Math[r.val.toUpperCase()] == "string")) {
298
+ return l;
299
+ }
300
+ // NaN Infinity e pi ...
301
+ if (r.typ == EnumToken.IdenTokenType ||
302
+ r.typ == EnumToken.InfinityTokenType ||
303
+ r.typ == EnumToken.NegativeInfinityTokenType) {
304
+ return l;
305
+ }
306
+ if (typeof r.val == "number") {
307
+ Object.assign(r, { val: 1 });
308
+ }
309
+ return r.typ == EnumToken.NaNTokenType ? l : defaultReturn;
310
+ }
311
+ if (r.typ == EnumToken.NaNTokenType) {
312
+ // if ((r as IdentToken).val == "NaN") {
313
+ if (l.typ == EnumToken.NumberTokenType ||
314
+ // @ts-expect-error
315
+ (l.typ == EnumToken.IdenTokenType && typeof Math[l.val.toUpperCase()] == "string")) {
316
+ return r;
317
+ }
318
+ if (typeof l.val == "number") {
319
+ Object.assign(l, { val: 1 });
320
+ }
321
+ // return defaultReturn;
322
+ }
323
+ // }
324
+ return defaultReturn;
325
+ }
326
+ /**
327
+ *
328
+ * @param l
329
+ * @param r
330
+ * @param op
331
+ * @param defaultReturn
332
+ * @returns
333
+ */
334
+ function computeInfinity(l, r, op, defaultReturn) {
335
+ if (l.typ == EnumToken.InfinityTokenType || l.typ == EnumToken.NegativeInfinityTokenType) {
336
+ if (r.typ == EnumToken.InfinityTokenType || r.typ == EnumToken.NegativeInfinityTokenType) {
337
+ // Infinity / Infinity Infinity - Infinity
338
+ if (op == EnumToken.Div ||
339
+ (op == EnumToken.Add && l.typ != r.typ) ||
340
+ (op == EnumToken.Sub && l.typ == r.typ)) {
341
+ return Object.assign(l, { typ: EnumToken.NaNTokenType });
342
+ }
343
+ if (l.typ != r.typ) {
344
+ l.typ = EnumToken.NegativeInfinityTokenType;
345
+ }
346
+ return l;
347
+ }
348
+ const value = getValue(r);
349
+ const sign = Math.sign(value);
350
+ const isNumber = r.typ == EnumToken.NumberTokenType || r.typ == EnumToken.IdenTokenType;
351
+ // Infinity * 0
352
+ if (value == 0 && op == EnumToken.Mul) {
353
+ l.typ = EnumToken.NaNTokenType;
354
+ return isNumber ? l : defaultReturn;
355
+ }
356
+ if (isNumber) {
357
+ // @ts-ignore
358
+ r.val /= r.val * sign;
359
+ }
360
+ if (op == EnumToken.Div) {
361
+ return isNumber
362
+ ? Object.assign(r, { typ: EnumToken.NumberTokenType, val: sign < 0 ? -0 : 0 })
363
+ : defaultReturn;
364
+ }
365
+ if (sign == -1) {
366
+ l.typ =
367
+ l.typ == EnumToken.InfinityTokenType
368
+ ? EnumToken.NegativeInfinityTokenType
369
+ : EnumToken.InfinityTokenType;
370
+ }
371
+ return isNumber ? l : defaultReturn;
372
+ }
373
+ if (r.typ == EnumToken.InfinityTokenType || r.typ == EnumToken.NegativeInfinityTokenType) {
374
+ const value = getValue(l);
375
+ let sign = Math.sign(value);
376
+ const isNumber = l.typ == EnumToken.NumberTokenType || l.typ == EnumToken.IdenTokenType;
377
+ if (isNumber) {
378
+ Object.assign(l, { typ: EnumToken.NumberTokenType, val: sign });
379
+ }
380
+ if (value == 0 && op == EnumToken.Mul) {
381
+ return Object.assign(l, { typ: EnumToken.NaNTokenType });
382
+ }
383
+ if (op == EnumToken.Div) {
384
+ return isNumber
385
+ ? Object.assign(l, { typ: EnumToken.NumberTokenType, val: sign < 0 ? -0 : 0 })
386
+ : defaultReturn;
387
+ }
388
+ return l.typ == isNumber || value == 0 ? r : defaultReturn;
389
+ }
390
+ return defaultReturn;
391
+ }
244
392
  function getValue(t) {
245
393
  if (t.typ == EnumToken.IdenTokenType) {
246
394
  // @ts-ignore
@@ -293,7 +441,9 @@ function evaluateFunc(token) {
293
441
  }
294
442
  const value = evaluate(values);
295
443
  // @ts-ignore
296
- let val = value[0].typ == EnumToken.NumberTokenType || value[0].typ == EnumToken.AngleTokenType
444
+ let val = value[0].typ == EnumToken.NumberTokenType ||
445
+ value[0].typ == EnumToken.AngleTokenType ||
446
+ value[0].typ == EnumToken.PercentageTokenType
297
447
  ? +value[0].val
298
448
  : // @ts-expect-error
299
449
  value[0].l.val / value[0].r.val;
@@ -308,7 +458,7 @@ function evaluateFunc(token) {
308
458
  [LOCEND]: value[0][LOCEND],
309
459
  }
310
460
  : {
311
- typ: EnumToken.NumberTokenType,
461
+ typ: token.val == "sign" ? EnumToken.NumberTokenType : value[0].typ,
312
462
  val: Math[token.val](val),
313
463
  [LOCSRCID]: value[0][LOCSRCID],
314
464
  [LOCSTA]: value[0][LOCSTA],
@@ -338,10 +488,23 @@ function evaluateFunc(token) {
338
488
  },
339
489
  ];
340
490
  }
491
+ case "mod":
341
492
  case "atan2":
342
493
  case "pow":
343
- case "rem":
344
- case "mod": {
494
+ case "rem": {
495
+ {
496
+ let typ = token.chi[0]?.typ;
497
+ for (let i = 1; i < token.chi.length; i++) {
498
+ if (token.chi[i].typ == EnumToken.WhitespaceTokenType ||
499
+ token.chi[i].typ == EnumToken.CommaTokenType ||
500
+ token.chi[i].typ == EnumToken.CommentTokenType) {
501
+ continue;
502
+ }
503
+ if (token.chi[i].typ != typ) {
504
+ return null;
505
+ }
506
+ }
507
+ }
345
508
  const chi = values.filter((t) => ![EnumToken.WhitespaceTokenType, EnumToken.CommentTokenType].includes(t.typ));
346
509
  if (token.val == "atan2") {
347
510
  for (let i = 0; i < chi.length; i++) {
@@ -560,7 +723,14 @@ function isScalarToken(token) {
560
723
  (token.typ == EnumToken.FunctionTokenType && mathFuncs.includes(token.val)) ||
561
724
  // @ts-ignore
562
725
  (token.typ == EnumToken.IdenTokenType && typeof Math[token.val.toUpperCase()] == "number") ||
563
- [EnumToken.NumberTokenType, EnumToken.FractionTokenType, EnumToken.PercentageTokenType].includes(token.typ));
726
+ (token.typ == EnumToken.IdenTokenType && token.val == "NaN") ||
727
+ (token.typ == EnumToken.IdenTokenType &&
728
+ (equalsIgnoreCase(token.val, "Infinity") ||
729
+ equalsIgnoreCase(token.val, "-Infinity"))) ||
730
+ [EnumToken.NumberTokenType, EnumToken.FractionTokenType, EnumToken.PercentageTokenType].includes(token.typ) ||
731
+ token.typ == EnumToken.NaNTokenType ||
732
+ token.typ == EnumToken.InfinityTokenType ||
733
+ token.typ == EnumToken.NegativeInfinityTokenType);
564
734
  }
565
735
  /**
566
736
  *
@@ -307,7 +307,15 @@ function reduce(acc, curr) {
307
307
  // trim :is()
308
308
  if (curr[0] == "&") {
309
309
  if (curr[1] == " " && !isIdent(curr[2]) && !isFunction(curr[2])) {
310
- curr.splice(0, 2);
310
+ const all = new Array(Math.max(curr.length - 2, 0));
311
+ let write = 0;
312
+ for (let read = 2; read < curr.length; read++) {
313
+ all[write++] = curr[read];
314
+ }
315
+ curr.length = 0;
316
+ for (let index = 0; index < write; index++) {
317
+ curr[index] = all[index];
318
+ }
311
319
  }
312
320
  }
313
321
  acc.push(curr.join(""));
@@ -585,19 +593,40 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
585
593
  if (optimized.length > 1) {
586
594
  const check = optimized.at(-2);
587
595
  if (!combinators.includes(check)) {
588
- let last = optimized.pop();
596
+ const last = optimized[optimized.length - 1];
597
+ const all = new Array(Math.max(optimized.length - 1, 0));
598
+ let write = 0;
599
+ for (let read = 0; read < optimized.length - 1; read++) {
600
+ all[write++] = optimized[read];
601
+ }
602
+ optimized.length = 0;
603
+ for (let index = 0; index < write; index++) {
604
+ optimized[index] = all[index];
605
+ }
589
606
  wrap = false;
590
607
  rule =
591
608
  optimized.join("") +
592
609
  `:is(${selector
593
610
  .map((s) => {
611
+ const next = s[0] == "&" ? new Array(s.length) : new Array(s.length + 1);
612
+ let write = 0;
594
613
  if (s[0] == "&") {
595
- s.splice(0, 1, last);
614
+ next[write++] = last;
615
+ for (let read = 1; read < s.length; read++) {
616
+ next[write++] = s[read];
617
+ }
596
618
  }
597
619
  else {
598
- s.unshift(last);
620
+ next[write++] = last;
621
+ for (let read = 0; read < s.length; read++) {
622
+ next[write++] = s[read];
623
+ }
599
624
  }
600
- return s.join("");
625
+ const rebuilt = new Array(write);
626
+ for (let index = 0; index < write; index++) {
627
+ rebuilt[index] = next[index];
628
+ }
629
+ return rebuilt.join("");
601
630
  })
602
631
  .join(",")})`;
603
632
  }
@@ -606,7 +635,20 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
606
635
  rule = selector
607
636
  .map((s) => {
608
637
  if (s[0] == "&") {
609
- s.splice(0, 1, ...node[OPTIMIZED].optimized);
638
+ const replacement = node[OPTIMIZED].optimized;
639
+ const all = new Array(Math.max(s.length - 1 + replacement.length, 0));
640
+ let write = 0;
641
+ for (let read = 0; read < replacement.length; read++) {
642
+ all[write++] = replacement[read];
643
+ }
644
+ for (let read = 1; read < s.length; read++) {
645
+ all[write++] = s[read];
646
+ }
647
+ const rebuilt = new Array(write);
648
+ for (let index = 0; index < write; index++) {
649
+ rebuilt[index] = all[index];
650
+ }
651
+ return rebuilt.join("");
610
652
  }
611
653
  return s.join("");
612
654
  })
@@ -838,18 +880,42 @@ function optimizeSelector(selector) {
838
880
  while (optimized.length > 0) {
839
881
  const last = optimized.at(-1);
840
882
  if (last == " " || combinators.includes(last)) {
841
- optimized.pop();
883
+ const all = new Array(Math.max(optimized.length - 1, 0));
884
+ let write = 0;
885
+ for (let read = 0; read < optimized.length - 1; read++) {
886
+ all[write++] = optimized[read];
887
+ }
888
+ optimized.length = 0;
889
+ for (let index = 0; index < write; index++) {
890
+ optimized[index] = all[index];
891
+ }
842
892
  continue;
843
893
  }
844
894
  break;
845
895
  }
846
896
  for (let i1 = 0; i1 < selector.length; i1++) {
847
- selector[i1].splice(0, optimized.length);
897
+ const all = new Array(Math.max(selector[i1].length - optimized.length, 0));
898
+ let write = 0;
899
+ for (let read = optimized.length; read < selector[i1].length; read++) {
900
+ all[write++] = selector[i1][read];
901
+ }
902
+ selector[i1].length = 0;
903
+ for (let index = 0; index < write; index++) {
904
+ selector[i1][index] = all[index];
905
+ }
848
906
  }
849
907
  let reducible = optimized.length == 1;
850
908
  if (optimized[0] == "&") {
851
909
  if (optimized[1] == " ") {
852
- optimized.splice(0, 2);
910
+ const all = new Array(Math.max(optimized.length - 2, 0));
911
+ let write = 0;
912
+ for (let read = 2; read < optimized.length; read++) {
913
+ all[write++] = optimized[read];
914
+ }
915
+ optimized.length = 0;
916
+ for (let index = 0; index < write; index++) {
917
+ optimized[index] = all[index];
918
+ }
853
919
  }
854
920
  }
855
921
  if (optimized.length == 0 || optimized[0].charAt(0) == "&" || selector.length == 1) {
@@ -1436,7 +1502,15 @@ function reduceRuleSelector(node) {
1436
1502
  if (selector.length > 1 &&
1437
1503
  selector[0] == "&" &&
1438
1504
  (combinators.includes(selector[1]) || !/^[a-zA-Z:]/.test(selector[1]))) {
1439
- selector.shift();
1505
+ const all = new Array(Math.max(selector.length - 1, 0));
1506
+ let write = 0;
1507
+ for (let read = 1; read < selector.length; read++) {
1508
+ all[write++] = selector[read];
1509
+ }
1510
+ selector.length = 0;
1511
+ for (let index = 0; index < write; index++) {
1512
+ selector[index] = all[index];
1513
+ }
1440
1514
  }
1441
1515
  }
1442
1516
  const unique = new Set();
@@ -2,7 +2,7 @@ import { identity, multiply, toZero } from './utils.js';
2
2
  import { EnumToken } from '../types.js';
3
3
  import { stripCommaToken } from '../../validation/utils/list.js';
4
4
  import { translateX, translateY, translateZ, translate, translate3d } from './translate.js';
5
- import { getNumber, getAngle } from '../../syntax/color/color.js';
5
+ import { getAngle, getNumber } from '../../syntax/color/color.js';
6
6
  import { rotate, rotate3D } from './rotate.js';
7
7
  import { scale3d, scale, scaleX, scaleY, scaleZ } from './scale.js';
8
8
  import { minify } from './minify.js';
@@ -19,6 +19,29 @@ function compute(transformLists) {
19
19
  let mat;
20
20
  let transforms;
21
21
  const cumulative = [];
22
+ // all transform function arguments must be 0 or scale(1)
23
+ for (const transform of transformLists) {
24
+ switch (transform.val) {
25
+ case "rotate":
26
+ case "rotateX":
27
+ case "rotateY":
28
+ case "rotateZ":
29
+ case "rotate3d":
30
+ for (const child of transform.chi) {
31
+ if (child.typ == EnumToken.WhitespaceTokenType || child.typ == EnumToken.CommaTokenType) {
32
+ continue;
33
+ }
34
+ if ((child.typ != EnumToken.AngleTokenType &&
35
+ child.typ != EnumToken.NumberTokenType &&
36
+ child.typ != EnumToken.PercentageTokenType) ||
37
+ // angle >= 360deg, do not transform
38
+ Math.abs(getAngle(child)) >= 1) {
39
+ return null;
40
+ }
41
+ }
42
+ // break;
43
+ }
44
+ }
22
45
  for (const transformList of splitTransformList(transformLists)) {
23
46
  mat = computeMatrix(transformList, identity());
24
47
  if (mat == null) {
@@ -49,60 +72,6 @@ function compute(transformLists) {
49
72
  cumulative,
50
73
  minified: minify(matrix) ?? [serialized],
51
74
  };
52
- // valid identity matrix
53
- if ((result.minified.length == 1 &&
54
- result.minified[0].typ == EnumToken.IdenTokenType &&
55
- result.minified[0].val == "none") ||
56
- (result.cumulative.length == 1 &&
57
- result.cumulative[0].typ == EnumToken.IdenTokenType &&
58
- result.cumulative[0].val == "none") ||
59
- (result.matrix?.typ == EnumToken.IdenTokenType && result.matrix.val == "none")) {
60
- // all transform function arguments must be 0 or scale(1)
61
- for (const transform of transformLists) {
62
- switch (transform.val) {
63
- case "translate":
64
- case "translateX":
65
- case "translateY":
66
- case "translateZ":
67
- case "translate3d":
68
- case "rotate":
69
- case "rotateX":
70
- case "rotateY":
71
- case "rotateZ":
72
- case "rotate3d":
73
- case "skew":
74
- case "skewX":
75
- case "skewY":
76
- for (const child of transform.chi) {
77
- if (child.typ == EnumToken.WhitespaceTokenType || child.typ == EnumToken.CommaTokenType) {
78
- continue;
79
- }
80
- if ((child.typ != EnumToken.AngleTokenType &&
81
- child.typ != EnumToken.NumberTokenType &&
82
- child.typ != EnumToken.PercentageTokenType) ||
83
- getNumber(child) != 0) {
84
- return null;
85
- }
86
- }
87
- break;
88
- case "scale":
89
- case "scaleX":
90
- case "scaleY":
91
- case "scaleZ":
92
- case "scale3d":
93
- for (const child of transform.chi) {
94
- if (child.typ == EnumToken.WhitespaceTokenType || child.typ == EnumToken.CommaTokenType) {
95
- continue;
96
- }
97
- if ((child.typ != EnumToken.NumberTokenType && child.typ != EnumToken.PercentageTokenType) ||
98
- getNumber(child) != 1) {
99
- return null;
100
- }
101
- }
102
- break;
103
- }
104
- }
105
- }
106
75
  return result;
107
76
  }
108
77
  function computeMatrix(transformList, matrixVar) {