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