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

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