@master/css 2.0.0-rc.14 → 2.0.0-rc.16

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 (74) hide show
  1. package/dist/_virtual/_commonjsHelpers.cjs +5 -0
  2. package/dist/_virtual/_commonjsHelpers.mjs +3 -0
  3. package/dist/_virtual/css-escape.cjs +5 -0
  4. package/dist/_virtual/css-escape.mjs +3 -0
  5. package/dist/bin/index.cjs +11 -0
  6. package/dist/bin/index.d.ts +1 -11
  7. package/dist/bin/index.mjs +9 -0
  8. package/dist/config/animations.cjs +113 -0
  9. package/dist/config/animations.mjs +111 -0
  10. package/dist/config/functions.cjs +352 -0
  11. package/dist/config/functions.mjs +350 -0
  12. package/dist/config/index.cjs +34 -0
  13. package/dist/config/index.mjs +25 -0
  14. package/dist/config/media-queries.cjs +7 -0
  15. package/dist/config/media-queries.mjs +1 -0
  16. package/dist/config/rules.cjs +2190 -0
  17. package/dist/config/rules.mjs +2184 -0
  18. package/dist/config/selectors.cjs +29 -0
  19. package/dist/config/selectors.mjs +27 -0
  20. package/dist/config/semantics.cjs +194 -0
  21. package/dist/config/semantics.mjs +192 -0
  22. package/dist/config/styles.cjs +2 -0
  23. package/dist/config/styles.mjs +1 -0
  24. package/dist/config/variables.cjs +583 -0
  25. package/dist/config/variables.mjs +581 -0
  26. package/dist/constants/base-unit-regex.cjs +5 -0
  27. package/dist/constants/base-unit-regex.mjs +3 -0
  28. package/dist/constants/start-symbol.cjs +10 -0
  29. package/dist/constants/start-symbol.mjs +8 -0
  30. package/dist/core.cjs +979 -0
  31. package/dist/core.d.ts +2 -3
  32. package/dist/core.mjs +974 -0
  33. package/dist/functions/reorder-for-readable-classes.cjs +68 -0
  34. package/dist/functions/reorder-for-readable-classes.d.ts +1 -1
  35. package/dist/functions/reorder-for-readable-classes.mjs +66 -0
  36. package/dist/functions/transform-color-with-opacity.cjs +9 -0
  37. package/dist/functions/transform-color-with-opacity.mjs +7 -0
  38. package/dist/index.cjs +37 -0
  39. package/dist/index.d.ts +3 -3
  40. package/dist/index.mjs +13 -0
  41. package/dist/layer.cjs +23 -0
  42. package/dist/layer.mjs +23 -0
  43. package/dist/polyfills/css-escape.cjs +8 -0
  44. package/dist/polyfills/css-escape.mjs +2 -0
  45. package/dist/polyfills/css-escape2.cjs +68 -0
  46. package/dist/polyfills/css-escape2.mjs +64 -0
  47. package/dist/rule.cjs +702 -0
  48. package/dist/rule.d.ts +1 -1
  49. package/dist/rule.mjs +700 -0
  50. package/dist/shared/utils/css-escape.cjs +56 -0
  51. package/dist/shared/utils/css-escape.mjs +54 -0
  52. package/dist/tokens/screen-sizes.cjs +17 -0
  53. package/dist/tokens/screen-sizes.mjs +15 -0
  54. package/dist/utils/concat-arrays.cjs +12 -0
  55. package/dist/utils/concat-arrays.mjs +10 -0
  56. package/dist/utils/extend-config.cjs +59 -0
  57. package/dist/utils/extend-config.mjs +57 -0
  58. package/dist/utils/flatten-object.cjs +15 -0
  59. package/dist/utils/flatten-object.mjs +13 -0
  60. package/dist/utils/get-type.cjs +12 -0
  61. package/dist/utils/get-type.mjs +10 -0
  62. package/dist/utils/hex-to-rgb.cjs +30 -0
  63. package/dist/utils/hex-to-rgb.mjs +28 -0
  64. package/dist/utils/is-plain-object.cjs +15 -0
  65. package/dist/utils/is-plain-object.mjs +13 -0
  66. package/dist/utils/is-symbol.cjs +14 -0
  67. package/dist/utils/is-symbol.mjs +12 -0
  68. package/dist/utils/rgb-to-hex.cjs +7 -0
  69. package/dist/utils/rgb-to-hex.mjs +5 -0
  70. package/package.json +1 -1
  71. package/dist/bin/index.bundle.js +0 -33
  72. package/dist/index.bundle.js +0 -1
  73. package/dist/index.bundle.mjs +0 -1
  74. package/dist/types/global.d.ts +0 -5
package/dist/core.mjs ADDED
@@ -0,0 +1,974 @@
1
+ import { Rule } from './rule.mjs';
2
+ import { config } from './config/index.mjs';
3
+ import { Layer } from './layer.mjs';
4
+ import { hexToRgb } from './utils/hex-to-rgb.mjs';
5
+ import { flattenObject } from './utils/flatten-object.mjs';
6
+ import { extendConfig } from './utils/extend-config.mjs';
7
+
8
+ class MasterCSS {
9
+ customConfig;
10
+ static config = config;
11
+ rules;
12
+ ruleBy;
13
+ classesUsage;
14
+ config;
15
+ RegisteredSemanticRules;
16
+ RegisteredRules;
17
+ constructor(customConfig = config){
18
+ this.customConfig = customConfig;
19
+ this.rules = [];
20
+ this.ruleBy = {};
21
+ this.classesUsage = {};
22
+ this.RegisteredSemanticRules = [];
23
+ this.RegisteredRules = [];
24
+ if (!customConfig?.override) {
25
+ this.config = extendConfig(config, customConfig);
26
+ } else {
27
+ this.config = extendConfig(customConfig);
28
+ }
29
+ this.resolve();
30
+ if (this.constructor === MasterCSS) {
31
+ masterCSSs.push(this);
32
+ }
33
+ }
34
+ resolve() {
35
+ this.styles = {};
36
+ this.stylesBy = {};
37
+ this.selectors = {};
38
+ this.variables = {};
39
+ this.mediaQueries = {};
40
+ this.animations = {};
41
+ this.RegisteredRules.length = 0;
42
+ this.RegisteredSemanticRules.length = 0;
43
+ this.variablesNativeRules = {};
44
+ this.hasKeyframesRule = false;
45
+ const colorVariableNames = {
46
+ current: undefined,
47
+ currentColor: undefined,
48
+ transparent: undefined
49
+ };
50
+ const { styles, selectors, variables, semantics, mediaQueries, rules, animations } = this.config;
51
+ function escapeString(str) {
52
+ return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
53
+ }
54
+ if (selectors) {
55
+ const resolvedSelectors = flattenObject(selectors);
56
+ for(const eachSelectorName in resolvedSelectors){
57
+ const eachResolvedSelectorText = resolvedSelectors[eachSelectorName];
58
+ const regexp = new RegExp(escapeString(eachSelectorName) + '(?![a-z-])');
59
+ for (const eachNewSelectorText of Array.isArray(eachResolvedSelectorText) ? eachResolvedSelectorText : [
60
+ eachResolvedSelectorText
61
+ ]){
62
+ const vendor = eachNewSelectorText.match(/^::-[a-z]+-/m)?.[0] ?? '';
63
+ let selectorValues = this.selectors[vendor];
64
+ if (!selectorValues) {
65
+ selectorValues = this.selectors[vendor] = [];
66
+ }
67
+ let currentSelectValue = selectorValues.find(([_valueRegexp])=>_valueRegexp === regexp);
68
+ if (!currentSelectValue) {
69
+ currentSelectValue = [
70
+ regexp,
71
+ []
72
+ ];
73
+ selectorValues.push(currentSelectValue);
74
+ }
75
+ currentSelectValue[1].push(eachNewSelectorText);
76
+ }
77
+ }
78
+ }
79
+ if (variables) {
80
+ const unexecutedAliasVariable = {};
81
+ const parseVariable = (variable, name, theme)=>{
82
+ if (!variable) return;
83
+ const addVariable = (name, variableValue, replacedTheme, alpha)=>{
84
+ if (variableValue === undefined) return;
85
+ if (variableValue.type === 'color') {
86
+ if (alpha) {
87
+ const slashIndex = variableValue.value.indexOf('/');
88
+ variableValue = {
89
+ ...variableValue,
90
+ value: slashIndex === -1 ? variableValue.value + ' / ' + (alpha.startsWith('0.') ? alpha.slice(1) : alpha) : variableValue.value.slice(0, slashIndex + 2) + String(+variableValue.value.slice(slashIndex + 2) * +alpha).slice(1)
91
+ };
92
+ }
93
+ colorVariableNames[name] = undefined;
94
+ }
95
+ const currentTheme = replacedTheme ?? theme;
96
+ if (currentTheme !== undefined) {
97
+ if (Object.prototype.hasOwnProperty.call(this.variables, name)) {
98
+ const variable = this.variables[name];
99
+ if (currentTheme) {
100
+ if (!variable.themes) {
101
+ variable.themes = {};
102
+ }
103
+ variable.themes[currentTheme] = variableValue;
104
+ } else {
105
+ variable.value = variableValue.value;
106
+ if (variableValue.type === 'color') {
107
+ variable.space = variableValue.space;
108
+ }
109
+ }
110
+ } else {
111
+ if (currentTheme) {
112
+ const newVariable = {
113
+ type: variableValue.type,
114
+ themes: {
115
+ [currentTheme]: variableValue
116
+ }
117
+ };
118
+ if (variableValue.type === 'color') {
119
+ newVariable.space = variableValue.space;
120
+ }
121
+ this.variables[name] = newVariable;
122
+ } else {
123
+ this.variables[name] = variableValue;
124
+ }
125
+ }
126
+ } else {
127
+ this.variables[name] = variableValue;
128
+ }
129
+ };
130
+ const type = typeof variable;
131
+ if (type === 'object') {
132
+ if (Array.isArray(variable)) {
133
+ addVariable(name, {
134
+ type: 'string',
135
+ value: variable.join(',')
136
+ });
137
+ } else {
138
+ const keys = Object.keys(variable);
139
+ for (const eachKey of keys){
140
+ if (eachKey === '' || eachKey.startsWith('@')) {
141
+ parseVariable(variable[eachKey], name, eachKey || keys.some((eachKey)=>eachKey.startsWith('@')) ? eachKey.slice(1) : undefined);
142
+ } else {
143
+ parseVariable(variable[eachKey], name + '-' + eachKey, undefined);
144
+ }
145
+ }
146
+ }
147
+ } else if (type === 'number') {
148
+ addVariable(name, {
149
+ type: 'number',
150
+ value: variable
151
+ });
152
+ addVariable('-' + name, {
153
+ type: 'number',
154
+ value: variable * -1
155
+ });
156
+ } else if (type === 'string') {
157
+ const aliasResult = /^\$\((.*?)\)(?: ?\/ ?(.+?))?$/.exec(variable);
158
+ if (aliasResult) {
159
+ if (!Object.prototype.hasOwnProperty.call(unexecutedAliasVariable, name)) {
160
+ unexecutedAliasVariable[name] = {};
161
+ }
162
+ unexecutedAliasVariable[name][theme] = ()=>{
163
+ delete unexecutedAliasVariable[name][theme];
164
+ const [alias, aliasTheme] = aliasResult[1].split('@');
165
+ if (alias) {
166
+ if (Object.prototype.hasOwnProperty.call(unexecutedAliasVariable, alias)) {
167
+ for (const theme of Object.keys(unexecutedAliasVariable[alias])){
168
+ unexecutedAliasVariable[alias][theme]?.();
169
+ }
170
+ }
171
+ const aliasVariable = this.variables[alias];
172
+ if (aliasVariable) {
173
+ if (aliasTheme === undefined && aliasVariable.themes) {
174
+ addVariable(name, {
175
+ type: aliasVariable.type,
176
+ value: aliasVariable.value,
177
+ space: aliasVariable.space
178
+ }, '', aliasResult[2]);
179
+ for(const theme in aliasVariable.themes){
180
+ addVariable(name, aliasVariable.themes[theme], theme, aliasResult[2]);
181
+ }
182
+ } else {
183
+ const variable = aliasTheme !== undefined ? aliasVariable.themes?.[aliasTheme] : aliasVariable;
184
+ if (variable) {
185
+ const newVariable = {
186
+ type: variable.type,
187
+ value: variable.value
188
+ };
189
+ if (variable.type === 'color') {
190
+ newVariable.space = variable.space;
191
+ }
192
+ addVariable(name, newVariable, undefined, aliasResult[2]);
193
+ }
194
+ }
195
+ }
196
+ }
197
+ };
198
+ } else {
199
+ const hexColorResult = /^#([A-Fa-f0-9]{3,4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.exec(variable);
200
+ if (hexColorResult) {
201
+ const [r, g, b, a] = hexToRgb(hexColorResult[1]);
202
+ addVariable(name, {
203
+ type: 'color',
204
+ value: `${r} ${g} ${b}${a === 1 ? '' : ' / ' + a}`,
205
+ space: 'rgb'
206
+ });
207
+ } else {
208
+ const rgbFunctionResult = /^rgb\( *([0-9]{1,3})(?: *, *| +)([0-9]{1,3})(?: *, *| +)([0-9]{1,3}) *(?:(?:,|\/) *(.*?) *)?\)$/.exec(variable);
209
+ if (rgbFunctionResult) {
210
+ addVariable(name, {
211
+ type: 'color',
212
+ value: rgbFunctionResult[1] + ' ' + rgbFunctionResult[2] + ' ' + rgbFunctionResult[3] + (rgbFunctionResult[4] ? ' / ' + (rgbFunctionResult[4].startsWith('0.') ? rgbFunctionResult[4].slice(1) : rgbFunctionResult[4]) : ''),
213
+ space: 'rgb'
214
+ });
215
+ } else {
216
+ const hslFunctionResult = /^hsl\((.*?)\)$/.exec(variable);
217
+ if (hslFunctionResult) {
218
+ addVariable(name, {
219
+ type: 'color',
220
+ value: hslFunctionResult[1],
221
+ space: 'hsl'
222
+ });
223
+ } else {
224
+ addVariable(name, {
225
+ type: 'string',
226
+ value: variable
227
+ });
228
+ }
229
+ }
230
+ }
231
+ }
232
+ }
233
+ };
234
+ for(const parnetKey in variables){
235
+ parseVariable(variables[parnetKey], parnetKey);
236
+ }
237
+ for (const name of Object.keys(unexecutedAliasVariable)){
238
+ for (const theme of Object.keys(unexecutedAliasVariable[name])){
239
+ unexecutedAliasVariable[name][theme]?.();
240
+ }
241
+ }
242
+ }
243
+ if (mediaQueries) {
244
+ this.mediaQueries = flattenObject(mediaQueries);
245
+ }
246
+ if (animations) {
247
+ for(const animationName in animations){
248
+ const eachAnimation = this.animations[animationName] = {};
249
+ const eachKeyframes = animations[animationName];
250
+ for(const eachKeyframeValue in eachKeyframes){
251
+ const newValueByPropertyName = eachAnimation[eachKeyframeValue] = {};
252
+ const eachKeyframeDeclarations = eachKeyframes[eachKeyframeValue];
253
+ for(const propertyName in eachKeyframeDeclarations){
254
+ newValueByPropertyName[propertyName] = eachKeyframeDeclarations[propertyName];
255
+ }
256
+ }
257
+ }
258
+ }
259
+ const flattedStyles = styles ? flattenObject(styles) : {};
260
+ const semanticNames = Object.keys(flattedStyles);
261
+ const handleSemanticName = (semanticName)=>{
262
+ if (Object.prototype.hasOwnProperty.call(this.styles, semanticName)) return;
263
+ const currentClass = this.styles[semanticName] = [];
264
+ const className = flattedStyles[semanticName];
265
+ if (!className) return;
266
+ const classNames = className.replace(/(?:\n(?:\s*))+/g, ' ').trim().split(' ');
267
+ for (const eachClassName of classNames){
268
+ const handle = (className)=>{
269
+ if (Object.prototype.hasOwnProperty.call(this.stylesBy, className)) {
270
+ const currentRelation = this.stylesBy[className];
271
+ if (!currentRelation.includes(semanticName)) {
272
+ currentRelation.push(semanticName);
273
+ }
274
+ } else {
275
+ this.stylesBy[className] = [
276
+ semanticName
277
+ ];
278
+ }
279
+ if (!currentClass.includes(className)) {
280
+ currentClass.push(className);
281
+ }
282
+ };
283
+ if (semanticNames.includes(eachClassName)) {
284
+ handleSemanticName(eachClassName);
285
+ for (const parentClassName of this.styles[eachClassName]){
286
+ handle(parentClassName);
287
+ }
288
+ } else {
289
+ handle(eachClassName);
290
+ }
291
+ }
292
+ };
293
+ for (const eachSemanticName of semanticNames){
294
+ handleSemanticName(eachSemanticName);
295
+ }
296
+ if (semantics) {
297
+ Object.entries(semantics).sort((a, b)=>a[0].localeCompare(b[0])).forEach(([id, declarations], index)=>{
298
+ this.RegisteredSemanticRules.push({
299
+ id: '.' + id,
300
+ match: new RegExp('^' + escapeString(id) + '(?=!|\\*|>|\\+|~|:|\\[|@|_|\\.|$)', 'm'),
301
+ order: index,
302
+ definition: {
303
+ declarations,
304
+ layer: Layer.Semantic
305
+ }
306
+ });
307
+ });
308
+ }
309
+ if (rules) {
310
+ const rulesEntries = Object.entries(rules).sort((a, b)=>{
311
+ if (a[1].layer !== b[1].layer) {
312
+ return (b[1].layer || 0) - (a[1].layer || 0);
313
+ }
314
+ return b[0].localeCompare(a[0]);
315
+ });
316
+ const rulesEntriesLength = rulesEntries.length;
317
+ const colorNames = Object.keys(colorVariableNames);
318
+ rulesEntries.forEach(([id, eachRuleDefinition], index)=>{
319
+ const eachRegisteredRule = {
320
+ id,
321
+ variables: {},
322
+ order: this.RegisteredSemanticRules.length + rulesEntriesLength - 1 - index,
323
+ definition: eachRuleDefinition
324
+ };
325
+ this.RegisteredRules.push(eachRegisteredRule);
326
+ const match = eachRuleDefinition.match;
327
+ // todo: 不可使用 startsWith 判斷,應改為更精準的從 config.variables 取得目標變數群組,但 config.variables 中的值還沒被 resolve 像是 Array
328
+ const addResolvedVariables = (prefix)=>{
329
+ for(const eachVariableName in this.variables){
330
+ if (eachVariableName.startsWith(prefix + '-') || eachVariableName.startsWith('-' + prefix + '-')) {
331
+ const simplifiedName = eachVariableName.slice(prefix.length + (prefix.startsWith('-') ? 0 : 1));
332
+ eachRegisteredRule.variables[simplifiedName] = {
333
+ ...this.variables[eachVariableName],
334
+ name: eachVariableName
335
+ };
336
+ }
337
+ }
338
+ };
339
+ // 1. custom `config.rules[id].variables`
340
+ if (eachRuleDefinition.variables) {
341
+ for (const eachVariableGroup of eachRuleDefinition.variables){
342
+ addResolvedVariables(eachVariableGroup);
343
+ }
344
+ }
345
+ // 2. custom `config.variables`
346
+ addResolvedVariables(id);
347
+ if (match) {
348
+ if (Array.isArray(match)) {
349
+ const [key, values = []] = match;
350
+ const valueMatches = [];
351
+ if (values.length) {
352
+ valueMatches.push(`(?:${values.join('|')})(?![a-zA-Z0-9-])`);
353
+ }
354
+ if (Object.keys(eachRegisteredRule.variables).length) {
355
+ valueMatches.push(`(?:${Object.keys(eachRegisteredRule.variables).join('|')})(?![a-zA-Z0-9-])`);
356
+ }
357
+ if (eachRuleDefinition.colored) {
358
+ valueMatches.push('#', '(?:color|color-contrast|color-mix|hwb|lab|lch|oklab|oklch|rgb|rgba|hsl|hsla)\\(.*\\)', `(?:${colorNames.join('|')})(?![a-zA-Z0-9-])`);
359
+ }
360
+ if (eachRuleDefinition.numeric) {
361
+ valueMatches.push('[\\d\\.]', '(?:max|min|calc|clamp)\\(.*\\)');
362
+ }
363
+ if (valueMatches.length) eachRegisteredRule.match = new RegExp(`^${key}:(?:${valueMatches.join('|')})[^|]*?(?:@|$)`);
364
+ } else {
365
+ eachRegisteredRule.match = match;
366
+ }
367
+ }
368
+ });
369
+ }
370
+ }
371
+ /**
372
+ * Match check if Master CSS syntax
373
+ * @param className
374
+ * @returns css text
375
+ */ match(className) {
376
+ // 1. rules
377
+ for (const eachRegisteredRule of this.RegisteredRules){
378
+ if (eachRegisteredRule.match?.test(className) || (eachRegisteredRule.definition.layer === Layer.Native || eachRegisteredRule.definition.layer === Layer.NativeShorthand || eachRegisteredRule.definition.layer === Layer.CoreNative || eachRegisteredRule.definition.layer === Layer.CoreNativeShorthand) && className.startsWith(eachRegisteredRule.id + ':')) {
379
+ return eachRegisteredRule;
380
+ }
381
+ }
382
+ // 2. semantic rules
383
+ for (const EachRegisteredSemanticRule of this.RegisteredSemanticRules){
384
+ if (EachRegisteredSemanticRule.match?.test(className)) {
385
+ return EachRegisteredSemanticRule;
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Generate rules from class name
391
+ * @param className
392
+ * @returns Rule[]
393
+ */ generate(className) {
394
+ return (Object.prototype.hasOwnProperty.call(this.styles, className) ? this.styles[className].map((eachSyntax)=>this.create(eachSyntax)) : [
395
+ this.create(className)
396
+ ]).filter((eachRule)=>eachRule && eachRule.text);
397
+ }
398
+ /**
399
+ * Create rule from given syntax
400
+ * @param syntax
401
+ * @returns Rule
402
+ */ create(syntax) {
403
+ if (Object.prototype.hasOwnProperty.call(this.ruleBy, syntax)) return this.ruleBy[syntax];
404
+ const RegistedRule = this.match(syntax);
405
+ if (RegistedRule) {
406
+ return new Rule(syntax, RegistedRule, this);
407
+ }
408
+ }
409
+ /**
410
+ * 根據蒐集到的所有 DOM class 重新 create
411
+ */ refresh(customConfig = this.customConfig) {
412
+ if (!customConfig?.override) {
413
+ // @ts-ignore
414
+ this.config = extendConfig(config, customConfig);
415
+ } else {
416
+ // @ts-ignore
417
+ this.config = extendConfig(customConfig);
418
+ }
419
+ this.resolve();
420
+ this.rules.length = 0;
421
+ // @ts-ignore
422
+ this.ruleBy = {};
423
+ /**
424
+ * 拿當前所有的 classNames 按照最新的 colors, config.rules 匹配並生成新的 style
425
+ * 所以 refresh 過後 rules 可能會變多也可能會變少
426
+ */ for(const name in this.classesUsage){
427
+ this.add(name);
428
+ }
429
+ return this;
430
+ }
431
+ reset() {
432
+ // @ts-ignore
433
+ this.ruleBy = {};
434
+ // @ts-ignore
435
+ this.classesUsage = {};
436
+ this.rules.length = 0;
437
+ this.hasKeyframesRule = false;
438
+ this.variablesNativeRules = {};
439
+ for(const keyframeName in this.animations){
440
+ const animation = this.animations[keyframeName];
441
+ animation.usage = 0;
442
+ animation.native = undefined;
443
+ }
444
+ for(const variableName in this.variables){
445
+ const variable = this.variables[variableName];
446
+ variable.usage = 0;
447
+ }
448
+ return this;
449
+ }
450
+ destroy() {
451
+ this.reset();
452
+ masterCSSs.splice(masterCSSs.indexOf(this), 1);
453
+ return this;
454
+ }
455
+ add(...classNames) {
456
+ for (const className of classNames){
457
+ const rules = this.generate(className);
458
+ if (rules.length) {
459
+ for (const rule of rules){
460
+ this.insert(rule);
461
+ }
462
+ }
463
+ }
464
+ return this;
465
+ }
466
+ delete(...classNames) {
467
+ /**
468
+ * class name 從 DOM tree 中被移除,
469
+ * 匹配並刪除對應的 rule
470
+ */ const sheet = this.style?.sheet;
471
+ const deleteRule = (name)=>{
472
+ const rule = this.ruleBy[name];
473
+ if (!rule || Object.prototype.hasOwnProperty.call(this.stylesBy, name) && this.stylesBy[name].some((eachClassName)=>Object.prototype.hasOwnProperty.call(this.classesUsage, eachClassName))) return;
474
+ if (sheet && rule.natives.length) {
475
+ const firstNative = rule.natives[0];
476
+ for(let index = 0; index < sheet.cssRules.length; index++){
477
+ const eachCSSRule = sheet.cssRules[index];
478
+ if (eachCSSRule === firstNative.cssRule) {
479
+ for(let i = 0; i < rule.natives.length; i++){
480
+ sheet.deleteRule(index);
481
+ }
482
+ break;
483
+ }
484
+ }
485
+ }
486
+ this.rules.splice(this.rules.indexOf(rule), 1);
487
+ delete this.ruleBy[name];
488
+ // variables
489
+ if (rule.variableNames) {
490
+ for (const eachVariableName of rule.variableNames){
491
+ const variable = this.variables[eachVariableName];
492
+ if (!variable.usage) variable.usage = 0;
493
+ if (!--variable.usage) {
494
+ const removeProperty = (theme)=>{
495
+ const nativeRule = this.variablesNativeRules[theme];
496
+ nativeRule.cssRule.style.removeProperty('--' + eachVariableName);
497
+ if (!nativeRule.cssRule.style.length) {
498
+ const variablesRule = this.rules[0];
499
+ const index = variablesRule.natives.indexOf(nativeRule);
500
+ sheet?.deleteRule(index);
501
+ variablesRule.natives.splice(index, 1);
502
+ delete this.variablesNativeRules[theme];
503
+ if (!variablesRule.natives.length) {
504
+ this.rules.splice(0, 1);
505
+ this.variablesNativeRules = {};
506
+ }
507
+ }
508
+ };
509
+ if (variable.value) {
510
+ removeProperty('');
511
+ }
512
+ if (variable.themes) {
513
+ for(const theme in variable.themes){
514
+ removeProperty(theme);
515
+ }
516
+ }
517
+ }
518
+ }
519
+ }
520
+ // animations
521
+ if (rule.animationNames) {
522
+ const keyframeRulesIndex = Object.keys(this.variablesNativeRules).length ? 1 : 0;
523
+ const keyframeRule = this.rules[keyframeRulesIndex];
524
+ for (const eachKeyframeName of rule.animationNames){
525
+ const keyframe = this.animations[eachKeyframeName];
526
+ if (!keyframe.usage) keyframe.usage = 0;
527
+ if (!--keyframe.usage && keyframe.native) {
528
+ const nativeIndex = keyframeRule.natives.indexOf(keyframe.native);
529
+ this.style.sheet?.deleteRule(Object.keys(this.variablesNativeRules).length + nativeIndex);
530
+ keyframeRule.natives.splice(nativeIndex, 1);
531
+ keyframe.native = undefined;
532
+ }
533
+ }
534
+ if (!keyframeRule.natives.length) {
535
+ this.rules.splice(keyframeRulesIndex, 1);
536
+ this.hasKeyframesRule = false;
537
+ }
538
+ }
539
+ rule.definition.delete?.call(rule, name);
540
+ };
541
+ for (const className of classNames){
542
+ if (Object.prototype.hasOwnProperty.call(this.styles, className)) {
543
+ for (const eachClassName of this.styles[className]){
544
+ if (!Object.prototype.hasOwnProperty.call(this.classesUsage, eachClassName)) {
545
+ deleteRule(eachClassName);
546
+ }
547
+ }
548
+ delete this.ruleBy[className];
549
+ } else {
550
+ deleteRule(className);
551
+ }
552
+ }
553
+ }
554
+ /**
555
+ * 加工插入規則
556
+ * 1. where
557
+ * 2. normal
558
+ * 3. where selectors
559
+ * 4. normal selectors
560
+ * 5. media where
561
+ * 6. media normal
562
+ * 7. media where selectors
563
+ * 8. media selectors
564
+ * 9. media width where
565
+ * 10. media width
566
+ * 11. media width where selectors
567
+ * 12. media width selectors
568
+ */ insert(rule) {
569
+ if (this.ruleBy[rule.className]) return;
570
+ let index;
571
+ /**
572
+ * 必須按斷點值遞增,並透過索引插入,
573
+ * 以實現響應式先後套用的規則
574
+ * @example <1 <2 <3 ALL >=1 >=2 >=3
575
+ * @description
576
+ */ const endIndex = this.rules.length - 1;
577
+ const { media, order, priority, hasWhere, className } = rule;
578
+ const findIndex = (startIndex, stopCheck, matchCheck)=>{
579
+ let i = startIndex;
580
+ for(; i <= endIndex; i++){
581
+ const eachRule = this.rules[i];
582
+ if (stopCheck?.(eachRule)) return matchCheck ? -1 : i - 1;
583
+ if (matchCheck?.(eachRule)) return i;
584
+ }
585
+ return matchCheck ? -1 : i - 1;
586
+ };
587
+ let matchStartIndex;
588
+ let matchEndIndex;
589
+ if (media) {
590
+ const mediaStartIndex = this.rules.findIndex((eachRule)=>eachRule.media);
591
+ if (mediaStartIndex === -1) {
592
+ index = endIndex + 1;
593
+ } else {
594
+ const { 'max-width': maxWidthFeature, 'min-width': minWidthFeature } = media.features;
595
+ if (maxWidthFeature || minWidthFeature) {
596
+ const mediaWidthStartIndex = this.rules.findIndex((eachRule)=>eachRule.media?.features['max-width'] || eachRule.media?.features['min-width']);
597
+ if (mediaWidthStartIndex === -1) {
598
+ index = endIndex + 1;
599
+ } else {
600
+ if (maxWidthFeature && minWidthFeature) {
601
+ /**
602
+ * 範圍越小 ( 越限定 越侷限 ) 越優先,
603
+ * 按照範圍 max-width - min-width 遞減排序
604
+ * find 第一個所遇到同樣 feature 且範圍值比自己大的 rule,
605
+ * 並插入在該 rule 之後,讓自己優先被套用
606
+ */ if (priority === -1) {
607
+ matchStartIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.priority !== -1, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width']);
608
+ matchEndIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.priority !== -1);
609
+ } else {
610
+ matchStartIndex = findIndex(mediaWidthStartIndex, undefined, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width'] && eachRule.priority !== -1);
611
+ matchEndIndex = endIndex;
612
+ }
613
+ if (matchStartIndex !== -1) {
614
+ const range = maxWidthFeature.value - minWidthFeature.value;
615
+ let i = matchEndIndex;
616
+ const endI = matchStartIndex;
617
+ matchStartIndex = undefined;
618
+ for(; i >= endI; i--){
619
+ const { 'max-width': eachMaxWidthFeature, 'min-width': eachMinWidthFeature } = this.rules[i].media.features;
620
+ const eachRange = eachMaxWidthFeature.value - eachMinWidthFeature.value;
621
+ if (eachRange < range) {
622
+ matchEndIndex = i - 1;
623
+ } else if (eachRange === range) {
624
+ matchStartIndex = i;
625
+ } else {
626
+ break;
627
+ }
628
+ }
629
+ }
630
+ if (matchStartIndex !== -1 && matchStartIndex !== undefined) {
631
+ const range = maxWidthFeature.value - minWidthFeature.value;
632
+ for(let i = matchEndIndex; i >= matchStartIndex; i--){
633
+ const { 'max-width': eachMaxWidthFeature, 'min-width': eachMinWidthFeature } = this.rules[i].media.features;
634
+ const eachRange = eachMaxWidthFeature.value - eachMinWidthFeature.value;
635
+ if (eachRange < range) {
636
+ matchEndIndex = i - 1;
637
+ } else if (eachRange > range) {
638
+ matchStartIndex = i + 1;
639
+ break;
640
+ }
641
+ }
642
+ }
643
+ } else if (minWidthFeature) {
644
+ /**
645
+ * find 第一個所遇到同樣 feature 且值比自己大的 rule,
646
+ * 並插入在該 rule 之後,讓自己優先被套用
647
+ */ if (priority === -1) {
648
+ matchStartIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width'] || eachRule.priority !== -1, (eachRule)=>!eachRule.media.features['max-width'] && eachRule.media.features['min-width']);
649
+ matchEndIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width'] || eachRule.priority !== -1);
650
+ } else {
651
+ matchStartIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width'] && eachRule.priority !== -1, (eachRule)=>!eachRule.media.features['max-width'] && eachRule.media.features['min-width'] && eachRule.priority !== -1);
652
+ matchEndIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['max-width'] && eachRule.media.features['min-width'] && eachRule.priority !== -1);
653
+ }
654
+ if (matchStartIndex !== -1) {
655
+ for(let i = matchEndIndex; i >= matchStartIndex; i--){
656
+ const value = this.rules[i].media.features['min-width'].value;
657
+ if (value > minWidthFeature.value) {
658
+ matchEndIndex = i - 1;
659
+ } else if (value < minWidthFeature.value) {
660
+ matchStartIndex = i + 1;
661
+ break;
662
+ }
663
+ }
664
+ }
665
+ } else {
666
+ /**
667
+ * find 第一個所遇到同樣 feature 且值比自己大的 rule,
668
+ * 並插入在該 rule 之後,讓自己優先被套用
669
+ */ if (priority === -1) {
670
+ matchStartIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['min-width'] || eachRule.priority !== -1, (eachRule)=>eachRule.media.features['max-width']);
671
+ matchEndIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['min-width'] || eachRule.priority !== -1);
672
+ } else {
673
+ matchStartIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['min-width'] && eachRule.priority !== -1, (eachRule)=>eachRule.media.features['max-width'] && eachRule.priority !== -1);
674
+ matchEndIndex = findIndex(mediaWidthStartIndex, (eachRule)=>eachRule.media.features['min-width'] && eachRule.priority !== -1);
675
+ }
676
+ if (matchStartIndex !== -1) {
677
+ for(let i = matchEndIndex; i >= matchStartIndex; i--){
678
+ const value = this.rules[i].media.features['max-width'].value;
679
+ if (value < maxWidthFeature.value) {
680
+ matchEndIndex = i - 1;
681
+ } else if (value > maxWidthFeature.value) {
682
+ matchStartIndex = i + 1;
683
+ break;
684
+ }
685
+ }
686
+ }
687
+ }
688
+ }
689
+ } else {
690
+ if (priority === -1) {
691
+ matchStartIndex = mediaStartIndex;
692
+ matchEndIndex = findIndex(mediaStartIndex, (eachRule)=>eachRule.media?.features['max-width'] || eachRule.media?.features['min-width'] || eachRule.priority !== -1);
693
+ } else {
694
+ matchStartIndex = findIndex(mediaStartIndex, (eachRule)=>eachRule.media?.features['max-width'] || eachRule.media?.features['min-width'], (eachRule)=>eachRule.priority !== -1);
695
+ matchEndIndex = findIndex(mediaStartIndex, (eachRule)=>eachRule.media?.features['max-width'] || eachRule.media?.features['min-width']);
696
+ }
697
+ }
698
+ }
699
+ } else {
700
+ const findStartIndex = Object.keys(this.variablesNativeRules).length ? this.hasKeyframesRule ? 2 : 1 : this.hasKeyframesRule ? 1 : 0;
701
+ if (priority === -1) {
702
+ matchStartIndex = findStartIndex;
703
+ matchEndIndex = findIndex(findStartIndex, (eachRule)=>eachRule.media || eachRule.priority !== -1);
704
+ } else {
705
+ matchStartIndex = findIndex(findStartIndex, (eachRule)=>eachRule.media, (eachRule)=>eachRule.priority !== -1);
706
+ matchEndIndex = findIndex(findStartIndex, (eachRule)=>eachRule.media);
707
+ }
708
+ }
709
+ if (index === undefined && matchEndIndex !== undefined && matchStartIndex !== undefined) {
710
+ if (matchStartIndex === -1) {
711
+ index = matchEndIndex + 1;
712
+ } else {
713
+ if (priority === -1) {
714
+ for(let i = matchStartIndex; i <= matchEndIndex; i++){
715
+ const currentRule = this.rules[i];
716
+ if (!hasWhere && currentRule.hasWhere) continue;
717
+ if (hasWhere && !currentRule.hasWhere || currentRule.order >= order) {
718
+ index = i;
719
+ break;
720
+ }
721
+ }
722
+ } else {
723
+ for(let i = matchStartIndex; i <= matchEndIndex; i++){
724
+ const currentRule = this.rules[i];
725
+ if (!hasWhere && currentRule.hasWhere) continue;
726
+ if (hasWhere && !currentRule.hasWhere) {
727
+ index = i;
728
+ break;
729
+ }
730
+ if (currentRule.priority < priority) {
731
+ index = i;
732
+ break;
733
+ } else if (currentRule.priority === priority) {
734
+ if (currentRule.order >= order) {
735
+ index = i;
736
+ break;
737
+ }
738
+ } else {
739
+ index = i + 1;
740
+ }
741
+ }
742
+ }
743
+ if (index === undefined) {
744
+ index = matchEndIndex + 1;
745
+ }
746
+ }
747
+ }
748
+ this.rules.splice(index, 0, rule);
749
+ this.ruleBy[className] = rule;
750
+ // 只在瀏覽器端運行
751
+ if (this.style) {
752
+ const sheet = this.style.sheet;
753
+ let cssRuleIndex = 0;
754
+ const getCssRuleIndex = (index)=>{
755
+ const previousRule = this.rules[index];
756
+ if (previousRule) {
757
+ if (!previousRule.natives.length) return getCssRuleIndex(index - 1);
758
+ const lastNative = previousRule.natives[previousRule.natives.length - 1];
759
+ const lastNativeCssRule = lastNative.cssRule?.parentRule ?? lastNative.cssRule;
760
+ if (sheet) for(let i = 0; i < sheet.cssRules.length; i++){
761
+ if (sheet.cssRules[i] === lastNativeCssRule) {
762
+ cssRuleIndex = i + 1;
763
+ break;
764
+ }
765
+ }
766
+ }
767
+ };
768
+ getCssRuleIndex(index - 1);
769
+ for(let i = 0; i < rule.natives.length;){
770
+ try {
771
+ const native = rule.natives[i];
772
+ sheet?.insertRule(native.text, cssRuleIndex);
773
+ native.cssRule = sheet?.cssRules[cssRuleIndex++];
774
+ i++;
775
+ } catch (error) {
776
+ console.error(error);
777
+ rule.natives.splice(i, 1);
778
+ }
779
+ }
780
+ }
781
+ // variables
782
+ this.handleRuleWithVariableNames(rule);
783
+ // animations
784
+ this.handleRuleWithAnimationNames(rule);
785
+ rule.definition.insert?.call(rule);
786
+ }
787
+ get text() {
788
+ return this.rules.map((eachRule)=>eachRule.text).join('');
789
+ }
790
+ handleRuleWithAnimationNames(rule, initializing = false) {
791
+ if (rule.animationNames) {
792
+ const sheet = this.style?.sheet;
793
+ for (const eachKeyframeName of rule.animationNames){
794
+ const animation = this.animations[eachKeyframeName];
795
+ if (animation.usage) {
796
+ animation.usage++;
797
+ } else {
798
+ const nativeRule = {
799
+ text: `@keyframes ${eachKeyframeName}{` + Object.entries(animation).filter(([key])=>key !== 'usage' && key !== 'native').map(([key, variables])=>`${key}{${Object.entries(variables).map(([name, value])=>name + ':' + value).join(';')}}`).join('') + '}'
800
+ };
801
+ const keyframeRulesIndex = Object.keys(this.variablesNativeRules).length ? 1 : 0;
802
+ let keyframeRule;
803
+ if (this.hasKeyframesRule) {
804
+ (keyframeRule = this.rules[keyframeRulesIndex]).natives.push(nativeRule);
805
+ } else {
806
+ this.rules.splice(keyframeRulesIndex, 0, keyframeRule = {
807
+ natives: [
808
+ nativeRule
809
+ ],
810
+ get text () {
811
+ return this.natives.map((eachNative)=>eachNative.text).join('');
812
+ }
813
+ });
814
+ this.hasKeyframesRule = true;
815
+ }
816
+ if (sheet) {
817
+ let cssRule;
818
+ if (initializing) {
819
+ for(let i = 0; i < sheet.cssRules.length; i++){
820
+ const eachCSSRule = sheet.cssRules[i];
821
+ if (eachCSSRule.constructor.name === 'CSSKeyframesRule' && eachCSSRule.name === eachKeyframeName) {
822
+ cssRule = eachCSSRule;
823
+ break;
824
+ }
825
+ }
826
+ }
827
+ if (cssRule) {
828
+ nativeRule.cssRule = cssRule;
829
+ } else {
830
+ const cssRuleIndex = Object.keys(this.variablesNativeRules).length + keyframeRule.natives.length - 1;
831
+ sheet.insertRule(nativeRule.text, cssRuleIndex);
832
+ nativeRule.cssRule = sheet.cssRules[cssRuleIndex];
833
+ }
834
+ }
835
+ animation.usage = 1;
836
+ animation.native = nativeRule;
837
+ }
838
+ }
839
+ }
840
+ }
841
+ handleRuleWithVariableNames(rule, initializing = false) {
842
+ if (rule.variableNames) {
843
+ const sheet = this.style?.sheet;
844
+ for (const eachVariableName of rule.variableNames){
845
+ const variable = this.variables[eachVariableName];
846
+ if (variable.usage) {
847
+ variable.usage++;
848
+ } else {
849
+ const addProperty = (theme, variableValue)=>{
850
+ let nativeRule = this.variablesNativeRules[theme];
851
+ if (!nativeRule) {
852
+ let cssRule;
853
+ let mediaConditionText;
854
+ let selectorText;
855
+ if (theme) {
856
+ switch(this.config.themeDriver){
857
+ case 'media':
858
+ mediaConditionText = `@media(prefers-color-scheme:${theme})`;
859
+ selectorText = ':root';
860
+ break;
861
+ case 'host':
862
+ selectorText = `:host(.${theme})`;
863
+ break;
864
+ default:
865
+ selectorText = `.${theme}`;
866
+ break;
867
+ }
868
+ } else {
869
+ selectorText = ':root';
870
+ }
871
+ if (sheet) {
872
+ const newCSSRuleIndex = Object.keys(this.variablesNativeRules).length ? this.rules[0].natives.length : 0;
873
+ sheet.insertRule((mediaConditionText ? mediaConditionText + '{' : '') + selectorText + '{}' + (mediaConditionText ? mediaConditionText + '}' : ''), newCSSRuleIndex);
874
+ cssRule = mediaConditionText ? sheet.cssRules[newCSSRuleIndex].cssRules[0] : sheet.cssRules[newCSSRuleIndex];
875
+ } else {
876
+ const styleMap = new Map();
877
+ const style = Object.defineProperties({}, {
878
+ getPropertyValue: {
879
+ value: (property)=>styleMap.get(property)
880
+ },
881
+ removeProperty: {
882
+ value: (property)=>{
883
+ styleMap.delete(property);
884
+ for(let i = 0; i < style.length; i++){
885
+ if (style[i] === property) {
886
+ delete style[i];
887
+ }
888
+ }
889
+ }
890
+ },
891
+ setProperty: {
892
+ value: (property, value)=>{
893
+ style[style.length] = property;
894
+ styleMap.set(property, value);
895
+ }
896
+ },
897
+ length: {
898
+ get () {
899
+ return Object.keys(style).length;
900
+ }
901
+ }
902
+ });
903
+ cssRule = {
904
+ selectorText,
905
+ style,
906
+ styleMap
907
+ };
908
+ if (mediaConditionText) {
909
+ // @ts-ignore
910
+ cssRule.parentRule = {
911
+ conditionText: mediaConditionText
912
+ };
913
+ }
914
+ }
915
+ nativeRule = this.pushVariableNativeRule(theme, cssRule);
916
+ }
917
+ const propertyName = '--' + eachVariableName;
918
+ if (!initializing || !nativeRule.cssRule.style.getPropertyValue(propertyName)) {
919
+ nativeRule.cssRule.style.setProperty(propertyName, String(variableValue.value));
920
+ }
921
+ };
922
+ if (variable.value) {
923
+ addProperty('', variable);
924
+ }
925
+ if (variable.themes) {
926
+ for(const theme in variable.themes){
927
+ addProperty(theme, variable.themes[theme]);
928
+ }
929
+ }
930
+ variable.usage = 1;
931
+ }
932
+ }
933
+ }
934
+ }
935
+ pushVariableNativeRule(theme, variableCSSRule) {
936
+ if (!Object.keys(this.variablesNativeRules).length) {
937
+ this.variablesNativeRules = {};
938
+ const newRule = {
939
+ natives: [],
940
+ get text () {
941
+ return this.natives.map((eachNative)=>eachNative.text).join('');
942
+ }
943
+ };
944
+ this.rules.splice(0, 0, newRule);
945
+ }
946
+ let prefix = '';
947
+ let suffix = '}';
948
+ if (variableCSSRule.parentRule) {
949
+ prefix += variableCSSRule.parentRule.conditionText.replace(/ /g, '') + '{';
950
+ suffix += '}';
951
+ }
952
+ prefix += variableCSSRule.selectorText + '{';
953
+ const nativeRule = {
954
+ cssRule: variableCSSRule,
955
+ get text () {
956
+ const properties = [];
957
+ for(let i = 0; i < variableCSSRule.style.length; i++){
958
+ const property = variableCSSRule.style[i];
959
+ properties.push(property + ':' + variableCSSRule.style.getPropertyValue(property));
960
+ }
961
+ return prefix + properties.join(';') + suffix;
962
+ }
963
+ };
964
+ this.rules[0].natives.push(this.variablesNativeRules[theme] = nativeRule);
965
+ return nativeRule;
966
+ }
967
+ }
968
+ const masterCSSs = [];
969
+ (()=>{
970
+ globalThis.MasterCSS = MasterCSS;
971
+ globalThis.masterCSSs = masterCSSs;
972
+ })();
973
+
974
+ export { MasterCSS as default, masterCSSs };