@navita/engine 0.0.10 → 0.0.11

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 (58) hide show
  1. package/cache.cjs +27 -0
  2. package/cache.mjs +25 -0
  3. package/helpers/declarationsToBlock.cjs +17 -0
  4. package/helpers/declarationsToBlock.mjs +15 -0
  5. package/helpers/generateCombinedAtRules.cjs +10 -0
  6. package/helpers/generateCombinedAtRules.mjs +8 -0
  7. package/helpers/getPropertyPriority.cjs +262 -0
  8. package/helpers/getPropertyPriority.mjs +260 -0
  9. package/helpers/hypenateProperty.cjs +11 -0
  10. package/helpers/hypenateProperty.mjs +9 -0
  11. package/helpers/isMediaQuery.cjs +7 -0
  12. package/helpers/isMediaQuery.mjs +5 -0
  13. package/helpers/isNestedSelector.cjs +8 -0
  14. package/helpers/isNestedSelector.mjs +6 -0
  15. package/helpers/isObject.cjs +7 -0
  16. package/helpers/isObject.mjs +5 -0
  17. package/helpers/isSupportsQuery.cjs +7 -0
  18. package/helpers/isSupportsQuery.mjs +5 -0
  19. package/helpers/normalizeCSSVarsProperty.cjs +15 -0
  20. package/helpers/normalizeCSSVarsProperty.mjs +13 -0
  21. package/helpers/normalizeNestedProperty.cjs +10 -0
  22. package/helpers/normalizeNestedProperty.mjs +8 -0
  23. package/helpers/pixelifyProperties.cjs +58 -0
  24. package/helpers/pixelifyProperties.mjs +56 -0
  25. package/helpers/splitStyleBlocks.cjs +19 -0
  26. package/helpers/splitStyleBlocks.mjs +17 -0
  27. package/helpers/transformContentProperty.cjs +8 -0
  28. package/helpers/transformContentProperty.mjs +6 -0
  29. package/identifiers/IDGenerator.cjs +10 -0
  30. package/identifiers/IDGenerator.mjs +8 -0
  31. package/identifiers/alphaIDGenerator.cjs +27 -0
  32. package/identifiers/alphaIDGenerator.mjs +25 -0
  33. package/identifiers/propertyValueIDGenerator.cjs +24 -0
  34. package/identifiers/propertyValueIDGenerator.mjs +22 -0
  35. package/index.cjs +226 -0
  36. package/index.mjs +27 -677
  37. package/package.json +2 -2
  38. package/printers/printFontFaces.cjs +16 -0
  39. package/printers/printFontFaces.mjs +14 -0
  40. package/printers/printKeyFrames.cjs +22 -0
  41. package/printers/printKeyFrames.mjs +20 -0
  42. package/printers/printSourceMap.cjs +42 -0
  43. package/printers/printSourceMap.mjs +40 -0
  44. package/printers/printStyleBlocks.cjs +60 -0
  45. package/printers/printStyleBlocks.mjs +58 -0
  46. package/printers/sortAtRules.cjs +10 -0
  47. package/printers/sortAtRules.mjs +8 -0
  48. package/printers/sortStatic.cjs +7 -0
  49. package/printers/sortStatic.mjs +5 -0
  50. package/processStyles.cjs +88 -0
  51. package/processStyles.mjs +86 -0
  52. package/types.cjs +2 -0
  53. package/types.mjs +1 -0
  54. package/wrappers/classList.cjs +6 -0
  55. package/wrappers/classList.mjs +4 -0
  56. package/wrappers/static.cjs +6 -0
  57. package/wrappers/static.mjs +4 -0
  58. package/index.js +0 -876
package/index.js DELETED
@@ -1,876 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('node:path');
4
- var hash = require('@emotion/hash');
5
- var sourceMap = require('source-map');
6
- var createSort = require('sort-css-media-queries/lib/create-sort.js');
7
-
8
- class Cache {
9
- constructor(_idGenerator){
10
- this._idGenerator = _idGenerator;
11
- this._items = {};
12
- }
13
- getOrStore(value) {
14
- const cacheKey = JSON.stringify(value);
15
- if (this._items[cacheKey]) {
16
- return this._items[cacheKey];
17
- }
18
- return this._items[cacheKey] = {
19
- id: this._idGenerator.next(value),
20
- ...value
21
- };
22
- }
23
- items(ids = undefined) {
24
- const items = Object.values(this._items);
25
- if (ids === undefined) {
26
- return items;
27
- }
28
- return items.filter((item)=>ids.includes(item.id));
29
- }
30
- }
31
-
32
- function isObject(val) {
33
- return val != null && typeof val === 'object' && Array.isArray(val) === false;
34
- }
35
-
36
- function splitStyleBlocks(blocks) {
37
- const atRules = [];
38
- const rules = [];
39
- for (const block of blocks){
40
- if (block.media || block.support) {
41
- atRules.push(block);
42
- } else {
43
- rules.push(block);
44
- }
45
- }
46
- return {
47
- atRules,
48
- rules
49
- };
50
- }
51
-
52
- class IDGenerator {
53
- counter = 1;
54
- next() {
55
- return this.counter++;
56
- }
57
- }
58
-
59
- const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
60
- const charLength = chars.length;
61
- class AlphaIDGenerator {
62
- constructor(blacklist = [
63
- 'ad'
64
- ]){
65
- this.blacklist = blacklist;
66
- this.counter = 1;
67
- }
68
- next() {
69
- const nextString = (id, className = '')=>{
70
- if (id <= charLength) {
71
- return chars[id - 1] + className;
72
- }
73
- return nextString(id / charLength | 0, chars[(id - 1) % charLength] + className);
74
- };
75
- let className;
76
- do {
77
- className = nextString(this.counter++);
78
- }while (this.blacklist.includes(className.toLowerCase()))
79
- return className;
80
- }
81
- }
82
-
83
- class PropertyValueIDGenerator {
84
- property = new AlphaIDGenerator();
85
- cache = {};
86
- next({ property , media ='' , support ='' , pseudo ='' , value }) {
87
- const propertyKey = `${media}${support}${pseudo}${property}`;
88
- if (this.cache[propertyKey] === undefined) {
89
- this.cache[propertyKey] = {
90
- key: this.property.next(),
91
- cache: {}
92
- };
93
- }
94
- const entry = this.cache[propertyKey];
95
- if (entry.cache[value] === undefined) {
96
- entry.cache[value] = Object.keys(entry.cache).length + 1;
97
- }
98
- return `${entry.key}${entry.cache[value]}`;
99
- }
100
- }
101
-
102
- // https://github.com/styletron/styletron/blob/b552ddc5050a8cc5eec84a46a299d937d3bb0112/packages/styletron-engine-atomic/src/hyphenate-style-name.ts
103
- const uppercasePattern = /[A-Z]/g;
104
- const msPattern = /^ms-/;
105
- const cache = {};
106
- function hyphenateProperty(property) {
107
- return property in cache ? cache[property] : cache[property] = property.replace(uppercasePattern, "-$&").toLowerCase().replace(msPattern, "-ms-");
108
- }
109
-
110
- // https://github.com/styletron/styletron/blob/b552ddc5050a8cc5eec84a46a299d937d3bb0112/packages/styletron-engine-atomic/src/css.ts#L36
111
- function declarationsToBlock(style) {
112
- let css = "";
113
- for(const prop in style){
114
- const val = style[prop];
115
- if (typeof val === "string" || typeof val === "number") {
116
- css += `${hyphenateProperty(prop)}:${val};`;
117
- }
118
- }
119
- return css.slice(0, -1);
120
- }
121
-
122
- function printFontFaces(blocks) {
123
- let fontFaces = '';
124
- for (const block of blocks){
125
- for (const rule of block.rule){
126
- fontFaces += `@font-face{font-family:${block.id};${declarationsToBlock(rule)}}`;
127
- }
128
- }
129
- return fontFaces;
130
- }
131
-
132
- // https://github.com/styletron/styletron/blob/master/packages/styletron-engine-atomic/src/css.ts#L48
133
- function keyframesToBlock(keyframes) {
134
- let result = "";
135
- for(const animationState in keyframes){
136
- result += `${animationState}{${declarationsToBlock(keyframes[animationState])}}`;
137
- }
138
- return result;
139
- }
140
- function printKeyFrames(blocks) {
141
- let keyframes = '';
142
- for (const block of blocks){
143
- keyframes += `@keyframes ${block.id}{${keyframesToBlock(block.rule)}}`;
144
- }
145
- return keyframes;
146
- }
147
-
148
- function printSourceMap(sourceMapReferences, content) {
149
- if (content.length === 0) {
150
- return content;
151
- }
152
- const entries = Object.entries(sourceMapReferences);
153
- if (entries.length === 0) {
154
- return content;
155
- }
156
- const sourceMap$1 = new sourceMap.SourceMapGenerator({
157
- file: "navita.css",
158
- skipValidation: true
159
- });
160
- const references = entries.flatMap(([filePath, references])=>references.map((reference)=>({
161
- filePath,
162
- ...reference
163
- })));
164
- for (const reference of references){
165
- const { filePath , selector , line , column } = reference;
166
- const generatedColumn = content.length - 1;
167
- content += `${selector}{/* Only used for sourceMap */}`;
168
- sourceMap$1.addMapping({
169
- source: filePath,
170
- original: {
171
- line,
172
- column
173
- },
174
- generated: {
175
- line: 1,
176
- column: generatedColumn
177
- }
178
- });
179
- }
180
- const sourceMapContent = Buffer.from(sourceMap$1.toString()).toString('base64');
181
- content += `\n/*# sourceMappingURL=data:application/json;base64,${sourceMapContent} */`;
182
- return content;
183
- }
184
-
185
- /**
186
- * This list comes from:
187
- * https://github.com/callstack/linaria/blob/master/packages/atomic/src/processors/helpers/propertyPriority.ts
188
- */ const shorthandProperties = {
189
- // The `all` property resets everything, and should effectively have priority zero.
190
- // In practice, this can be achieved by using: div { all: ... } to have even less specificity, but to avoid duplicating all selectors, we just let it be
191
- // 'all': []
192
- animation: [
193
- 'animation-name',
194
- 'animation-duration',
195
- 'animation-timing-function',
196
- 'animation-delay',
197
- 'animation-iteration-count',
198
- 'animation-direction',
199
- 'animation-fill-mode',
200
- 'animation-play-state'
201
- ],
202
- background: [
203
- 'background-attachment',
204
- 'background-clip',
205
- 'background-color',
206
- 'background-image',
207
- 'background-origin',
208
- 'background-position',
209
- 'background-repeat',
210
- 'background-size'
211
- ],
212
- border: [
213
- 'border-color',
214
- 'border-style',
215
- 'border-width'
216
- ],
217
- 'border-block-end': [
218
- 'border-block-end-color',
219
- 'border-block-end-style',
220
- 'border-block-end-width'
221
- ],
222
- 'border-block-start': [
223
- 'border-block-start-color',
224
- 'border-block-start-style',
225
- 'border-block-start-width'
226
- ],
227
- 'border-bottom': [
228
- 'border-bottom-color',
229
- 'border-bottom-style',
230
- 'border-bottom-width'
231
- ],
232
- 'border-color': [
233
- 'border-bottom-color',
234
- 'border-left-color',
235
- 'border-right-color',
236
- 'border-top-color'
237
- ],
238
- 'border-image': [
239
- 'border-image-outset',
240
- 'border-image-repeat',
241
- 'border-image-slice',
242
- 'border-image-source',
243
- 'border-image-width'
244
- ],
245
- 'border-inline-end': [
246
- 'border-inline-end-color',
247
- 'border-inline-end-style',
248
- 'border-inline-end-width'
249
- ],
250
- 'border-inline-start': [
251
- 'border-inline-start-color',
252
- 'border-inline-start-style',
253
- 'border-inline-start-width'
254
- ],
255
- 'border-left': [
256
- 'border-left-color',
257
- 'border-left-style',
258
- 'border-left-width'
259
- ],
260
- 'border-radius': [
261
- 'border-top-left-radius',
262
- 'border-top-right-radius',
263
- 'border-bottom-right-radius',
264
- 'border-bottom-left-radius'
265
- ],
266
- 'border-right': [
267
- 'border-right-color',
268
- 'border-right-style',
269
- 'border-right-width'
270
- ],
271
- 'border-style': [
272
- 'border-bottom-style',
273
- 'border-left-style',
274
- 'border-right-style',
275
- 'border-top-style'
276
- ],
277
- 'border-top': [
278
- 'border-top-color',
279
- 'border-top-style',
280
- 'border-top-width'
281
- ],
282
- 'border-width': [
283
- 'border-bottom-width',
284
- 'border-left-width',
285
- 'border-right-width',
286
- 'border-top-width'
287
- ],
288
- 'column-rule': [
289
- 'column-rule-width',
290
- 'column-rule-style',
291
- 'column-rule-color'
292
- ],
293
- columns: [
294
- 'column-count',
295
- 'column-width'
296
- ],
297
- flex: [
298
- 'flex-grow',
299
- 'flex-shrink',
300
- 'flex-basis'
301
- ],
302
- 'flex-flow': [
303
- 'flex-direction',
304
- 'flex-wrap'
305
- ],
306
- font: [
307
- 'font-family',
308
- 'font-size',
309
- 'font-stretch',
310
- 'font-style',
311
- 'font-variant',
312
- 'font-weight',
313
- 'line-height'
314
- ],
315
- gap: [
316
- 'row-gap',
317
- 'column-gap'
318
- ],
319
- grid: [
320
- 'grid-auto-columns',
321
- 'grid-auto-flow',
322
- 'grid-auto-rows',
323
- 'grid-template-areas',
324
- 'grid-template-columns',
325
- 'grid-template-rows'
326
- ],
327
- 'grid-area': [
328
- 'grid-row-start',
329
- 'grid-column-start',
330
- 'grid-row-end',
331
- 'grid-column-end'
332
- ],
333
- 'grid-column': [
334
- 'grid-column-end',
335
- 'grid-column-start'
336
- ],
337
- 'grid-row': [
338
- 'grid-row-end',
339
- 'grid-row-start'
340
- ],
341
- 'grid-template': [
342
- 'grid-template-areas',
343
- 'grid-template-columns',
344
- 'grid-template-rows'
345
- ],
346
- 'list-style': [
347
- 'list-style-image',
348
- 'list-style-position',
349
- 'list-style-type'
350
- ],
351
- margin: [
352
- 'margin-bottom',
353
- 'margin-left',
354
- 'margin-right',
355
- 'margin-top'
356
- ],
357
- mask: [
358
- 'mask-clip',
359
- 'mask-composite',
360
- 'mask-image',
361
- 'mask-mode',
362
- 'mask-origin',
363
- 'mask-position',
364
- 'mask-repeat',
365
- 'mask-size'
366
- ],
367
- offset: [
368
- 'offset-anchor',
369
- 'offset-distance',
370
- 'offset-path',
371
- 'offset-position',
372
- 'offset-rotate'
373
- ],
374
- outline: [
375
- 'outline-color',
376
- 'outline-style',
377
- 'outline-width'
378
- ],
379
- overflow: [
380
- 'overflow-x',
381
- 'overflow-y'
382
- ],
383
- padding: [
384
- 'padding-bottom',
385
- 'padding-left',
386
- 'padding-right',
387
- 'padding-top'
388
- ],
389
- 'place-content': [
390
- 'align-content',
391
- 'justify-content'
392
- ],
393
- 'place-items': [
394
- 'align-items',
395
- 'justify-items'
396
- ],
397
- 'place-self': [
398
- 'align-self',
399
- 'justify-self'
400
- ],
401
- 'scroll-margin': [
402
- 'scroll-margin-bottom',
403
- 'scroll-margin-left',
404
- 'scroll-margin-right',
405
- 'scroll-margin-top'
406
- ],
407
- 'scroll-padding': [
408
- 'scroll-padding-bottom',
409
- 'scroll-padding-left',
410
- 'scroll-padding-right',
411
- 'scroll-padding-top'
412
- ],
413
- 'text-decoration': [
414
- 'text-decoration-color',
415
- 'text-decoration-line',
416
- 'text-decoration-style',
417
- 'text-decoration-thickness'
418
- ],
419
- 'text-emphasis': [
420
- 'text-emphasis-color',
421
- 'text-emphasis-style'
422
- ],
423
- transition: [
424
- 'transition-delay',
425
- 'transition-duration',
426
- 'transition-property',
427
- 'transition-timing-function'
428
- ]
429
- };
430
- const longhands = Object.values(shorthandProperties).reduce((a, b)=>[
431
- ...a,
432
- ...b
433
- ], []);
434
- /**
435
- * The concept here is that shorthand properties, such as "border" gets
436
- * a priority of one, while longhand properties, such as "border-color" gets
437
- * a priority of 2.
438
- *
439
- * Read more:
440
- * @see https://weser.io/blog/the-shorthand-longhand-problem-in-atomic-css
441
- * @see https://www.w3.org/TR/selectors-3/#specificity
442
- */ const getPropertyPriority = (property)=>longhands.includes(property) ? 2 : 1;
443
-
444
- function printStyleBlocks(blocks) {
445
- let stylesheet = '';
446
- let previousStyle;
447
- for (const style of blocks){
448
- if (style.type === 'static' && previousStyle && (previousStyle.selector !== style.selector || previousStyle.pseudo !== style.pseudo || previousStyle.media !== style.media || previousStyle.support !== style.support)) {
449
- stylesheet += '}';
450
- }
451
- // Close support queries:
452
- // 1. When the current style is not a support query, and the previous style was support query
453
- // 2. When the current style is a support query and the previous style was a support query with a different support query
454
- if (previousStyle && previousStyle.support && (!style.support || style.support !== previousStyle.support)) {
455
- stylesheet += '}';
456
- }
457
- // Close media queries:
458
- // 1. When the current style is not a media query, and the previous style was media query
459
- // 2. When the current style is a media query and the previous style was a media query with a different media query
460
- if (previousStyle && previousStyle.media && (!style.media || style.media !== previousStyle.media)) {
461
- stylesheet += '}';
462
- }
463
- // Only add media queries if the previous style was not the same media query
464
- if (style.media && previousStyle?.media !== style.media) {
465
- stylesheet += `@media ${style.media}{`;
466
- }
467
- // Only add support queries if the previous style was not the same support query
468
- if (style.support && previousStyle?.support !== style.support) {
469
- stylesheet += `@supports ${style.support}{`;
470
- }
471
- if (style.type === 'rule') {
472
- const className = `.${style.id}`.repeat(getPropertyPriority(style.property));
473
- stylesheet += `${className}${style.pseudo}{`;
474
- } else if (style.type === 'static' && (previousStyle?.selector !== style.selector || previousStyle?.pseudo !== style.pseudo || previousStyle?.media !== style.media || previousStyle?.support !== style.support)) {
475
- // If static, we don't add pseudo selectors currently
476
- stylesheet += `${style.selector}${style.pseudo}{`;
477
- }
478
- stylesheet += `${style.property}:${style.value}`;
479
- if (style.type === 'static') {
480
- stylesheet += ';';
481
- }
482
- if (style.type === 'rule') {
483
- stylesheet += '}';
484
- }
485
- previousStyle = style;
486
- }
487
- if (previousStyle?.support) {
488
- stylesheet += '}';
489
- }
490
- if (previousStyle?.media) {
491
- stylesheet += '}';
492
- }
493
- if (previousStyle?.type === 'static') {
494
- stylesheet += '}';
495
- }
496
- return stylesheet;
497
- }
498
-
499
- const sortCSSMediaQueries = createSort();
500
- function sortAtRules(blocks) {
501
- return blocks.sort((a, b)=>sortCSSMediaQueries(a.media, b.media) || a.support.localeCompare(b.support));
502
- }
503
-
504
- function generateCombinedAtRules(currentMediaQuery, nestedMediaQuery) {
505
- if (currentMediaQuery.length === 0) {
506
- return nestedMediaQuery;
507
- }
508
- return `${currentMediaQuery} and ${nestedMediaQuery}`;
509
- }
510
-
511
- function isMediaQuery(property) {
512
- return property.startsWith('@media');
513
- }
514
-
515
- const regex$1 = /^([:\[>&])/;
516
- function isNestedSelector(property) {
517
- return regex$1.test(property);
518
- }
519
-
520
- function isSupportsQuery(property) {
521
- return property.startsWith("@supports");
522
- }
523
-
524
- const regex = /var\(([^,]+).*\)/;
525
- function normalizeCSSVarsProperty(property) {
526
- if (!property.startsWith('var(')) {
527
- return property;
528
- }
529
- const matches = property.match(regex);
530
- if (!matches) {
531
- return property;
532
- }
533
- return matches[1];
534
- }
535
-
536
- function normalizeNestedProperty(nestedProperty) {
537
- if (nestedProperty.charAt(0) === '&') {
538
- return nestedProperty.slice(1);
539
- }
540
- return nestedProperty;
541
- }
542
-
543
- const UNITLESS = {
544
- animationIterationCount: true,
545
- borderImage: true,
546
- borderImageOutset: true,
547
- borderImageSlice: true,
548
- borderImageWidth: true,
549
- boxFlex: true,
550
- boxFlexGroup: true,
551
- columnCount: true,
552
- columns: true,
553
- flex: true,
554
- flexGrow: true,
555
- flexShrink: true,
556
- fontWeight: true,
557
- gridArea: true,
558
- gridColumn: true,
559
- gridColumnEnd: true,
560
- gridColumnStart: true,
561
- gridRow: true,
562
- gridRowEnd: true,
563
- gridRowStart: true,
564
- initialLetter: true,
565
- lineClamp: true,
566
- lineHeight: true,
567
- maxLines: true,
568
- opacity: true,
569
- order: true,
570
- orphans: true,
571
- scale: true,
572
- tabSize: true,
573
- WebkitLineClamp: true,
574
- widows: true,
575
- zIndex: true,
576
- zoom: true,
577
- // svg properties
578
- fillOpacity: true,
579
- floodOpacity: true,
580
- maskBorder: true,
581
- maskBorderOutset: true,
582
- maskBorderSlice: true,
583
- maskBorderWidth: true,
584
- shapeImageThreshold: true,
585
- stopOpacity: true,
586
- strokeDashoffset: true,
587
- strokeMiterlimit: true,
588
- strokeOpacity: true,
589
- strokeWidth: true
590
- };
591
- function pixelifyProperties(property, value) {
592
- if (value !== 0 && !UNITLESS[property]) {
593
- return `${value}px`;
594
- }
595
- return value;
596
- }
597
-
598
- // https://github.com/vanilla-extract-css/vanilla-extract/blob/40d7e72c041989a4dc847dc66b94a4c680b5536e/packages/css/src/transformCss.ts#L277
599
- function transformContentProperty(value) {
600
- return value && (value.includes('"') || value.includes("'") || /^([A-Za-z\-]+\([^]*|[^]*-quote|inherit|initial|none|normal|revert|unset)(\s|$)/.test(value)) ? value : `"${value}"`;
601
- }
602
-
603
- const transformValuePropertyMap = {
604
- content: transformContentProperty
605
- };
606
- function processStyles({ cache , type }) {
607
- return function process({ styles , pseudo ="" , media ="" , support ="" , selector ="" }) {
608
- const result = [];
609
- for (const [property, value] of Object.entries(styles)){
610
- if (isObject(value)) {
611
- if (isMediaQuery(property)) {
612
- const combinedMedia = generateCombinedAtRules(media, property.slice(6).trim());
613
- result.push(...process({
614
- styles: value,
615
- pseudo,
616
- media: combinedMedia,
617
- support,
618
- selector
619
- }));
620
- } else if (isSupportsQuery(property)) {
621
- const combinedSupport = generateCombinedAtRules(support, property.slice(9).trim());
622
- result.push(...process({
623
- styles: value,
624
- pseudo,
625
- media,
626
- support: combinedSupport,
627
- selector
628
- }));
629
- } else if (isNestedSelector(property)) {
630
- // This is only allowed in simple pseudos currently.
631
- const copies = property.split(',').map((p)=>p.trim());
632
- for (const copy of copies){
633
- result.push(...process({
634
- styles: value,
635
- pseudo: pseudo + normalizeNestedProperty(copy),
636
- media,
637
- support,
638
- selector
639
- }));
640
- }
641
- } else {
642
- console.warn("Unknown property", property);
643
- }
644
- } else {
645
- let newProperty = normalizeCSSVarsProperty(property);
646
- let newValue = value;
647
- if (typeof value === "string") {
648
- newValue = value.trim().replace(/;[\n\s]*$/, "");
649
- }
650
- // Check if value starts with --, if so, wrap in var()
651
- if (typeof newValue === "string" && newValue.startsWith("--")) {
652
- newValue = `var(${value})`;
653
- }
654
- if (typeof value === "number") {
655
- newValue = pixelifyProperties(newProperty, value);
656
- }
657
- if (transformValuePropertyMap[newProperty]) {
658
- newValue = transformValuePropertyMap[newProperty](value);
659
- }
660
- newProperty = hyphenateProperty(newProperty);
661
- // Remove trailing semicolon and new lines with regex
662
- result.push(cache.getOrStore({
663
- type,
664
- selector,
665
- property: newProperty,
666
- value: newValue,
667
- pseudo,
668
- media,
669
- support
670
- }));
671
- }
672
- }
673
- return result;
674
- };
675
- }
676
-
677
- class ClassList extends String {
678
- }
679
-
680
- class Static {
681
- }
682
-
683
- const defaultOptions = {
684
- enableSourceMaps: false,
685
- enableDebugIdentifiers: false
686
- };
687
- class Engine {
688
- caches = {
689
- rule: new Cache(new PropertyValueIDGenerator()),
690
- static: new Cache(new IDGenerator()),
691
- keyframes: new Cache(new AlphaIDGenerator()),
692
- fontFace: new Cache(new AlphaIDGenerator()),
693
- identifiers: new Cache(new AlphaIDGenerator())
694
- };
695
- usedIds = {};
696
- identifierCount = 0;
697
- options = {};
698
- sourceMapReferences = {};
699
- constructor(options = {}){
700
- this.options = {
701
- ...defaultOptions,
702
- ...Object.keys(options).reduce((acc, key)=>{
703
- if (options[key] !== undefined) {
704
- acc[key] = options[key];
705
- }
706
- return acc;
707
- }, {})
708
- };
709
- }
710
- addStatic(selector, styles) {
711
- this.addUsedIds("static", processStyles({
712
- type: "static",
713
- cache: this.caches.static
714
- })({
715
- styles,
716
- selector
717
- }).map((style)=>style.id));
718
- return new Static();
719
- }
720
- addStyle(styles) {
721
- const rules = processStyles({
722
- type: "rule",
723
- cache: this.caches.rule
724
- })({
725
- styles
726
- });
727
- const ids = rules.map((rule)=>rule.id);
728
- this.addUsedIds("rule", ids);
729
- return new ClassList(ids.join(" "));
730
- }
731
- addFontFace(fontFace) {
732
- const { id } = this.caches.fontFace.getOrStore({
733
- type: "fontFace",
734
- rule: Array.isArray(fontFace) ? fontFace : [
735
- fontFace
736
- ]
737
- });
738
- this.addUsedIds("fontFace", [
739
- id
740
- ]);
741
- return id;
742
- }
743
- addKeyframes(keyframes) {
744
- const { id } = this.caches.keyframes.getOrStore({
745
- type: "keyframes",
746
- rule: keyframes
747
- });
748
- this.addUsedIds("keyframes", [
749
- id
750
- ]);
751
- return id;
752
- }
753
- addSourceMapReference({ filePath , identifier , classList , line , column , index }) {
754
- if (!this.options.enableSourceMaps) {
755
- return false;
756
- }
757
- const { name } = path.parse(filePath);
758
- const extraClass = this.options.enableDebugIdentifiers ? `${name}_${identifier}` : '';
759
- const selector = '.' + classList.toString().split(' ').concat(extraClass).filter(Boolean).join('.');
760
- const newFilePath = path.relative(this.options.context || process.cwd(), filePath);
761
- if (index === 0 || !this.sourceMapReferences[newFilePath]) {
762
- this.sourceMapReferences[newFilePath] = [];
763
- }
764
- this.sourceMapReferences[newFilePath][index] = {
765
- selector,
766
- line,
767
- column
768
- };
769
- return extraClass;
770
- }
771
- generateIdentifier(value) {
772
- if (typeof value === 'undefined') {
773
- let identifier = hash((this.identifierCount++).toString(36));
774
- if (identifier.match(/^\d/)) {
775
- identifier = `_${identifier}`;
776
- }
777
- return identifier;
778
- }
779
- const newValue = JSON.stringify(value);
780
- const { id } = this.caches.identifiers.getOrStore({
781
- value: newValue
782
- });
783
- this.addUsedIds("identifiers", [
784
- id
785
- ]);
786
- return `_${id}`;
787
- }
788
- renderCssToString(options) {
789
- const { filePaths , usedIds , opinionatedLayers =false } = options || {};
790
- // We prioritize ids over filePaths. If neither are provided, we use all the used filePaths.
791
- const { keyframes: keyframesCache , fontFace: fontFaceCache , static: staticCache , rule: ruleCache } = usedIds ?? this.getUsedCacheIds(filePaths ?? Object.keys(this.usedIds));
792
- const { atRules , rules } = splitStyleBlocks(this.caches.rule.items(ruleCache));
793
- const keyFrameCss = printKeyFrames(this.caches.keyframes.items(keyframesCache));
794
- const fontFaceCss = printFontFaces(this.caches.fontFace.items(fontFaceCache));
795
- const staticCss = printStyleBlocks(this.caches.static.items(staticCache));
796
- const atRulesCss = printStyleBlocks(sortAtRules(atRules));
797
- const rulesCss = printStyleBlocks(rules);
798
- if (opinionatedLayers) {
799
- const result = `${keyFrameCss}${fontFaceCss}` + (staticCss.length > 0 ? `@layer static{${staticCss}}` : '') + (rulesCss.length > 0 ? `@layer rules{${rulesCss}}` : '') + (atRulesCss.length > 0 ? `@layer at{${atRulesCss}}` : '');
800
- if (result.length > 0) {
801
- return `@layer static,rules,at;${result}`;
802
- }
803
- return '';
804
- }
805
- return printSourceMap(this.sourceMapReferences, keyFrameCss + fontFaceCss + staticCss + rulesCss + atRulesCss);
806
- }
807
- serialize() {
808
- const { caches , usedIds , identifierCount , sourceMapReferences } = this;
809
- return JSON.stringify({
810
- caches,
811
- usedIds,
812
- identifierCount,
813
- sourceMapReferences
814
- });
815
- }
816
- async deserialize(buffer) {
817
- const data = JSON.parse(buffer.toString());
818
- function assign(target, source) {
819
- for(const key in source){
820
- if (isObject(target[key]) && isObject(source[key])) {
821
- assign(target[key], source[key]);
822
- } else {
823
- target[key] = source[key];
824
- }
825
- }
826
- return target;
827
- }
828
- assign(this, data);
829
- }
830
- setFilePath(filePath) {
831
- this.filePath = filePath;
832
- }
833
- clearUsedIds(filePath) {
834
- if (filePath === undefined) {
835
- return;
836
- }
837
- this.usedIds[filePath] = {};
838
- }
839
- addUsedIds(cacheType, identifiers) {
840
- const { filePath } = this;
841
- if (filePath === undefined) {
842
- return;
843
- }
844
- if (this.usedIds[filePath] === undefined) {
845
- this.usedIds[filePath] = {};
846
- }
847
- if (this.usedIds[filePath][cacheType] === undefined) {
848
- this.usedIds[filePath][cacheType] = [];
849
- }
850
- this.usedIds[filePath][cacheType] = [
851
- ...new Set([
852
- ...this.usedIds[filePath][cacheType],
853
- ...identifiers
854
- ])
855
- ];
856
- }
857
- getUsedCacheIds(filePaths = []) {
858
- return filePaths.reduce((acc, filePath)=>({
859
- ...acc,
860
- ...Object.keys(this.usedIds[filePath] || []).reduce((cache, key)=>({
861
- ...cache,
862
- [key]: [
863
- ...acc[key] || [],
864
- ...this.usedIds[filePath][key] || []
865
- ]
866
- }), {})
867
- }), Object.keys(this.caches).reduce((acc, key)=>({
868
- ...acc,
869
- [key]: []
870
- }), {}));
871
- }
872
- }
873
-
874
- exports.ClassList = ClassList;
875
- exports.Engine = Engine;
876
- exports.Static = Static;