@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.
package/dist/index.cjs ADDED
@@ -0,0 +1,505 @@
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
+ try {
64
+ const node = rule.nodes[i];
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, rule.nodes[i]);
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
+ this.supportVendors = new Set();
144
+ const styleDeclaration = document.documentElement.style;
145
+ if ('webkitTransform' in styleDeclaration) this.supportVendors.add('webkit');
146
+ if ('MozTransform' in styleDeclaration) this.supportVendors.add('moz');
147
+ if ('msTransform' in styleDeclaration) this.supportVendors.add('ms');
148
+ if ('OTransform' in styleDeclaration) this.supportVendors.add('o');
149
+ globalThis.CSSRuntime.instances.set(this.root, this);
150
+ __MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:created', {
151
+ cssRuntime: this
152
+ });
153
+ }
154
+ /**
155
+ * Observe the DOM for changes and update the running stylesheet. (browser only)
156
+ * @param options mutation observer options
157
+ * @returns this
158
+ */ observe() {
159
+ if (this.observing) return this;
160
+ // 1. Check if the stylesheet is progressive.
161
+ if (this.root.styleSheets) for (const sheet of this.root.styleSheets){
162
+ const { ownerNode } = sheet;
163
+ if (ownerNode && ownerNode.id === 'master') {
164
+ this.style = ownerNode;
165
+ // @ts-ignore
166
+ this.progressive = true;
167
+ break;
168
+ }
169
+ }
170
+ // 2. Count the classes in the host and its children.
171
+ const connectedNames = new Set();
172
+ const increaseClassCount = (className)=>{
173
+ const count = this.classCounts.get(className) || 0;
174
+ if (!count) {
175
+ connectedNames.add(className);
176
+ }
177
+ this.classCounts.set(className, count + 1);
178
+ };
179
+ this.host.classList.forEach(increaseClassCount);
180
+ (this.root.constructor.name === 'HTMLDocument' ? this.host : this.container).querySelectorAll('[class]').forEach((element)=>element.classList.forEach(increaseClassCount));
181
+ // 3. Hydrate the existing CSS rules or create a new one.
182
+ if (this.progressive) {
183
+ const hydrateResult = this.hydrate(this.style.sheet.cssRules);
184
+ // Add the connected class names that are not hydrated yet.
185
+ for (const eachConnectedName of connectedNames){
186
+ if (hydrateResult.allSyntaxRules.find((rule)=>(rule.fixedClass || rule.name) === eachConnectedName)) continue;
187
+ this.add(eachConnectedName);
188
+ }
189
+ } else {
190
+ this.style = document.createElement('style');
191
+ this.style.id = 'master';
192
+ this.container.append(this.style);
193
+ this.style.sheet.insertRule(this.layerStatementRule.text);
194
+ this.layerStatementRule.nodes[0].native = this.style.sheet.cssRules.item(0);
195
+ for (const eachConnectedName of connectedNames){
196
+ this.add(eachConnectedName);
197
+ }
198
+ }
199
+ // @ts-expect-error readonly
200
+ this.observer = new MutationObserver((mutationRecords)=>{
201
+ const eachClassCounts = new Map();
202
+ const targetFirstAttrMutationRecord = new Map();
203
+ const updateClassCount = (classes, isAdding = false)=>{
204
+ const usage = isAdding ? 1 : -1;
205
+ classes.forEach((className)=>{
206
+ eachClassCounts.set(className, (eachClassCounts.get(className) || 0) + usage);
207
+ });
208
+ };
209
+ const connectedStatusMap = new Map();
210
+ const disconnectedStatusMap = new Map();
211
+ const recordStatus = (target, mutationRecord, map, adding)=>{
212
+ const status = map.get(target);
213
+ if (status) {
214
+ status.change += adding ? 1 : -1;
215
+ status.mutationRecord = mutationRecord;
216
+ } else {
217
+ map.set(target, {
218
+ change: adding ? 1 : -1,
219
+ mutationRecord
220
+ });
221
+ }
222
+ for (const child of target.children){
223
+ if ('classList' in child) {
224
+ recordStatus(child, mutationRecord, map, adding);
225
+ }
226
+ }
227
+ };
228
+ mutationRecords.forEach((mutationRecord)=>{
229
+ const target = mutationRecord.target;
230
+ switch(mutationRecord.type){
231
+ case 'attributes':
232
+ if (!targetFirstAttrMutationRecord.has(target)) {
233
+ targetFirstAttrMutationRecord.set(target, mutationRecord);
234
+ }
235
+ break;
236
+ case 'childList':
237
+ const targetStatusMap = target.isConnected ? connectedStatusMap : disconnectedStatusMap;
238
+ mutationRecord.addedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, true));
239
+ mutationRecord.removedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, false));
240
+ break;
241
+ }
242
+ });
243
+ const updateTarget = (target, adding)=>{
244
+ const firstAttrMutationRecord = targetFirstAttrMutationRecord.get(target);
245
+ if (firstAttrMutationRecord) {
246
+ targetFirstAttrMutationRecord.delete(target);
247
+ }
248
+ if (adding) {
249
+ updateClassCount(target.classList, adding);
250
+ } else {
251
+ if (firstAttrMutationRecord) {
252
+ updateClassCount(firstAttrMutationRecord.oldValue ? firstAttrMutationRecord.oldValue.split(/\s+/) : [], adding);
253
+ } else {
254
+ updateClassCount(target.classList, adding);
255
+ }
256
+ disconnectedStatusMap.forEach((disconnectedTargetStatus, disconnectedTarget)=>{
257
+ if (disconnectedTargetStatus.mutationRecord.target === target && disconnectedTargetStatus.change !== 0) {
258
+ updateTarget(disconnectedTarget, disconnectedTargetStatus.change > 0);
259
+ }
260
+ });
261
+ }
262
+ };
263
+ connectedStatusMap.forEach(({ change }, target)=>change !== 0 && updateTarget(target, change > 0));
264
+ targetFirstAttrMutationRecord.forEach((mutation, target)=>{
265
+ if (!target.isConnected) return;
266
+ const oldClassList = mutation.oldValue ? mutation.oldValue.split(/\s+/) : [];
267
+ const newClassList = target.classList;
268
+ const addedClasses = [];
269
+ newClassList.forEach((c)=>{
270
+ if (!oldClassList.includes(c)) addedClasses.push(c);
271
+ });
272
+ const removedClasses = oldClassList.filter((c)=>!newClassList.contains(c));
273
+ if (addedClasses.length) {
274
+ updateClassCount(addedClasses, true);
275
+ }
276
+ if (removedClasses.length) {
277
+ updateClassCount(removedClasses, false);
278
+ }
279
+ });
280
+ /**
281
+ * Merge the class usage changes into the current class usage map.
282
+ */ eachClassCounts.forEach((countChange, className)=>{
283
+ let currentCount = this.classCounts.get(className) || 0;
284
+ let newCount = currentCount + countChange;
285
+ if (newCount > 0) {
286
+ this.classCounts.set(className, newCount);
287
+ if (currentCount === 0) {
288
+ this.add(className);
289
+ }
290
+ } else {
291
+ this.classCounts.delete(className);
292
+ this.remove(className);
293
+ }
294
+ });
295
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:mutated', {
296
+ records: mutationRecords,
297
+ classCounts: eachClassCounts,
298
+ cssRuntime: this
299
+ });
300
+ });
301
+ this.observer.observe(this.root, {
302
+ attributes: true,
303
+ attributeOldValue: true,
304
+ attributeFilter: [
305
+ 'class'
306
+ ],
307
+ childList: true,
308
+ subtree: true
309
+ });
310
+ if (!this.progressive) {
311
+ this.host.removeAttribute('hidden');
312
+ }
313
+ // @ts-ignore
314
+ this.observing = true;
315
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:observed', {
316
+ cssRuntime: this
317
+ });
318
+ return this;
319
+ }
320
+ hydrate(nativeLayerRules) {
321
+ const cssLayerRules = [];
322
+ const checkSheet = new CSSStyleSheet();
323
+ const result = {
324
+ allSyntaxRules: []
325
+ };
326
+ for(let i = 0; i < nativeLayerRules.length; i++){
327
+ const eachNativeCSSRule = nativeLayerRules[i];
328
+ if (eachNativeCSSRule.constructor.name === 'CSSLayerBlockRule') {
329
+ const eachCSSLayerRule = eachNativeCSSRule;
330
+ if (eachNativeCSSRule.name === 'theme') {
331
+ this.themeLayer.native = eachCSSLayerRule;
332
+ let variableRule;
333
+ let lastVariableName;
334
+ for(let j = 0; j < eachCSSLayerRule.cssRules.length; j++){
335
+ const cssRule = eachCSSLayerRule.cssRules[j];
336
+ const variableCSSRule = cssRule.constructor.name === 'CSSMediaRule' ? cssRule.cssRules[0] : cssRule;
337
+ const variableName = variableCSSRule.style[0].slice(2);
338
+ if (variableName !== lastVariableName) {
339
+ lastVariableName = variableName;
340
+ variableRule = new css.Rule(variableName);
341
+ this.themeLayer.rules.push(variableRule);
342
+ this.themeLayer.tokenCounts.set(variableRule.name, 0);
343
+ }
344
+ variableRule?.nodes.push({
345
+ native: cssRule,
346
+ text: cssRule.cssText
347
+ });
348
+ }
349
+ if (this.themeLayer.rules.length) this.rules.push(this.themeLayer);
350
+ } else {
351
+ cssLayerRules.push(eachCSSLayerRule);
352
+ }
353
+ } else if (eachNativeCSSRule.constructor.name === 'CSSLayerStatementRule') {
354
+ this.layerStatementRule.nodes[0].native = eachNativeCSSRule;
355
+ } else if (eachNativeCSSRule.constructor.name === 'CSSKeyframesRule') {
356
+ const keyframsRule = eachNativeCSSRule;
357
+ const animationRule = new css.Rule(keyframsRule.name, [
358
+ {
359
+ native: keyframsRule,
360
+ text: keyframsRule.cssText
361
+ }
362
+ ]);
363
+ this.animationsNonLayer.rules.push(animationRule);
364
+ this.rules.push(animationRule);
365
+ this.animationsNonLayer.tokenCounts.set(animationRule.name, 0);
366
+ }
367
+ }
368
+ for (const eachCSSLayerRule of cssLayerRules){
369
+ let layer;
370
+ switch(eachCSSLayerRule.name){
371
+ case 'base':
372
+ layer = this.baseLayer;
373
+ break;
374
+ case 'preset':
375
+ layer = this.presetLayer;
376
+ break;
377
+ case 'components':
378
+ layer = this.componentsLayer;
379
+ break;
380
+ case 'general':
381
+ layer = this.generalLayer;
382
+ break;
383
+ default:
384
+ console.error(`Cannot recognize the layer \`${eachCSSLayerRule.name}\`. (https://rc.css.master.co/messages/hydration-errors)`);
385
+ continue;
386
+ }
387
+ layer.native = eachCSSLayerRule;
388
+ const unresolvedCSSRules = new Map();
389
+ for (const rule of eachCSSLayerRule.cssRules){
390
+ unresolvedCSSRules.set(rule.cssText, rule);
391
+ }
392
+ for (const eachNativeLayerRule of eachCSSLayerRule.cssRules){
393
+ if (!unresolvedCSSRules.has(eachNativeLayerRule.cssText)) continue;
394
+ const selectorText = this.getSelectorText(eachNativeLayerRule);
395
+ if (!selectorText) {
396
+ console.error(`Cannot get the selector text from \`${eachNativeLayerRule.cssText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
397
+ continue;
398
+ }
399
+ const createdRules = this.createFromSelectorText(selectorText);
400
+ if (createdRules) {
401
+ for (const createdRule of createdRules){
402
+ layer.rules.push(createdRule);
403
+ layer.insertVariables(createdRule);
404
+ layer.insertAnimations(createdRule);
405
+ result.allSyntaxRules.push(createdRule);
406
+ createdRule.nodes.forEach((node)=>{
407
+ const createdNodeNativeRule = checkSheet.cssRules.item(checkSheet.insertRule(node.text));
408
+ if (createdNodeNativeRule) {
409
+ const match = unresolvedCSSRules.get(createdNodeNativeRule.cssText);
410
+ if (match) {
411
+ node.native = match;
412
+ unresolvedCSSRules.delete(createdNodeNativeRule.cssText);
413
+ return;
414
+ }
415
+ }
416
+ console.error(`Cannot retrieve CSS rule for \`${node.selectorText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
417
+ });
418
+ }
419
+ } else {
420
+ console.error(`Cannot recognize \`${eachNativeLayerRule.cssText}\`. (${layer.name}) (https://rc.css.master.co/messages/hydration-errors)`);
421
+ }
422
+ }
423
+ if (layer.rules.length) this.rules.push(layer);
424
+ }
425
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:hydrated', {
426
+ cssRuntime: this,
427
+ result
428
+ });
429
+ return result;
430
+ }
431
+ getSelectorText(cssRule) {
432
+ if (cssRule instanceof CSSStyleRule) {
433
+ return cssRule.selectorText;
434
+ } else if (cssRule instanceof CSSGroupingRule) {
435
+ return this.getSelectorText(cssRule.cssRules.item(0));
436
+ }
437
+ }
438
+ disconnect() {
439
+ if (!this.observing) return;
440
+ if (this.observer) {
441
+ this.observer.disconnect();
442
+ // @ts-expect-error readonly
443
+ this.observer = undefined;
444
+ }
445
+ // @ts-ignore
446
+ this.observing = false;
447
+ this.reset();
448
+ this.classCounts.clear();
449
+ if (!this.progressive) {
450
+ this.style?.remove();
451
+ this.style = null;
452
+ }
453
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:disconnected', {
454
+ cssRuntime: this
455
+ });
456
+ return this;
457
+ }
458
+ refresh(customConfig = this.customConfig) {
459
+ if (!this.observing || !this.style.sheet) return this;
460
+ for(let i = 1; i <= this.style.sheet.cssRules.length - 1; i++){
461
+ this.style.sheet.deleteRule(i);
462
+ }
463
+ super.refresh(customConfig);
464
+ /**
465
+ * 拿當前所有的 classNames 按照最新的 colors, config.rules 匹配並生成新的 style
466
+ * 所以 refresh 過後 rules 可能會變多也可能會變少
467
+ */ this.classCounts.forEach((_, className)=>{
468
+ this.add(className);
469
+ });
470
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:refreshed', {
471
+ cssRuntime: this,
472
+ customConfig
473
+ });
474
+ return this;
475
+ }
476
+ destroy() {
477
+ this.disconnect();
478
+ globalThis.CSSRuntime.instances.delete(this.root);
479
+ globalThis.__MASTER_CSS_DEVTOOLS_HOOK__?.emit('runtime:destroyed', {
480
+ cssRuntime: this
481
+ });
482
+ return this;
483
+ }
484
+ }
485
+ (function(CSSRuntime) {
486
+ registerGlobal(CSSRuntime);
487
+ })(CSSRuntime);
488
+
489
+ /**
490
+ * Initialize a new CSSRuntime instance and observe the target root
491
+ * @param config master css config
492
+ * @param root target root to observe
493
+ * @param autoObserve auto observe the target root
494
+ * @returns master css instance
495
+ */ function initCSSRuntime(config, root = document, autoObserve = true) {
496
+ let cssRuntime = globalThis.CSSRuntime.instances.get(root);
497
+ if (cssRuntime) return cssRuntime;
498
+ cssRuntime = new CSSRuntime(root, config);
499
+ if (autoObserve) cssRuntime.observe();
500
+ return cssRuntime;
501
+ }
502
+
503
+ exports.CSSRuntime = CSSRuntime;
504
+ exports.default = CSSRuntime;
505
+ exports.initCSSRuntime = initCSSRuntime;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
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 type * from './types';
4
+ export type * from './syntax-layer';