@master/css-runtime 2.0.0-rc.5 → 2.0.0-rc.50

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,415 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var css = require('@master/css');
6
+
7
+ class RuntimeCSS extends css.MasterCSS {
8
+ root;
9
+ customConfig;
10
+ // @ts-expect-error
11
+ host;
12
+ observing;
13
+ progressive;
14
+ // @ts-expect-error
15
+ container;
16
+ observer;
17
+ constructor(root = document, customConfig = css.config){
18
+ super(customConfig), this.root = root, this.customConfig = customConfig, this.observing = false, this.progressive = false;
19
+ this.init();
20
+ }
21
+ init() {
22
+ const existingRuntimeCSS = globalThis.runtimeCSSs.find((eachCSS)=>eachCSS.root === this.root);
23
+ if (existingRuntimeCSS) throw new Error('Cannot create multiple RuntimeCSS instances for the same root element.');
24
+ const rootConstructorName = this.root?.constructor.name;
25
+ if (rootConstructorName === 'HTMLDocument' || rootConstructorName === 'Document') {
26
+ // @ts-ignore
27
+ this.root.defaultView.globalThis.runtimeCSS = this;
28
+ // @ts-ignore readonly
29
+ this.container = this.root.head;
30
+ // @ts-ignore readonly
31
+ this.host = this.root.documentElement;
32
+ } else {
33
+ // @ts-ignore readonly
34
+ this.container = this.root;
35
+ // @ts-ignore readonly
36
+ this.host = this.root.host;
37
+ }
38
+ runtimeCSSs.push(this);
39
+ }
40
+ /**
41
+ * Observe the DOM for changes and update the running stylesheet. (browser only)
42
+ * @param options mutation observer options
43
+ * @returns this
44
+ */ observe() {
45
+ if (this.observing) return this;
46
+ if (this.root.styleSheets) for (const sheet of this.root.styleSheets){
47
+ const { ownerNode } = sheet;
48
+ if (ownerNode && ownerNode.id === 'master') {
49
+ this.style = ownerNode;
50
+ // @ts-ignore
51
+ this.progressive = true;
52
+ break;
53
+ }
54
+ }
55
+ if (this.progressive) {
56
+ this.hydrate(this.style.sheet.cssRules);
57
+ } else {
58
+ this.style = document.createElement('style');
59
+ this.style.id = 'master';
60
+ this.container.append(this.style);
61
+ this.style.sheet.insertRule(this.layerStatementRule.text);
62
+ this.layerStatementRule.nodes[0].native = this.style.sheet.cssRules.item(0);
63
+ }
64
+ const firstConnectedElementsClasses = new Map();
65
+ const addClasses = (element)=>{
66
+ element.classList.forEach((className)=>{
67
+ if (this.classUsages.has(className)) {
68
+ this.classUsages.set(className, this.classUsages.get(className) + 1);
69
+ } else {
70
+ this.classUsages.set(className, 1);
71
+ this.add(className);
72
+ }
73
+ const classes = firstConnectedElementsClasses.get(element);
74
+ if (classes) {
75
+ classes.push(className);
76
+ } else {
77
+ firstConnectedElementsClasses.set(element, [
78
+ className
79
+ ]);
80
+ }
81
+ });
82
+ };
83
+ addClasses(this.host);
84
+ /**
85
+ * 待所有 DOM 結構完成解析後,開始繪製 Rule 樣式
86
+ */ (this.root.constructor.name === 'HTMLDocument' ? this.host : this.container).querySelectorAll('[class]').forEach((element)=>{
87
+ addClasses(element);
88
+ });
89
+ // @ts-expect-error readonly
90
+ this.observer = new MutationObserver((mutationRecords)=>{
91
+ // console.clear()
92
+ // console.log('-----------')
93
+ // const test = 'swiper-slide-next'
94
+ // console.log(`${test}: ${this.classUsages.get(test)}`)
95
+ const eachClassUsages = new Map();
96
+ const updatedAttrElements = new Set();
97
+ const updatedConnectedElements = new Set();
98
+ const updatedElements = new Set();
99
+ const updateClassUsage = (classes, isAdding = false)=>{
100
+ const usage = isAdding ? 1 : -1;
101
+ classes.forEach((className)=>{
102
+ // if (className === test) console.log(` ${isAdding ? '+' : '-'} ${className} ${(eachClassUsages.get(className) || 0) + usage}`, target)
103
+ eachClassUsages.set(className, (eachClassUsages.get(className) || 0) + usage);
104
+ });
105
+ };
106
+ const updateElementTree = (element, adding)=>{
107
+ if (element.isConnected) {
108
+ updatedConnectedElements.add(element);
109
+ }
110
+ updatedElements.add(element);
111
+ updateClassUsage(element.classList, adding);
112
+ for (const child of element.children){
113
+ updateElementTree(child, adding);
114
+ }
115
+ };
116
+ // console.log('///')
117
+ mutationRecords.forEach((mutation)=>{
118
+ const target = mutation.target;
119
+ switch(mutation.type){
120
+ case 'attributes':
121
+ const oldClassList = mutation.oldValue ? mutation.oldValue.split(/\s+/) : [];
122
+ const newClassList = target.classList;
123
+ newClassList.forEach((c)=>{
124
+ if (!oldClassList.includes(c)) ;
125
+ });
126
+ break;
127
+ }
128
+ });
129
+ // console.log('///')
130
+ mutationRecords.forEach((mutation)=>{
131
+ const target = mutation.target;
132
+ switch(mutation.type){
133
+ case 'attributes':
134
+ /**
135
+ * We only need to determine the first attribute record of the same target,
136
+ * because the first record has the original old class name.
137
+ *
138
+ * The target is skipped if it is contained in the unhandled childList.
139
+ */ if (updatedAttrElements.has(target) || updatedElements.has(target)) return;
140
+ updatedAttrElements.add(target);
141
+ const oldClassList = mutation.oldValue ? mutation.oldValue.split(/\s+/) : [];
142
+ const newClassList = target.classList;
143
+ const addedClasses = [];
144
+ newClassList.forEach((c)=>{
145
+ if (!oldClassList.includes(c)) addedClasses.push(c);
146
+ });
147
+ const removedClasses = oldClassList.filter((c)=>!newClassList.contains(c));
148
+ // if (addedClasses.length) console.log('[attribute]', '[add]', addedClasses, target)
149
+ if (addedClasses.length) updateClassUsage(addedClasses, true);
150
+ // if (removedClasses.length) console.log('[attribute]', '[remove]', removedClasses, target)
151
+ if (removedClasses.length) updateClassUsage(removedClasses, false);
152
+ break;
153
+ case 'childList':
154
+ if (updatedConnectedElements.has(target)) return;
155
+ // if (mutation.addedNodes.length) console.log('[childList]', '[add]', mutation.addedNodes)
156
+ mutation.addedNodes.forEach((node)=>'classList' in node && updateElementTree(node, true));
157
+ // if (mutation.removedNodes.length) console.log('[childList]', '[remove]', mutation.removedNodes)
158
+ mutation.removedNodes.forEach((node)=>'classList' in node && updateElementTree(node, false));
159
+ break;
160
+ }
161
+ });
162
+ /**
163
+ * Merge the class usage changes into the current class usage map.
164
+ */ eachClassUsages.forEach((countChange, className)=>{
165
+ let currentCount = this.classUsages.get(className) || 0;
166
+ let newCount = currentCount + countChange;
167
+ if (newCount > 0) {
168
+ this.classUsages.set(className, newCount);
169
+ if (currentCount === 0) {
170
+ this.add(className);
171
+ }
172
+ } else {
173
+ this.classUsages.delete(className);
174
+ this.remove(className);
175
+ }
176
+ });
177
+ // start: debug
178
+ // const safeClassUsages: any = {};
179
+ // ((this.root.constructor.name === 'HTMLDocument') ? this.host : this.container)
180
+ // .querySelectorAll('[class]')
181
+ // .forEach((element) => {
182
+ // element.classList.forEach((className) => {
183
+ // if (Object.prototype.hasOwnProperty.call(safeClassUsages, className)) {
184
+ // safeClassUsages[className]++
185
+ // } else {
186
+ // safeClassUsages[className] = 1
187
+ // }
188
+ // })
189
+ // })
190
+ // this.host.classList.forEach((className) => {
191
+ // if (Object.prototype.hasOwnProperty.call(safeClassUsages, className)) {
192
+ // safeClassUsages[className]++
193
+ // } else {
194
+ // safeClassUsages[className] = 1
195
+ // }
196
+ // })
197
+ // // 與 this.classUsages 比較並且打印不同的部分
198
+ // for (const className in safeClassUsages) {
199
+ // if (this.classUsages.get(className) !== safeClassUsages[className]) {
200
+ // throw new Error(`[css] ${className} ${this.classUsages.get(className)} (correct: ${safeClassUsages[className]})`)
201
+ // }
202
+ // }
203
+ // end: debug
204
+ });
205
+ this.observer.observe(this.root, {
206
+ attributes: true,
207
+ attributeOldValue: true,
208
+ attributeFilter: [
209
+ 'class'
210
+ ],
211
+ childList: true,
212
+ subtree: true
213
+ });
214
+ if (!this.progressive) {
215
+ this.host.style.removeProperty('display');
216
+ }
217
+ // @ts-ignore
218
+ this.observing = true;
219
+ return this;
220
+ }
221
+ hydrate(nativeCSSRules) {
222
+ const cssSyntaxLayerBlockRules = [];
223
+ for(let i = 0; i < nativeCSSRules.length; i++){
224
+ const eachNativeCSSRule = nativeCSSRules[i];
225
+ if (eachNativeCSSRule.constructor.name === 'CSSLayerBlockRule') {
226
+ const cssLayerBlockRule = eachNativeCSSRule;
227
+ if (eachNativeCSSRule.name === 'theme') {
228
+ this.themeLayer.native = cssLayerBlockRule;
229
+ let variableRule;
230
+ let lastVariableName;
231
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
232
+ const cssRule = cssLayerBlockRule.cssRules[j];
233
+ const variableCSSRule = cssRule.constructor.name === 'CSSMediaRule' ? cssRule.cssRules[0] : cssRule;
234
+ const variableName = variableCSSRule.style[0].slice(2);
235
+ if (variableName !== lastVariableName) {
236
+ lastVariableName = variableName;
237
+ variableRule = new css.Rule(variableName);
238
+ this.themeLayer.rules.push(variableRule);
239
+ this.themeLayer.usages[variableRule.name] = 0;
240
+ }
241
+ variableRule?.nodes.push({
242
+ native: cssRule,
243
+ text: cssRule.cssText
244
+ });
245
+ }
246
+ if (this.themeLayer.rules.length) this.rules.push(this.themeLayer);
247
+ } else {
248
+ cssSyntaxLayerBlockRules.push(cssLayerBlockRule);
249
+ }
250
+ } else if (eachNativeCSSRule.constructor.name === 'CSSLayerStatementRule') {
251
+ this.layerStatementRule.nodes[0].native = eachNativeCSSRule;
252
+ } else if (eachNativeCSSRule.constructor.name === 'CSSKeyframesRule') {
253
+ const keyframsRule = eachNativeCSSRule;
254
+ const animationRule = new css.Rule(keyframsRule.name, [
255
+ {
256
+ native: keyframsRule,
257
+ text: keyframsRule.cssText
258
+ }
259
+ ]);
260
+ this.animationsNonLayer.rules.push(animationRule);
261
+ this.rules.push(animationRule);
262
+ this.animationsNonLayer.usages[animationRule.name] = 0;
263
+ }
264
+ }
265
+ for (const cssLayerBlockRule of cssSyntaxLayerBlockRules){
266
+ const handleSyntaxLayer = (layer)=>{
267
+ layer.native = cssLayerBlockRule;
268
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
269
+ const cssRule = cssLayerBlockRule.cssRules[j];
270
+ const createSyntaxRule = (cssRule)=>{
271
+ if (cssRule.selectorText) {
272
+ const syntaxRule = this.createFromSelectorText(cssRule.selectorText)[0];
273
+ if (syntaxRule) return syntaxRule;
274
+ } else if (cssRule.cssRules) {
275
+ for (const eachCSSRule of cssRule.cssRules){
276
+ const syntaxRule = createSyntaxRule(eachCSSRule);
277
+ if (syntaxRule) return syntaxRule;
278
+ }
279
+ }
280
+ };
281
+ const syntaxRule = createSyntaxRule(cssRule);
282
+ if (syntaxRule) {
283
+ layer.rules.push(syntaxRule);
284
+ layer.insertVariables(syntaxRule);
285
+ layer.insertAnimations(syntaxRule);
286
+ for (const eachNode of syntaxRule.nodes){
287
+ if (!eachNode.native) eachNode.native = cssRule;
288
+ }
289
+ } else {
290
+ cssLayerBlockRule.deleteRule?.(j--);
291
+ console.error(`Cannot recognize the CSS rule in the ${layer.name} layer. \`${cssRule.cssText}\` (https://rc.css.master.co/messages/hydration-errors)`);
292
+ }
293
+ }
294
+ for (const eachRule of layer.rules){
295
+ for(let k = eachRule.nodes.length - 1; k >= 0; k--){
296
+ if (!eachRule.nodes[k].native) {
297
+ eachRule.nodes.splice(k, 1);
298
+ }
299
+ }
300
+ }
301
+ if (layer.rules.length) this.rules.push(layer);
302
+ };
303
+ switch(cssLayerBlockRule.name){
304
+ case 'base':
305
+ handleSyntaxLayer(this.baseLayer);
306
+ break;
307
+ case 'preset':
308
+ handleSyntaxLayer(this.presetLayer);
309
+ break;
310
+ case 'components':
311
+ this.componentsLayer.native = cssLayerBlockRule;
312
+ let stylePreText;
313
+ const createSyntaxRules = (cssRule)=>{
314
+ if (cssRule.selectorText) {
315
+ const syntaxRules = this.createFromSelectorText(cssRule.selectorText);
316
+ if (syntaxRules.length) {
317
+ stylePreText = cssRule.selectorText + '{';
318
+ return syntaxRules;
319
+ }
320
+ } else if (cssRule.cssRules) {
321
+ for (const eachCSSRule of cssRule.cssRules){
322
+ const syntaxRules = this.createFromSelectorText(eachCSSRule.selectorText);
323
+ if (syntaxRules) return syntaxRules;
324
+ }
325
+ }
326
+ };
327
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
328
+ const cssRule = cssLayerBlockRule.cssRules[j];
329
+ const syntaxRules = createSyntaxRules(cssRule);
330
+ if (syntaxRules) {
331
+ let matched = false;
332
+ for (const eachSyntaxRule of syntaxRules){
333
+ for (const node of eachSyntaxRule.nodes){
334
+ if (!node.native && node.text.includes(stylePreText)) {
335
+ node.native = cssRule;
336
+ if (!this.componentsLayer.rules.includes(eachSyntaxRule)) {
337
+ this.componentsLayer.rules.push(eachSyntaxRule);
338
+ this.componentsLayer.insertVariables(eachSyntaxRule);
339
+ this.componentsLayer.insertAnimations(eachSyntaxRule);
340
+ }
341
+ matched = true;
342
+ break;
343
+ }
344
+ }
345
+ if (matched) break;
346
+ }
347
+ } else {
348
+ cssLayerBlockRule?.deleteRule?.(j--);
349
+ console.error(`Cannot recognize the CSS rule in the components layer. \`${cssRule.cssText}\` (https://rc.css.master.co/messages/hydration-errors)`);
350
+ }
351
+ }
352
+ for (const eachRule of this.componentsLayer.rules){
353
+ for(let k = eachRule.nodes.length - 1; k >= 0; k--){
354
+ if (!eachRule.nodes[k].native) {
355
+ eachRule.nodes.splice(k, 1);
356
+ }
357
+ }
358
+ }
359
+ if (this.componentsLayer.rules.length) this.rules.push(this.componentsLayer);
360
+ break;
361
+ case 'general':
362
+ handleSyntaxLayer(this.generalLayer);
363
+ break;
364
+ }
365
+ }
366
+ }
367
+ disconnect() {
368
+ if (!this.observing) return;
369
+ if (this.observer) {
370
+ this.observer.disconnect();
371
+ // @ts-expect-error readonly
372
+ this.observer = undefined;
373
+ }
374
+ // @ts-ignore
375
+ this.observing = false;
376
+ this.reset();
377
+ this.classUsages.clear();
378
+ if (!this.progressive) {
379
+ this.style?.remove();
380
+ this.style = null;
381
+ }
382
+ return this;
383
+ }
384
+ refresh(customConfig = this.customConfig) {
385
+ if (!this.observing || !this.style.sheet) return this;
386
+ for(let i = 1; i <= this.style.sheet.cssRules.length - 1; i++){
387
+ this.style.sheet.deleteRule(i);
388
+ }
389
+ super.refresh(customConfig);
390
+ return this;
391
+ }
392
+ destroy() {
393
+ this.disconnect();
394
+ runtimeCSSs.splice(runtimeCSSs.indexOf(this), 1);
395
+ return this;
396
+ }
397
+ }
398
+ const runtimeCSSs = [];
399
+ (()=>{
400
+ globalThis.RuntimeCSS = RuntimeCSS;
401
+ globalThis.runtimeCSSs = runtimeCSSs;
402
+ })();
403
+
404
+ /**
405
+ * Initialize a new RuntimeCSS instance and observe the target root
406
+ * @param config master css config
407
+ * @param targetRoot target root to observe
408
+ * @returns master css instance
409
+ */ function initCSSRuntime(config) {
410
+ return new RuntimeCSS(document, config).observe();
411
+ }
412
+
413
+ exports.RuntimeCSS = RuntimeCSS;
414
+ exports.default = RuntimeCSS;
415
+ exports.initCSSRuntime = initCSSRuntime;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { CSSRuntime, CSSRuntime as default } from './core';
1
+ export { RuntimeCSS, RuntimeCSS as default } from './core';
2
2
  export { default as initCSSRuntime } from './init-css-runtime';