@master/css-runtime 2.0.0-rc.6 → 2.0.0-rc.60

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.
@@ -0,0 +1,595 @@
1
+ import { Layer, withSyntaxLayer, MasterCSS, config, Rule } from '@master/css';
2
+ import { installHook } from '@master/css-devtools-hook';
3
+
4
+ const createLogger = (type)=>{
5
+ return (message, ...args)=>{
6
+ if (!type) return console.log(message, ...args);
7
+ if (console[type]) {
8
+ console[type](`%c[Master CSS]%c ${message}`, 'color: gray;', 'color: inherit;', ...args);
9
+ }
10
+ };
11
+ };
12
+ const loggers = {
13
+ info: createLogger('info'),
14
+ debug: createLogger('debug'),
15
+ warn: console.warn,
16
+ error: console.error,
17
+ trace: console.trace,
18
+ table: console.table,
19
+ group: console.group,
20
+ groupCollapsed: console.group,
21
+ groupEnd: console.groupEnd,
22
+ time: console.time,
23
+ timeEnd: console.timeEnd
24
+ };
25
+ const log = createLogger();
26
+ Object.assign(log, loggers);
27
+
28
+ function registerClassCountDebugger() {
29
+ const hook = globalThis.__MASTER_CSS_DEVTOOLS_HOOK__;
30
+ hook.on('runtime:mutated', ({ records, classCounts, cssRuntime })=>{
31
+ const actualClassCounts = {};
32
+ let errored = false;
33
+ const resolveClass = (className)=>{
34
+ if (Object.prototype.hasOwnProperty.call(actualClassCounts, className)) {
35
+ actualClassCounts[className]++;
36
+ } else {
37
+ actualClassCounts[className] = 1;
38
+ }
39
+ };
40
+ (cssRuntime.root.constructor.name === 'HTMLDocument' ? cssRuntime.host : cssRuntime.container).querySelectorAll('[class]').forEach((element)=>{
41
+ element.classList.forEach(resolveClass);
42
+ });
43
+ cssRuntime.host.classList.forEach(resolveClass);
44
+ for(const className in actualClassCounts){
45
+ const eachCount = cssRuntime.classCounts.get(className);
46
+ const eachActualCount = actualClassCounts[className];
47
+ if (eachCount !== eachActualCount) {
48
+ log.error(`Class count mismatch for '${className}' (expected ${eachActualCount}) (received ${eachCount})`);
49
+ errored = true;
50
+ }
51
+ }
52
+ cssRuntime.classCounts.forEach((eachCount, className)=>{
53
+ if (!Object.prototype.hasOwnProperty.call(actualClassCounts, className)) {
54
+ log.error(`Class count mismatch for '${className}' (expected ${0}) (received ${eachCount})`);
55
+ errored = true;
56
+ }
57
+ });
58
+ if (errored) {
59
+ log.debug('Records:', records);
60
+ log.debug('Counts:', classCounts);
61
+ }
62
+ });
63
+ }
64
+
65
+ function registerLifecycleDebugger() {
66
+ const hook = globalThis.__MASTER_CSS_DEVTOOLS_HOOK__;
67
+ hook.on('runtime:created', ({ cssRuntime })=>{
68
+ log.debug('Runtime created:', cssRuntime);
69
+ });
70
+ hook.on('runtime:hydrated', ({ cssRuntime })=>{
71
+ log.debug('Runtime hydrated:', cssRuntime);
72
+ });
73
+ hook.on('runtime:observed', ({ cssRuntime })=>{
74
+ log.debug('Runtime observed:', cssRuntime);
75
+ });
76
+ hook.on('runtime:refreshed', ({ cssRuntime, customConfig })=>{
77
+ log.debug('Runtime refreshed:', cssRuntime, customConfig);
78
+ });
79
+ hook.on('runtime:disconnected', ({ cssRuntime })=>{
80
+ log.debug('Runtime disconnected:', cssRuntime);
81
+ });
82
+ hook.on('runtime:destroyed', ({ cssRuntime })=>{
83
+ log.debug('Runtime destroyed:', cssRuntime);
84
+ });
85
+ }
86
+
87
+ function startDebuggers() {
88
+ log.info('Debug mode is enabled by default in development.');
89
+ registerClassCountDebugger();
90
+ registerLifecycleDebugger();
91
+ }
92
+
93
+ function registerGlobal(CSSRuntime) {
94
+ if (!globalThis.CSSRuntime) globalThis.CSSRuntime = CSSRuntime;
95
+ installHook();
96
+ {
97
+ startDebuggers();
98
+ }
99
+ }
100
+
101
+ function findNativeCSSRuleIndex(cssRules, nativeRule) {
102
+ for(let i = 0; i < cssRules.length; i++){
103
+ if (cssRules[i] === nativeRule) {
104
+ return i;
105
+ }
106
+ }
107
+ return -1;
108
+ }
109
+
110
+ class RuntimeLayer extends Layer {
111
+ name;
112
+ cssRuntime;
113
+ rules;
114
+ tokenCounts;
115
+ native;
116
+ constructor(name, cssRuntime){
117
+ super(name, cssRuntime), this.name = name, this.cssRuntime = cssRuntime, this.rules = [], this.tokenCounts = new Map(), this.native = null;
118
+ }
119
+ attach() {
120
+ super.attach();
121
+ const nativeSheet = this.cssRuntime.style?.sheet;
122
+ if (nativeSheet && !this.native?.parentStyleSheet) {
123
+ const insertedIndex = nativeSheet.insertRule(this.text, nativeSheet.cssRules.length);
124
+ this.native = nativeSheet.cssRules.item(insertedIndex);
125
+ }
126
+ }
127
+ insert(rule, index = this.rules.length) {
128
+ const insertedIndex = super.insert(rule, index);
129
+ if (insertedIndex === undefined) return;
130
+ if (this.native) {
131
+ let cssRuleIndex = 0;
132
+ const lastCssRule = function getLastCssRule(layer, index) {
133
+ let lastCssRule;
134
+ const previouRule = layer.rules[index];
135
+ if (previouRule && 'nodes' in previouRule) {
136
+ if (!previouRule.nodes.length) return getLastCssRule(layer, index - 1);
137
+ const lastNativeRule = previouRule.nodes[previouRule.nodes.length - 1];
138
+ lastCssRule = lastNativeRule.native;
139
+ }
140
+ return lastCssRule;
141
+ }(this, insertedIndex - 1);
142
+ if (lastCssRule) {
143
+ for(let i = 0; i < this.native.cssRules.length; i++){
144
+ if (this.native.cssRules[i] === lastCssRule) {
145
+ cssRuleIndex = i + 1;
146
+ break;
147
+ }
148
+ }
149
+ }
150
+ for(let i = 0; i < rule.nodes.length;){
151
+ try {
152
+ const node = rule.nodes[i];
153
+ const insertedIndex = this.native.insertRule(node.text, cssRuleIndex);
154
+ node.native = this.native.cssRules.item(insertedIndex);
155
+ cssRuleIndex++;
156
+ i++;
157
+ } catch (error) {
158
+ console.error(error, rule.nodes[i]);
159
+ rule.nodes.splice(i, 1);
160
+ }
161
+ }
162
+ }
163
+ return insertedIndex;
164
+ }
165
+ detach() {
166
+ const nativeSheet = this.cssRuntime.style?.sheet;
167
+ if (nativeSheet && this.native?.parentStyleSheet) {
168
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
169
+ if (foundIndex !== -1) {
170
+ nativeSheet.deleteRule(foundIndex);
171
+ }
172
+ }
173
+ }
174
+ delete(key) {
175
+ const deletedRule = super.delete(key);
176
+ if (!deletedRule) return;
177
+ if (this.native?.cssRules && 'nodes' in deletedRule) {
178
+ for (const node of deletedRule.nodes){
179
+ if (node.native) {
180
+ const foundIndex = findNativeCSSRuleIndex(this.native.cssRules, node.native);
181
+ if (foundIndex !== -1) {
182
+ // todo: Firefox throw "Uncaught NS_ERROR_FAILURE". Reproduce: Add '@fade|1s @fade|2s' and remove '@fade|1s @fade|2s'
183
+ this.native.deleteRule(foundIndex);
184
+ }
185
+ }
186
+ }
187
+ }
188
+ return deletedRule;
189
+ }
190
+ reset() {
191
+ super.reset();
192
+ const nativeSheet = this.cssRuntime.style?.sheet;
193
+ if (this.native && nativeSheet) {
194
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
195
+ if (foundIndex !== -1) {
196
+ nativeSheet.deleteRule(foundIndex);
197
+ }
198
+ this.native = null;
199
+ }
200
+ }
201
+ }
202
+
203
+ const RuntimeSyntaxLayer = withSyntaxLayer(RuntimeLayer);
204
+
205
+ class CSSRuntime extends MasterCSS {
206
+ root;
207
+ customConfig;
208
+ static instances = new WeakMap();
209
+ host;
210
+ observing;
211
+ progressive;
212
+ container;
213
+ observer;
214
+ baseLayer;
215
+ themeLayer;
216
+ presetLayer;
217
+ componentsLayer;
218
+ generalLayer;
219
+ classCounts;
220
+ constructor(root = document, customConfig = config){
221
+ super(customConfig), this.root = root, this.customConfig = customConfig, this.observing = false, this.progressive = false, this.baseLayer = new RuntimeSyntaxLayer('base', this), this.themeLayer = new RuntimeLayer('theme', this), this.presetLayer = new RuntimeSyntaxLayer('preset', this), this.componentsLayer = new RuntimeSyntaxLayer('components', this), this.generalLayer = new RuntimeSyntaxLayer('general', this), this.classCounts = new Map();
222
+ const rootConstructorName = root?.constructor.name;
223
+ if (rootConstructorName === 'HTMLDocument' || rootConstructorName === 'Document') {
224
+ this.root.defaultView.globalThis.cssRuntime = this;
225
+ this.container = this.root.head;
226
+ this.host = this.root.documentElement;
227
+ } else {
228
+ this.container = this.root;
229
+ this.host = this.root.host;
230
+ }
231
+ this.supportVendors = new Set();
232
+ const styleDeclaration = document.documentElement.style;
233
+ if ('webkitTransform' in styleDeclaration) this.supportVendors.add('webkit');
234
+ if ('MozTransform' in styleDeclaration) this.supportVendors.add('moz');
235
+ if ('msTransform' in styleDeclaration) this.supportVendors.add('ms');
236
+ if ('OTransform' in styleDeclaration) this.supportVendors.add('o');
237
+ globalThis.CSSRuntime.instances.set(this.root, this);
238
+ __MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:created', {
239
+ cssRuntime: this
240
+ });
241
+ }
242
+ /**
243
+ * Observe the DOM for changes and update the running stylesheet. (browser only)
244
+ * @param options mutation observer options
245
+ * @returns this
246
+ */ observe() {
247
+ if (this.observing) return this;
248
+ // 1. Check if the stylesheet is progressive.
249
+ if (this.root.styleSheets) for (const sheet of this.root.styleSheets){
250
+ const { ownerNode } = sheet;
251
+ if (ownerNode && ownerNode.id === 'master') {
252
+ this.style = ownerNode;
253
+ // @ts-ignore
254
+ this.progressive = true;
255
+ break;
256
+ }
257
+ }
258
+ // 2. Count the classes in the host and its children.
259
+ const connectedNames = new Set();
260
+ const increaseClassCount = (className)=>{
261
+ const count = this.classCounts.get(className) || 0;
262
+ if (!count) {
263
+ connectedNames.add(className);
264
+ }
265
+ this.classCounts.set(className, count + 1);
266
+ };
267
+ this.host.classList.forEach(increaseClassCount);
268
+ (this.root.constructor.name === 'HTMLDocument' ? this.host : this.container).querySelectorAll('[class]').forEach((element)=>element.classList.forEach(increaseClassCount));
269
+ // 3. Hydrate the existing CSS rules or create a new one.
270
+ if (this.progressive) {
271
+ const hydrateResult = this.hydrate(this.style.sheet.cssRules);
272
+ // Add the connected class names that are not hydrated yet.
273
+ for (const eachConnectedName of connectedNames){
274
+ if (hydrateResult.allSyntaxRules.find((rule)=>(rule.fixedClass || rule.name) === eachConnectedName)) continue;
275
+ this.add(eachConnectedName);
276
+ {
277
+ // Basically, the style#master should have all the prerendered CSS rules that are connected in the DOM.
278
+ console.debug(`The class \`${eachConnectedName}\` was added via script before calling hydrate, or the corresponding CSS rule were not properly pre-rendered.`);
279
+ }
280
+ }
281
+ } else {
282
+ this.style = document.createElement('style');
283
+ this.style.id = 'master';
284
+ this.container.append(this.style);
285
+ this.style.sheet.insertRule(this.layerStatementRule.text);
286
+ this.layerStatementRule.nodes[0].native = this.style.sheet.cssRules.item(0);
287
+ for (const eachConnectedName of connectedNames){
288
+ this.add(eachConnectedName);
289
+ }
290
+ }
291
+ // @ts-expect-error readonly
292
+ this.observer = new MutationObserver((mutationRecords)=>{
293
+ const eachClassCounts = new Map();
294
+ const targetFirstAttrMutationRecord = new Map();
295
+ const updateClassCount = (classes, isAdding = false)=>{
296
+ const usage = isAdding ? 1 : -1;
297
+ classes.forEach((className)=>{
298
+ eachClassCounts.set(className, (eachClassCounts.get(className) || 0) + usage);
299
+ });
300
+ };
301
+ const connectedStatusMap = new Map();
302
+ const disconnectedStatusMap = new Map();
303
+ const recordStatus = (target, mutationRecord, map, adding)=>{
304
+ const status = map.get(target);
305
+ if (status) {
306
+ status.change += adding ? 1 : -1;
307
+ status.mutationRecord = mutationRecord;
308
+ } else {
309
+ map.set(target, {
310
+ change: adding ? 1 : -1,
311
+ mutationRecord
312
+ });
313
+ }
314
+ for (const child of target.children){
315
+ if ('classList' in child) {
316
+ recordStatus(child, mutationRecord, map, adding);
317
+ }
318
+ }
319
+ };
320
+ mutationRecords.forEach((mutationRecord)=>{
321
+ const target = mutationRecord.target;
322
+ switch(mutationRecord.type){
323
+ case 'attributes':
324
+ if (!targetFirstAttrMutationRecord.has(target)) {
325
+ targetFirstAttrMutationRecord.set(target, mutationRecord);
326
+ }
327
+ break;
328
+ case 'childList':
329
+ const targetStatusMap = target.isConnected ? connectedStatusMap : disconnectedStatusMap;
330
+ mutationRecord.addedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, true));
331
+ mutationRecord.removedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, false));
332
+ break;
333
+ }
334
+ });
335
+ const updateTarget = (target, adding)=>{
336
+ const firstAttrMutationRecord = targetFirstAttrMutationRecord.get(target);
337
+ if (firstAttrMutationRecord) {
338
+ targetFirstAttrMutationRecord.delete(target);
339
+ }
340
+ if (adding) {
341
+ updateClassCount(target.classList, adding);
342
+ } else {
343
+ if (firstAttrMutationRecord) {
344
+ updateClassCount(firstAttrMutationRecord.oldValue ? firstAttrMutationRecord.oldValue.split(/\s+/) : [], adding);
345
+ } else {
346
+ updateClassCount(target.classList, adding);
347
+ }
348
+ disconnectedStatusMap.forEach((disconnectedTargetStatus, disconnectedTarget)=>{
349
+ if (disconnectedTargetStatus.mutationRecord.target === target && disconnectedTargetStatus.change !== 0) {
350
+ updateTarget(disconnectedTarget, disconnectedTargetStatus.change > 0);
351
+ }
352
+ });
353
+ }
354
+ };
355
+ connectedStatusMap.forEach(({ change }, target)=>change !== 0 && updateTarget(target, change > 0));
356
+ targetFirstAttrMutationRecord.forEach((mutation, target)=>{
357
+ if (!target.isConnected) return;
358
+ const oldClassList = mutation.oldValue ? mutation.oldValue.split(/\s+/) : [];
359
+ const newClassList = target.classList;
360
+ const addedClasses = [];
361
+ newClassList.forEach((c)=>{
362
+ if (!oldClassList.includes(c)) addedClasses.push(c);
363
+ });
364
+ const removedClasses = oldClassList.filter((c)=>!newClassList.contains(c));
365
+ if (addedClasses.length) {
366
+ updateClassCount(addedClasses, true);
367
+ }
368
+ if (removedClasses.length) {
369
+ updateClassCount(removedClasses, false);
370
+ }
371
+ });
372
+ /**
373
+ * Merge the class usage changes into the current class usage map.
374
+ */ eachClassCounts.forEach((countChange, className)=>{
375
+ let currentCount = this.classCounts.get(className) || 0;
376
+ let newCount = currentCount + countChange;
377
+ if (newCount > 0) {
378
+ this.classCounts.set(className, newCount);
379
+ if (currentCount === 0) {
380
+ this.add(className);
381
+ }
382
+ } else {
383
+ this.classCounts.delete(className);
384
+ this.remove(className);
385
+ }
386
+ });
387
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:mutated', {
388
+ records: mutationRecords,
389
+ classCounts: eachClassCounts,
390
+ cssRuntime: this
391
+ });
392
+ });
393
+ this.observer.observe(this.root, {
394
+ attributes: true,
395
+ attributeOldValue: true,
396
+ attributeFilter: [
397
+ 'class'
398
+ ],
399
+ childList: true,
400
+ subtree: true
401
+ });
402
+ if (!this.progressive) {
403
+ this.host.removeAttribute('hidden');
404
+ }
405
+ // @ts-ignore
406
+ this.observing = true;
407
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:observed', {
408
+ cssRuntime: this
409
+ });
410
+ return this;
411
+ }
412
+ hydrate(nativeLayerRules) {
413
+ const cssLayerRules = [];
414
+ const checkSheet = new CSSStyleSheet();
415
+ const result = {
416
+ allSyntaxRules: []
417
+ };
418
+ for(let i = 0; i < nativeLayerRules.length; i++){
419
+ const eachNativeCSSRule = nativeLayerRules[i];
420
+ if (eachNativeCSSRule.constructor.name === 'CSSLayerBlockRule') {
421
+ const eachCSSLayerRule = eachNativeCSSRule;
422
+ if (eachNativeCSSRule.name === 'theme') {
423
+ this.themeLayer.native = eachCSSLayerRule;
424
+ let variableRule;
425
+ let lastVariableName;
426
+ for(let j = 0; j < eachCSSLayerRule.cssRules.length; j++){
427
+ const cssRule = eachCSSLayerRule.cssRules[j];
428
+ const variableCSSRule = cssRule.constructor.name === 'CSSMediaRule' ? cssRule.cssRules[0] : cssRule;
429
+ const variableName = variableCSSRule.style[0].slice(2);
430
+ if (variableName !== lastVariableName) {
431
+ lastVariableName = variableName;
432
+ variableRule = new Rule(variableName);
433
+ this.themeLayer.rules.push(variableRule);
434
+ this.themeLayer.tokenCounts.set(variableRule.name, 0);
435
+ }
436
+ variableRule?.nodes.push({
437
+ native: cssRule,
438
+ text: cssRule.cssText
439
+ });
440
+ }
441
+ if (this.themeLayer.rules.length) this.rules.push(this.themeLayer);
442
+ } else {
443
+ cssLayerRules.push(eachCSSLayerRule);
444
+ }
445
+ } else if (eachNativeCSSRule.constructor.name === 'CSSLayerStatementRule') {
446
+ this.layerStatementRule.nodes[0].native = eachNativeCSSRule;
447
+ } else if (eachNativeCSSRule.constructor.name === 'CSSKeyframesRule') {
448
+ const keyframsRule = eachNativeCSSRule;
449
+ const animationRule = new Rule(keyframsRule.name, [
450
+ {
451
+ native: keyframsRule,
452
+ text: keyframsRule.cssText
453
+ }
454
+ ]);
455
+ this.animationsNonLayer.rules.push(animationRule);
456
+ this.rules.push(animationRule);
457
+ this.animationsNonLayer.tokenCounts.set(animationRule.name, 0);
458
+ }
459
+ }
460
+ for (const eachCSSLayerRule of cssLayerRules){
461
+ let layer;
462
+ switch(eachCSSLayerRule.name){
463
+ case 'base':
464
+ layer = this.baseLayer;
465
+ break;
466
+ case 'preset':
467
+ layer = this.presetLayer;
468
+ break;
469
+ case 'components':
470
+ layer = this.componentsLayer;
471
+ break;
472
+ case 'general':
473
+ layer = this.generalLayer;
474
+ break;
475
+ default:
476
+ console.error(`Cannot recognize the layer \`${eachCSSLayerRule.name}\`. (https://rc.css.master.co/messages/hydration-errors)`);
477
+ continue;
478
+ }
479
+ layer.native = eachCSSLayerRule;
480
+ const unresolvedCSSRules = new Map();
481
+ for (const rule of eachCSSLayerRule.cssRules){
482
+ unresolvedCSSRules.set(rule.cssText, rule);
483
+ }
484
+ for (const eachNativeLayerRule of eachCSSLayerRule.cssRules){
485
+ if (!unresolvedCSSRules.has(eachNativeLayerRule.cssText)) continue;
486
+ const selectorText = this.getSelectorText(eachNativeLayerRule);
487
+ if (!selectorText) {
488
+ console.error(`Cannot get the selector text from \`${eachNativeLayerRule.cssText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
489
+ continue;
490
+ }
491
+ const createdRules = this.createFromSelectorText(selectorText);
492
+ if (createdRules) {
493
+ for (const createdRule of createdRules){
494
+ layer.rules.push(createdRule);
495
+ layer.insertVariables(createdRule);
496
+ layer.insertAnimations(createdRule);
497
+ result.allSyntaxRules.push(createdRule);
498
+ createdRule.nodes.forEach((node)=>{
499
+ const createdNodeNativeRule = checkSheet.cssRules.item(checkSheet.insertRule(node.text));
500
+ if (createdNodeNativeRule) {
501
+ const match = unresolvedCSSRules.get(createdNodeNativeRule.cssText);
502
+ if (match) {
503
+ node.native = match;
504
+ unresolvedCSSRules.delete(createdNodeNativeRule.cssText);
505
+ return;
506
+ }
507
+ }
508
+ console.error(`Cannot retrieve CSS rule for \`${node.selectorText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
509
+ });
510
+ }
511
+ } else {
512
+ console.error(`Cannot recognize \`${eachNativeLayerRule.cssText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
513
+ }
514
+ }
515
+ if (layer.rules.length) this.rules.push(layer);
516
+ }
517
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:hydrated', {
518
+ cssRuntime: this,
519
+ result
520
+ });
521
+ return result;
522
+ }
523
+ getSelectorText(cssRule) {
524
+ if (cssRule instanceof CSSStyleRule) {
525
+ return cssRule.selectorText;
526
+ } else if (cssRule instanceof CSSGroupingRule) {
527
+ return this.getSelectorText(cssRule.cssRules.item(0));
528
+ }
529
+ }
530
+ disconnect() {
531
+ if (!this.observing) return;
532
+ if (this.observer) {
533
+ this.observer.disconnect();
534
+ // @ts-expect-error readonly
535
+ this.observer = undefined;
536
+ }
537
+ // @ts-ignore
538
+ this.observing = false;
539
+ this.reset();
540
+ this.classCounts.clear();
541
+ if (!this.progressive) {
542
+ this.style?.remove();
543
+ this.style = null;
544
+ }
545
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:disconnected', {
546
+ cssRuntime: this
547
+ });
548
+ return this;
549
+ }
550
+ refresh(customConfig = this.customConfig) {
551
+ if (!this.observing || !this.style.sheet) return this;
552
+ for(let i = 1; i <= this.style.sheet.cssRules.length - 1; i++){
553
+ this.style.sheet.deleteRule(i);
554
+ }
555
+ super.refresh(customConfig);
556
+ /**
557
+ * 拿當前所有的 classNames 按照最新的 colors, config.rules 匹配並生成新的 style
558
+ * 所以 refresh 過後 rules 可能會變多也可能會變少
559
+ */ this.classCounts.forEach((_, className)=>{
560
+ this.add(className);
561
+ });
562
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:refreshed', {
563
+ cssRuntime: this,
564
+ customConfig
565
+ });
566
+ return this;
567
+ }
568
+ destroy() {
569
+ this.disconnect();
570
+ globalThis.CSSRuntime.instances.delete(this.root);
571
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:destroyed', {
572
+ cssRuntime: this
573
+ });
574
+ return this;
575
+ }
576
+ }
577
+ (function(CSSRuntime) {
578
+ registerGlobal(CSSRuntime);
579
+ })(CSSRuntime);
580
+
581
+ /**
582
+ * Initialize a new CSSRuntime instance and observe the target root
583
+ * @param config master css config
584
+ * @param root target root to observe
585
+ * @param autoObserve auto observe the target root
586
+ * @returns master css instance
587
+ */ function initCSSRuntime(config, root = document, autoObserve = true) {
588
+ let cssRuntime = globalThis.CSSRuntime.instances.get(root);
589
+ if (cssRuntime) return cssRuntime;
590
+ cssRuntime = new CSSRuntime(root, config);
591
+ if (autoObserve) cssRuntime.observe();
592
+ return cssRuntime;
593
+ }
594
+
595
+ export { CSSRuntime, initCSSRuntime };