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