@master/css-runtime 2.0.0-rc.2 → 2.0.0-rc.21

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,399 @@
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
+ host;
11
+ observing;
12
+ progressive;
13
+ container;
14
+ observer;
15
+ constructor(root = document, customConfig = css.config){
16
+ super(customConfig);
17
+ this.root = root;
18
+ this.customConfig = customConfig;
19
+ this.observing = false;
20
+ this.progressive = false;
21
+ if (!root) this.root = document;
22
+ if (this.root === document) {
23
+ globalThis.runtimeCSS = this;
24
+ this.container = document.head;
25
+ this.host = document.documentElement;
26
+ } else {
27
+ this.container = this.root;
28
+ this.host = this.root.host;
29
+ }
30
+ runtimeCSSs.push(this);
31
+ }
32
+ /**
33
+ * Observe the DOM for changes and update the running stylesheet. (browser only)
34
+ * @param options mutation observer options
35
+ * @returns this
36
+ */ observe(options = {
37
+ subtree: true,
38
+ childList: true
39
+ }) {
40
+ if (this.observing || !this.root) return this;
41
+ if (runtimeCSSs.find((eachRuntimeCSS)=>eachRuntimeCSS !== this && eachRuntimeCSS.root === this.root)) {
42
+ console.warn('Cannot observe the same root element repeatedly.');
43
+ return this;
44
+ }
45
+ if (this.root?.styleSheets) for (const sheet of this.root.styleSheets){
46
+ const { ownerNode } = sheet;
47
+ if (ownerNode && ownerNode.id === 'master') {
48
+ // @ts-ignore
49
+ this.style = ownerNode;
50
+ // @ts-ignore
51
+ this.progressive = true;
52
+ break;
53
+ }
54
+ }
55
+ if (this.style?.sheet) {
56
+ let index = 0;
57
+ for(; index < this.style.sheet.cssRules.length; index++){
58
+ const eachCSSRule = this.style.sheet.cssRules[index];
59
+ switch(eachCSSRule.constructor.name){
60
+ case 'CSSKeyframesRule':
61
+ continue;
62
+ case 'CSSMeidaRule':
63
+ if (this.config.themeDriver === 'media') {
64
+ const result = /\(prefers-color-scheme: (.*?)\)/.exec(eachCSSRule.conditionText);
65
+ if (result) {
66
+ const firstCSSRule = eachCSSRule.cssRules[0];
67
+ if (firstCSSRule?.constructor.name === 'CSSStyleRule' && firstCSSRule.selectorText === ':root') {
68
+ this.pushVariableNativeRule(result[1], firstCSSRule);
69
+ continue;
70
+ }
71
+ }
72
+ }
73
+ break;
74
+ case 'CSSStyleRule':
75
+ // eslint-disable-next-line no-case-declarations
76
+ const selectorText = eachCSSRule.selectorText;
77
+ if (eachCSSRule.style.length) {
78
+ let isVariablesRule = true;
79
+ for(let i = 0; i < eachCSSRule.style.length; i++){
80
+ if (!eachCSSRule.style[i]?.startsWith('--')) {
81
+ isVariablesRule = false;
82
+ break;
83
+ }
84
+ }
85
+ if (isVariablesRule) {
86
+ if (selectorText === ':root') {
87
+ this.pushVariableNativeRule('', eachCSSRule);
88
+ continue;
89
+ } else {
90
+ if (this.config.themeDriver === 'host') {
91
+ const result = /:host(.*?)/.exec(selectorText);
92
+ if (result) {
93
+ this.pushVariableNativeRule(result[1], eachCSSRule);
94
+ continue;
95
+ }
96
+ } else if (!selectorText.startsWith('.\\$')) {
97
+ this.pushVariableNativeRule(selectorText.slice(1), eachCSSRule);
98
+ continue;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ break;
104
+ }
105
+ break;
106
+ }
107
+ for(; index < this.style.sheet.cssRules.length; index++){
108
+ const getRule = (cssRule)=>{
109
+ if (cssRule.selectorText) {
110
+ const selectorTexts = cssRule.selectorText.split(', ');
111
+ const escapedClassNames = selectorTexts[0].split(' ');
112
+ for(let i = 0; i < escapedClassNames.length; i++){
113
+ const eachSelectorText = escapedClassNames[i];
114
+ if (eachSelectorText[0] === '.') {
115
+ const escapedClassName = eachSelectorText.slice(1);
116
+ let className = '';
117
+ for(let j = 0; j < escapedClassName.length; j++){
118
+ const char = escapedClassName[j];
119
+ const nextChar = escapedClassName[j + 1];
120
+ if (char === '\\') {
121
+ j++;
122
+ if (nextChar !== '\\') {
123
+ className += nextChar;
124
+ continue;
125
+ }
126
+ } else if ([
127
+ ',',
128
+ '.',
129
+ '#',
130
+ '[',
131
+ '!',
132
+ '*',
133
+ '>',
134
+ '+',
135
+ '~',
136
+ ':',
137
+ '@'
138
+ ].includes(char)) {
139
+ break;
140
+ }
141
+ className += char;
142
+ }
143
+ if (!Object.prototype.hasOwnProperty.call(this.ruleBy, className) && !Object.prototype.hasOwnProperty.call(this.styles, className)) {
144
+ const currentRule = this.generate(className)[0];
145
+ if (currentRule) return currentRule;
146
+ }
147
+ }
148
+ }
149
+ } else if (cssRule.cssRules) {
150
+ for(let index = 0; index < cssRule.cssRules.length; index++){
151
+ const currentRule = getRule(cssRule.cssRules[index]);
152
+ if (currentRule) return currentRule;
153
+ }
154
+ }
155
+ };
156
+ const rule = getRule(this.style.sheet.cssRules[index]);
157
+ if (rule) {
158
+ this.rules.push(rule);
159
+ this.ruleBy[rule.className] = rule;
160
+ for(let i = 0; i < rule.natives.length; i++){
161
+ rule.natives[i].cssRule = this.style.sheet.cssRules[index + i];
162
+ }
163
+ index += rule.natives.length - 1;
164
+ // variables
165
+ this.handleRuleWithVariableNames(rule, true);
166
+ // animations
167
+ this.handleRuleWithAnimationNames(rule, true);
168
+ rule.definition.insert?.call(rule);
169
+ }
170
+ }
171
+ } else {
172
+ // @ts-ignore
173
+ this.style = document.createElement('style');
174
+ this.style.id = 'master';
175
+ this.container.append(this.style);
176
+ }
177
+ const handleClassList = (classList)=>{
178
+ classList.forEach((className)=>{
179
+ if (Object.prototype.hasOwnProperty.call(this.classesUsage, className)) {
180
+ this.classesUsage[className]++;
181
+ } else {
182
+ this.classesUsage[className] = 1;
183
+ this.add(className);
184
+ }
185
+ });
186
+ };
187
+ handleClassList(this.host.classList);
188
+ if (options.subtree) {
189
+ /**
190
+ * 待所有 DOM 結構完成解析後,開始繪製 Rule 樣式
191
+ */ (this.root === document ? this.host : this.container).querySelectorAll('[class]').forEach((element)=>handleClassList(element.classList));
192
+ }
193
+ this.observer = new MutationObserver((mutationRecords)=>{
194
+ // console.time('css engine');
195
+ const correctionOfClassName = {};
196
+ const attributeMutationRecords = [];
197
+ const updatedElements = [];
198
+ const unchangedElements = [];
199
+ /**
200
+ * 取得所有深層後代的 class names
201
+ */ const handleClassNameDeeply = (element, remove)=>{
202
+ if (remove) {
203
+ element.classList.forEach(removeClassName);
204
+ } else {
205
+ element.classList.forEach(addClassName);
206
+ }
207
+ const children = element.children;
208
+ for(let i = 0; i < children.length; i++){
209
+ const eachChildren = children[i];
210
+ if (eachChildren.classList) {
211
+ updatedElements.push(eachChildren);
212
+ handleClassNameDeeply(eachChildren, remove);
213
+ }
214
+ }
215
+ };
216
+ const addClassName = (className)=>{
217
+ if (Object.prototype.hasOwnProperty.call(correctionOfClassName, className)) {
218
+ correctionOfClassName[className]++;
219
+ } else {
220
+ correctionOfClassName[className] = 1;
221
+ }
222
+ };
223
+ const removeClassName = (className)=>{
224
+ if (Object.prototype.hasOwnProperty.call(correctionOfClassName, className)) {
225
+ correctionOfClassName[className]--;
226
+ } else if (Object.prototype.hasOwnProperty.call(this.classesUsage, className)) {
227
+ correctionOfClassName[className] = -1;
228
+ }
229
+ };
230
+ const handleNodes = (nodes, remove)=>{
231
+ for(let i = 0; i < nodes.length; i++){
232
+ const eachNode = nodes[i];
233
+ if (eachNode.classList && !updatedElements.includes(eachNode) && !unchangedElements.includes(eachNode)) {
234
+ if (eachNode.isConnected !== remove) {
235
+ updatedElements.push(eachNode);
236
+ handleClassNameDeeply(eachNode, remove);
237
+ } else {
238
+ unchangedElements.push(eachNode);
239
+ }
240
+ }
241
+ }
242
+ };
243
+ for(let i = 0; i < mutationRecords.length; i++){
244
+ const mutationRecord = mutationRecords[i];
245
+ const { addedNodes, removedNodes, type, target } = mutationRecord;
246
+ if (type === 'attributes') {
247
+ /**
248
+ * 防止同樣的 MutationRecord 重複執行
249
+ * According to this history,
250
+ * MutationObserver was designed to work that way.
251
+ * Any call to setAttribute triggers a mutation,
252
+ * regardless of whether the value is being changed or set to the current value
253
+ */ if (attributeMutationRecords.find((eachAttributeMutationRecord)=>eachAttributeMutationRecord.target === target)) {
254
+ continue;
255
+ } else {
256
+ /**
257
+ * 第一個匹配到的 oldValue 一定是該批變動前的原始狀態值
258
+ */ attributeMutationRecords.push(mutationRecord);
259
+ }
260
+ } else {
261
+ // 先判斷節點新增或移除
262
+ handleNodes(addedNodes, false);
263
+ // 忽略處理新元素的已刪除子節點
264
+ if (!target.isConnected || !updatedElements.includes(target)) {
265
+ handleNodes(removedNodes, true);
266
+ }
267
+ }
268
+ }
269
+ if (!attributeMutationRecords.length && !Object.keys(correctionOfClassName).length) {
270
+ // console.timeEnd('css engine');
271
+ return;
272
+ }
273
+ for (const { oldValue, target } of attributeMutationRecords){
274
+ /**
275
+ * 如果被操作的元素中包含了屬性變更的目標,
276
+ * 則將該目標從 existedAttributeMutationTargets 中移除,
277
+ * 以防止執行接下來的屬性變更處理
278
+ *
279
+ * 該批 mutationRecords 中,某個 target 同時有 attribute 及 childList 的變更,
280
+ * 則以 childList 節點插入及移除的 target.className 為主
281
+ */ const updated = updatedElements.includes(target);
282
+ const classNames = target.classList;
283
+ const oldClassNames = oldValue ? oldValue.split(' ') : [];
284
+ if (updated) {
285
+ if (target.isConnected) {
286
+ continue;
287
+ } else {
288
+ for (const oldClassName of oldClassNames){
289
+ if (!classNames.contains(oldClassName)) {
290
+ removeClassName(oldClassName);
291
+ }
292
+ }
293
+ }
294
+ } else if (target.isConnected) {
295
+ classNames.forEach((className)=>{
296
+ if (!oldClassNames.includes(className)) {
297
+ addClassName(className);
298
+ }
299
+ });
300
+ for (const oldClassName of oldClassNames){
301
+ if (!classNames.contains(oldClassName)) {
302
+ removeClassName(oldClassName);
303
+ }
304
+ }
305
+ }
306
+ }
307
+ for(const className in correctionOfClassName){
308
+ const correction = correctionOfClassName[className];
309
+ const count = (this.classesUsage[className] || 0) + correction;
310
+ if (count === 0) {
311
+ // remove
312
+ delete this.classesUsage[className];
313
+ /**
314
+ * class name 從 DOM tree 中被移除,
315
+ * 匹配並刪除對應的 rule
316
+ */ this.delete(className);
317
+ } else {
318
+ if (!Object.prototype.hasOwnProperty.call(this.classesUsage, className)) {
319
+ // add
320
+ /**
321
+ * 新 class name 被 connected 至 DOM tree,
322
+ * 匹配並創建對應的 Rule
323
+ */ this.add(className);
324
+ }
325
+ this.classesUsage[className] = count;
326
+ }
327
+ }
328
+ });
329
+ this.observer.observe(this.root, {
330
+ ...options,
331
+ attributes: true,
332
+ attributeOldValue: true,
333
+ attributeFilter: [
334
+ 'class'
335
+ ]
336
+ });
337
+ this.host.style.removeProperty('display');
338
+ // @ts-ignore
339
+ this.observing = true;
340
+ return this;
341
+ }
342
+ refresh(customConfig = this.customConfig) {
343
+ const newStyle = document.createElement('style');
344
+ newStyle.id = 'master';
345
+ this.style.replaceWith(newStyle);
346
+ // @ts-ignore
347
+ this.style = newStyle;
348
+ super.refresh(customConfig);
349
+ return this;
350
+ }
351
+ reset() {
352
+ super.reset();
353
+ const sheet = this.style?.sheet;
354
+ if (sheet?.cssRules) {
355
+ for(let i = sheet.cssRules.length - 1; i >= 0; i--){
356
+ sheet.deleteRule(i);
357
+ }
358
+ }
359
+ if (!this.progressive) {
360
+ this.style?.remove();
361
+ // @ts-ignore
362
+ this.style = null;
363
+ }
364
+ return this;
365
+ }
366
+ disconnect() {
367
+ if (this.observer) {
368
+ this.observer.disconnect();
369
+ this.observer = null;
370
+ }
371
+ // @ts-ignore
372
+ this.observing = false;
373
+ this.reset();
374
+ return this;
375
+ }
376
+ destroy() {
377
+ this.disconnect();
378
+ runtimeCSSs.splice(runtimeCSSs.indexOf(this), 1);
379
+ return this;
380
+ }
381
+ }
382
+ const runtimeCSSs = [];
383
+ (()=>{
384
+ globalThis.RuntimeCSS = RuntimeCSS;
385
+ globalThis.runtimeCSSs = runtimeCSSs;
386
+ })();
387
+
388
+ /**
389
+ * Initialize a new RuntimeCSS instance and observe the target root
390
+ * @param config master css config
391
+ * @param targetRoot target root to observe
392
+ * @returns master css instance
393
+ */ function initCSSRuntime(config) {
394
+ return new RuntimeCSS(document, config).observe();
395
+ }
396
+
397
+ exports.RuntimeCSS = RuntimeCSS;
398
+ exports.default = RuntimeCSS;
399
+ 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';