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

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,439 @@
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
+ // const test = ''
93
+ // if (test) {
94
+ // console.log('')
95
+ // console.log(`${test}: ${this.classUsages.get(test)}`)
96
+ // }
97
+ const eachClassUsages = new Map();
98
+ const targetFirstAttrMutationRecord = new Map();
99
+ const updateClassUsage = (classes, isAdding = false)=>{
100
+ const usage = isAdding ? 1 : -1;
101
+ classes.forEach((className)=>{
102
+ eachClassUsages.set(className, (eachClassUsages.get(className) || 0) + usage);
103
+ });
104
+ };
105
+ const connectedStatusMap = new Map();
106
+ const disconnectedStatusMap = new Map();
107
+ const recordStatus = (target, mutationRecord, map, adding)=>{
108
+ const status = map.get(target);
109
+ if (status) {
110
+ status.change += adding ? 1 : -1;
111
+ status.mutationRecord = mutationRecord;
112
+ } else {
113
+ map.set(target, {
114
+ change: adding ? 1 : -1,
115
+ mutationRecord
116
+ });
117
+ }
118
+ };
119
+ mutationRecords.forEach((mutationRecord)=>{
120
+ const target = mutationRecord.target;
121
+ switch(mutationRecord.type){
122
+ case 'attributes':
123
+ if (!targetFirstAttrMutationRecord.has(target)) {
124
+ targetFirstAttrMutationRecord.set(target, mutationRecord);
125
+ }
126
+ break;
127
+ case 'childList':
128
+ const targetStatusMap = target.isConnected ? connectedStatusMap : disconnectedStatusMap;
129
+ mutationRecord.addedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, true));
130
+ mutationRecord.removedNodes.forEach((node)=>'classList' in node && recordStatus(node, mutationRecord, targetStatusMap, false));
131
+ break;
132
+ }
133
+ });
134
+ const updatedTargetChangeMap = new Map();
135
+ const updateTarget = (target, adding)=>{
136
+ const change = updatedTargetChangeMap.get(target) || 0;
137
+ const newChange = change + (adding ? 1 : -1);
138
+ if (newChange >= -1 && newChange <= 1) {
139
+ updatedTargetChangeMap.set(target, newChange);
140
+ const firstAttrMutationRecord = targetFirstAttrMutationRecord.get(target);
141
+ if (firstAttrMutationRecord) {
142
+ targetFirstAttrMutationRecord.delete(target);
143
+ }
144
+ if (adding) {
145
+ updateClassUsage(target.classList, adding);
146
+ } else {
147
+ if (firstAttrMutationRecord) {
148
+ updateClassUsage(firstAttrMutationRecord.oldValue ? firstAttrMutationRecord.oldValue.split(/\s+/) : [], adding);
149
+ } else {
150
+ updateClassUsage(target.classList, adding);
151
+ }
152
+ disconnectedStatusMap.forEach((disconnectedTargetStatus, disconnectedTarget)=>{
153
+ if (disconnectedTargetStatus.mutationRecord.target === target && disconnectedTargetStatus.change !== 0) {
154
+ updateTarget(disconnectedTarget, disconnectedTargetStatus.change > 0);
155
+ }
156
+ });
157
+ }
158
+ for (const child of target.children){
159
+ updateTarget(child, adding);
160
+ }
161
+ }
162
+ };
163
+ connectedStatusMap.forEach(({ change }, target)=>change !== 0 && updateTarget(target, change > 0));
164
+ targetFirstAttrMutationRecord.forEach((mutation, target)=>{
165
+ if (!target.isConnected) return;
166
+ const oldClassList = mutation.oldValue ? mutation.oldValue.split(/\s+/) : [];
167
+ const newClassList = target.classList;
168
+ const addedClasses = [];
169
+ newClassList.forEach((c)=>{
170
+ if (!oldClassList.includes(c)) addedClasses.push(c);
171
+ });
172
+ const removedClasses = oldClassList.filter((c)=>!newClassList.contains(c));
173
+ if (addedClasses.length) {
174
+ // console.log('[attribute]', '[add] ', addedClasses, target)
175
+ updateClassUsage(addedClasses, true);
176
+ }
177
+ if (removedClasses.length) {
178
+ // console.log('[attribute]', '[remove]', removedClasses, target)
179
+ updateClassUsage(removedClasses, false);
180
+ }
181
+ });
182
+ /**
183
+ * Merge the class usage changes into the current class usage map.
184
+ */ eachClassUsages.forEach((countChange, className)=>{
185
+ let currentCount = this.classUsages.get(className) || 0;
186
+ let newCount = currentCount + countChange;
187
+ if (newCount > 0) {
188
+ this.classUsages.set(className, newCount);
189
+ if (currentCount === 0) {
190
+ this.add(className);
191
+ }
192
+ } else {
193
+ this.classUsages.delete(className);
194
+ this.remove(className);
195
+ }
196
+ });
197
+ // start: debug
198
+ // const safeClassUsages: any = {};
199
+ // ((this.root.constructor.name === 'HTMLDocument') ? this.host : this.container)
200
+ // .querySelectorAll('[class]')
201
+ // .forEach((element) => {
202
+ // element.classList.forEach((className) => {
203
+ // if (Object.prototype.hasOwnProperty.call(safeClassUsages, className)) {
204
+ // safeClassUsages[className]++
205
+ // } else {
206
+ // safeClassUsages[className] = 1
207
+ // }
208
+ // })
209
+ // })
210
+ // this.host.classList.forEach((className) => {
211
+ // if (Object.prototype.hasOwnProperty.call(safeClassUsages, className)) {
212
+ // safeClassUsages[className]++
213
+ // } else {
214
+ // safeClassUsages[className] = 1
215
+ // }
216
+ // })
217
+ // for (const className in safeClassUsages) {
218
+ // if (this.classUsages.get(className) !== safeClassUsages[className]) {
219
+ // throw new Error(`[css] ${className} ${this.classUsages.get(className)} (correct: ${safeClassUsages[className]})`)
220
+ // }
221
+ // }
222
+ // this.classUsages.forEach((count, className) => {
223
+ // if (!Object.prototype.hasOwnProperty.call(safeClassUsages, className)) {
224
+ // throw new Error(`[css] ${className} ${count} (correct: 0)`)
225
+ // }
226
+ // })
227
+ // end: debug
228
+ });
229
+ this.observer.observe(this.root, {
230
+ attributes: true,
231
+ attributeOldValue: true,
232
+ attributeFilter: [
233
+ 'class'
234
+ ],
235
+ childList: true,
236
+ subtree: true
237
+ });
238
+ if (!this.progressive) {
239
+ this.host.style.removeProperty('display');
240
+ }
241
+ // @ts-ignore
242
+ this.observing = true;
243
+ return this;
244
+ }
245
+ hydrate(nativeCSSRules) {
246
+ const cssSyntaxLayerBlockRules = [];
247
+ for(let i = 0; i < nativeCSSRules.length; i++){
248
+ const eachNativeCSSRule = nativeCSSRules[i];
249
+ if (eachNativeCSSRule.constructor.name === 'CSSLayerBlockRule') {
250
+ const cssLayerBlockRule = eachNativeCSSRule;
251
+ if (eachNativeCSSRule.name === 'theme') {
252
+ this.themeLayer.native = cssLayerBlockRule;
253
+ let variableRule;
254
+ let lastVariableName;
255
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
256
+ const cssRule = cssLayerBlockRule.cssRules[j];
257
+ const variableCSSRule = cssRule.constructor.name === 'CSSMediaRule' ? cssRule.cssRules[0] : cssRule;
258
+ const variableName = variableCSSRule.style[0].slice(2);
259
+ if (variableName !== lastVariableName) {
260
+ lastVariableName = variableName;
261
+ variableRule = new css.Rule(variableName);
262
+ this.themeLayer.rules.push(variableRule);
263
+ this.themeLayer.usages[variableRule.name] = 0;
264
+ }
265
+ variableRule?.nodes.push({
266
+ native: cssRule,
267
+ text: cssRule.cssText
268
+ });
269
+ }
270
+ if (this.themeLayer.rules.length) this.rules.push(this.themeLayer);
271
+ } else {
272
+ cssSyntaxLayerBlockRules.push(cssLayerBlockRule);
273
+ }
274
+ } else if (eachNativeCSSRule.constructor.name === 'CSSLayerStatementRule') {
275
+ this.layerStatementRule.nodes[0].native = eachNativeCSSRule;
276
+ } else if (eachNativeCSSRule.constructor.name === 'CSSKeyframesRule') {
277
+ const keyframsRule = eachNativeCSSRule;
278
+ const animationRule = new css.Rule(keyframsRule.name, [
279
+ {
280
+ native: keyframsRule,
281
+ text: keyframsRule.cssText
282
+ }
283
+ ]);
284
+ this.animationsNonLayer.rules.push(animationRule);
285
+ this.rules.push(animationRule);
286
+ this.animationsNonLayer.usages[animationRule.name] = 0;
287
+ }
288
+ }
289
+ for (const cssLayerBlockRule of cssSyntaxLayerBlockRules){
290
+ const handleSyntaxLayer = (layer)=>{
291
+ layer.native = cssLayerBlockRule;
292
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
293
+ const cssRule = cssLayerBlockRule.cssRules[j];
294
+ const createSyntaxRule = (cssRule)=>{
295
+ if (cssRule.selectorText) {
296
+ const syntaxRule = this.createFromSelectorText(cssRule.selectorText)[0];
297
+ if (syntaxRule) return syntaxRule;
298
+ } else if (cssRule.cssRules) {
299
+ for (const eachCSSRule of cssRule.cssRules){
300
+ const syntaxRule = createSyntaxRule(eachCSSRule);
301
+ if (syntaxRule) return syntaxRule;
302
+ }
303
+ }
304
+ };
305
+ const syntaxRule = createSyntaxRule(cssRule);
306
+ if (syntaxRule) {
307
+ layer.rules.push(syntaxRule);
308
+ layer.insertVariables(syntaxRule);
309
+ layer.insertAnimations(syntaxRule);
310
+ for (const eachNode of syntaxRule.nodes){
311
+ if (!eachNode.native) eachNode.native = cssRule;
312
+ }
313
+ } else {
314
+ cssLayerBlockRule.deleteRule?.(j--);
315
+ console.error(`Cannot recognize the CSS rule in the ${layer.name} layer. \`${cssRule.cssText}\` (https://rc.css.master.co/messages/hydration-errors)`);
316
+ }
317
+ }
318
+ for (const eachRule of layer.rules){
319
+ for(let k = eachRule.nodes.length - 1; k >= 0; k--){
320
+ if (!eachRule.nodes[k].native) {
321
+ eachRule.nodes.splice(k, 1);
322
+ }
323
+ }
324
+ }
325
+ if (layer.rules.length) this.rules.push(layer);
326
+ };
327
+ switch(cssLayerBlockRule.name){
328
+ case 'base':
329
+ handleSyntaxLayer(this.baseLayer);
330
+ break;
331
+ case 'preset':
332
+ handleSyntaxLayer(this.presetLayer);
333
+ break;
334
+ case 'components':
335
+ this.componentsLayer.native = cssLayerBlockRule;
336
+ let stylePreText;
337
+ const createSyntaxRules = (cssRule)=>{
338
+ if (cssRule.selectorText) {
339
+ const syntaxRules = this.createFromSelectorText(cssRule.selectorText);
340
+ if (syntaxRules.length) {
341
+ stylePreText = cssRule.selectorText + '{';
342
+ return syntaxRules;
343
+ }
344
+ } else if (cssRule.cssRules) {
345
+ for (const eachCSSRule of cssRule.cssRules){
346
+ const syntaxRules = this.createFromSelectorText(eachCSSRule.selectorText);
347
+ if (syntaxRules) return syntaxRules;
348
+ }
349
+ }
350
+ };
351
+ for(let j = 0; j < cssLayerBlockRule.cssRules.length; j++){
352
+ const cssRule = cssLayerBlockRule.cssRules[j];
353
+ const syntaxRules = createSyntaxRules(cssRule);
354
+ if (syntaxRules) {
355
+ let matched = false;
356
+ for (const eachSyntaxRule of syntaxRules){
357
+ for (const node of eachSyntaxRule.nodes){
358
+ if (!node.native && node.text.includes(stylePreText)) {
359
+ node.native = cssRule;
360
+ if (!this.componentsLayer.rules.includes(eachSyntaxRule)) {
361
+ this.componentsLayer.rules.push(eachSyntaxRule);
362
+ this.componentsLayer.insertVariables(eachSyntaxRule);
363
+ this.componentsLayer.insertAnimations(eachSyntaxRule);
364
+ }
365
+ matched = true;
366
+ break;
367
+ }
368
+ }
369
+ if (matched) break;
370
+ }
371
+ } else {
372
+ cssLayerBlockRule?.deleteRule?.(j--);
373
+ console.error(`Cannot recognize the CSS rule in the components layer. \`${cssRule.cssText}\` (https://rc.css.master.co/messages/hydration-errors)`);
374
+ }
375
+ }
376
+ for (const eachRule of this.componentsLayer.rules){
377
+ for(let k = eachRule.nodes.length - 1; k >= 0; k--){
378
+ if (!eachRule.nodes[k].native) {
379
+ eachRule.nodes.splice(k, 1);
380
+ }
381
+ }
382
+ }
383
+ if (this.componentsLayer.rules.length) this.rules.push(this.componentsLayer);
384
+ break;
385
+ case 'general':
386
+ handleSyntaxLayer(this.generalLayer);
387
+ break;
388
+ }
389
+ }
390
+ }
391
+ disconnect() {
392
+ if (!this.observing) return;
393
+ if (this.observer) {
394
+ this.observer.disconnect();
395
+ // @ts-expect-error readonly
396
+ this.observer = undefined;
397
+ }
398
+ // @ts-ignore
399
+ this.observing = false;
400
+ this.reset();
401
+ this.classUsages.clear();
402
+ if (!this.progressive) {
403
+ this.style?.remove();
404
+ this.style = null;
405
+ }
406
+ return this;
407
+ }
408
+ refresh(customConfig = this.customConfig) {
409
+ if (!this.observing || !this.style.sheet) return this;
410
+ for(let i = 1; i <= this.style.sheet.cssRules.length - 1; i++){
411
+ this.style.sheet.deleteRule(i);
412
+ }
413
+ super.refresh(customConfig);
414
+ return this;
415
+ }
416
+ destroy() {
417
+ this.disconnect();
418
+ runtimeCSSs.splice(runtimeCSSs.indexOf(this), 1);
419
+ return this;
420
+ }
421
+ }
422
+ const runtimeCSSs = [];
423
+ (()=>{
424
+ globalThis.RuntimeCSS = RuntimeCSS;
425
+ globalThis.runtimeCSSs = runtimeCSSs;
426
+ })();
427
+
428
+ /**
429
+ * Initialize a new RuntimeCSS instance and observe the target root
430
+ * @param config master css config
431
+ * @param targetRoot target root to observe
432
+ * @returns master css instance
433
+ */ function initCSSRuntime(config) {
434
+ return new RuntimeCSS(document, config).observe();
435
+ }
436
+
437
+ exports.RuntimeCSS = RuntimeCSS;
438
+ exports.default = RuntimeCSS;
439
+ 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';