@unocss/runtime 66.7.0 → 66.7.2

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.js CHANGED
@@ -1,263 +1,231 @@
1
- // src/index.ts
2
1
  import { createGenerator, isString, toArray } from "@unocss/core";
3
-
4
- // src/utils.ts
2
+ //#region src/utils.ts
5
3
  function camelize(str) {
6
- return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
4
+ return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
7
5
  }
8
6
  function capitalize(str) {
9
- return str.charAt(0).toUpperCase() + str.slice(1);
7
+ return str.charAt(0).toUpperCase() + str.slice(1);
10
8
  }
11
9
  function hyphenate(str) {
12
- return str.replace(/(?:^|\B)([A-Z])/g, "-$1").toLowerCase();
10
+ return str.replace(/(?:^|\B)([A-Z])/g, "-$1").toLowerCase();
13
11
  }
14
- var prefixes = ["Webkit", "Moz", "ms"];
12
+ const prefixes = [
13
+ "Webkit",
14
+ "Moz",
15
+ "ms"
16
+ ];
15
17
  function autoPrefixer(style) {
16
- const prefixCache = {};
17
- function autoPrefix(rawName) {
18
- const cached = prefixCache[rawName];
19
- if (cached)
20
- return cached;
21
- let name = camelize(rawName);
22
- if (name !== "filter" && name in style)
23
- return prefixCache[rawName] = hyphenate(name);
24
- name = capitalize(name);
25
- for (let i = 0; i < prefixes.length; i++) {
26
- const prefixed = `${prefixes[i]}${name}`;
27
- if (prefixed in style)
28
- return prefixCache[rawName] = hyphenate(capitalize(prefixed));
29
- }
30
- return rawName;
31
- }
32
- return ({ entries }) => entries.forEach((e) => {
33
- if (!e[0].startsWith("--"))
34
- e[0] = autoPrefix(e[0]);
35
- });
18
+ const prefixCache = {};
19
+ function autoPrefix(rawName) {
20
+ const cached = prefixCache[rawName];
21
+ if (cached) return cached;
22
+ let name = camelize(rawName);
23
+ if (name !== "filter" && name in style) return prefixCache[rawName] = hyphenate(name);
24
+ name = capitalize(name);
25
+ for (let i = 0; i < prefixes.length; i++) {
26
+ const prefixed = `${prefixes[i]}${name}`;
27
+ if (prefixed in style) return prefixCache[rawName] = hyphenate(capitalize(prefixed));
28
+ }
29
+ return rawName;
30
+ }
31
+ return ({ entries }) => entries.forEach((e) => {
32
+ if (!e[0].startsWith("--")) e[0] = autoPrefix(e[0]);
33
+ });
36
34
  }
37
35
  function decodeHtml(html) {
38
- return html.replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<");
36
+ return html.replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<");
39
37
  }
40
-
41
- // src/index.ts
38
+ //#endregion
39
+ //#region src/index.ts
40
+ /**
41
+ * Define UnoCSS config
42
+ */
42
43
  function defineConfig(config) {
43
- return config;
44
+ return config;
44
45
  }
45
46
  async function init(inlineConfig = {}) {
46
- if (typeof window == "undefined") {
47
- console.warn("@unocss/runtime been used in non-browser environment, skipped.");
48
- return;
49
- }
50
- const defaultWindow = window;
51
- const defaultDocument = window.document;
52
- const html = () => defaultDocument.documentElement;
53
- const userConfig = defaultWindow.__unocss || {};
54
- const runtimeOptions = Object.assign({}, inlineConfig, userConfig.runtime);
55
- const userConfigDefaults = runtimeOptions.defaults || {};
56
- const cloakAttribute = runtimeOptions.cloakAttribute ?? "un-cloak";
57
- if (runtimeOptions.autoPrefix) {
58
- const postprocessors = userConfigDefaults.postprocess = toArray(userConfigDefaults.postprocess);
59
- postprocessors.unshift(autoPrefixer(defaultDocument.createElement("div").style));
60
- }
61
- runtimeOptions.configResolved?.(userConfig, userConfigDefaults);
62
- const uno = await createGenerator(userConfig, userConfigDefaults);
63
- const inject = (styleElement) => {
64
- const rootElement2 = inlineConfig.rootElement?.();
65
- if (rootElement2) {
66
- rootElement2.appendChild(styleElement);
67
- return;
68
- }
69
- runtimeOptions.inject ? runtimeOptions.inject(styleElement) : html().prepend(styleElement);
70
- };
71
- const rootElement = () => runtimeOptions.rootElement ? runtimeOptions.rootElement() : defaultDocument.body;
72
- const styleElements = /* @__PURE__ */ new Map();
73
- let paused = true;
74
- const tokens = /* @__PURE__ */ new Set();
75
- let inspector;
76
- let _timer;
77
- let _resolvers = [];
78
- const scheduleUpdate = () => new Promise((resolve) => {
79
- _resolvers.push(resolve);
80
- if (_timer != null)
81
- clearTimeout(_timer);
82
- _timer = setTimeout(() => updateStyle().then(() => {
83
- const resolvers = _resolvers;
84
- _resolvers = [];
85
- resolvers.forEach((r) => r());
86
- }), 0);
87
- });
88
- function removeCloak(node, isAll = false) {
89
- if (node.nodeType !== 1)
90
- return;
91
- const el = node;
92
- if (el.hasAttribute(cloakAttribute))
93
- el.removeAttribute(cloakAttribute);
94
- if (isAll) {
95
- el.querySelectorAll(`[${cloakAttribute}]`).forEach((n) => {
96
- n.removeAttribute(cloakAttribute);
97
- });
98
- }
99
- }
100
- function getStyleElement(layer, previousLayer) {
101
- let styleElement = styleElements.get(layer);
102
- if (!styleElement) {
103
- styleElement = defaultDocument.createElement("style");
104
- styleElement.setAttribute("data-unocss-runtime-layer", layer);
105
- styleElements.set(layer, styleElement);
106
- if (previousLayer == null) {
107
- inject(styleElement);
108
- } else {
109
- const previousStyle = getStyleElement(previousLayer);
110
- const parentNode = previousStyle.parentNode;
111
- if (parentNode)
112
- parentNode.insertBefore(styleElement, previousStyle.nextSibling);
113
- else
114
- inject(styleElement);
115
- }
116
- }
117
- return styleElement;
118
- }
119
- async function updateStyle() {
120
- const currentToken = [...tokens];
121
- const result = await uno.generate(currentToken);
122
- result.layers.reduce((previous, current) => {
123
- getStyleElement(current, previous).innerHTML = result.getLayer(current) ?? "";
124
- return current;
125
- }, void 0);
126
- const clearTokens = currentToken.filter((i) => !result.matched.has(i));
127
- clearTokens.forEach((t) => tokens.delete(t));
128
- return {
129
- ...result,
130
- getStyleElement: (layer) => styleElements.get(layer),
131
- getStyleElements: () => styleElements
132
- };
133
- }
134
- async function extract(str) {
135
- const tokenSize = tokens.size;
136
- await uno.applyExtractors(str, void 0, tokens);
137
- if (tokenSize !== tokens.size)
138
- await scheduleUpdate();
139
- }
140
- async function extractAll(target = rootElement()) {
141
- const outerHTML = target && target.outerHTML;
142
- if (outerHTML) {
143
- await extract(`${outerHTML} ${decodeHtml(outerHTML)}`);
144
- removeCloak(html());
145
- removeCloak(target, true);
146
- }
147
- }
148
- const mutationObserver = new MutationObserver((mutations) => {
149
- if (paused)
150
- return;
151
- mutations.forEach(async (mutation) => {
152
- if (mutation.target.nodeType !== 1)
153
- return;
154
- const target = mutation.target;
155
- for (const item of styleElements) {
156
- if (target === item[1])
157
- return;
158
- }
159
- if (mutation.type === "childList") {
160
- mutation.addedNodes.forEach(async (node) => {
161
- if (node.nodeType !== 1)
162
- return;
163
- const el = node;
164
- if (inspector && !inspector(el))
165
- return;
166
- await extract(el.outerHTML);
167
- removeCloak(el);
168
- });
169
- } else {
170
- if (inspector && !inspector(target))
171
- return;
172
- if (mutation.attributeName !== cloakAttribute) {
173
- const attrs = Array.from(target.attributes).map((i) => i.value ? `${i.name}="${i.value}"` : i.name).join(" ");
174
- const tag = `<${target.tagName.toLowerCase()} ${attrs}>`;
175
- await extract(tag);
176
- }
177
- removeCloak(target);
178
- }
179
- });
180
- });
181
- let observing = false;
182
- function observe() {
183
- if (observing)
184
- return;
185
- const target = runtimeOptions.observer?.target ? runtimeOptions.observer.target() : rootElement();
186
- if (!target)
187
- return;
188
- mutationObserver.observe(target, {
189
- childList: true,
190
- subtree: true,
191
- attributes: true,
192
- attributeFilter: runtimeOptions.observer?.attributeFilter
193
- });
194
- observing = true;
195
- }
196
- function execute() {
197
- if (runtimeOptions.bypassDefined)
198
- getDefinedCssSelectors(uno.blocked);
199
- extractAll();
200
- observe();
201
- }
202
- function ready() {
203
- if (defaultDocument.readyState === "loading")
204
- defaultWindow.addEventListener("DOMContentLoaded", execute);
205
- else
206
- execute();
207
- }
208
- const unoCssRuntime = defaultWindow.__unocss_runtime = defaultWindow.__unocss_runtime = {
209
- version: uno.version,
210
- uno,
211
- async extract(userTokens) {
212
- if (!isString(userTokens)) {
213
- userTokens.forEach((t) => tokens.add(t));
214
- userTokens = "";
215
- }
216
- await extract(userTokens);
217
- },
218
- extractAll,
219
- inspect(callback) {
220
- inspector = callback;
221
- },
222
- toggleObserver(set) {
223
- if (set === void 0)
224
- paused = !paused;
225
- else
226
- paused = !!set;
227
- if (!observing && !paused)
228
- ready();
229
- },
230
- update: updateStyle,
231
- presets: defaultWindow.__unocss_runtime?.presets ?? {}
232
- };
233
- if (runtimeOptions.ready?.(unoCssRuntime) !== false) {
234
- paused = false;
235
- ready();
236
- }
47
+ if (typeof window == "undefined") {
48
+ console.warn("@unocss/runtime been used in non-browser environment, skipped.");
49
+ return;
50
+ }
51
+ const defaultWindow = window;
52
+ const defaultDocument = window.document;
53
+ const html = () => defaultDocument.documentElement;
54
+ const userConfig = defaultWindow.__unocss || {};
55
+ const runtimeOptions = Object.assign({}, inlineConfig, userConfig.runtime);
56
+ const userConfigDefaults = runtimeOptions.defaults || {};
57
+ const cloakAttribute = runtimeOptions.cloakAttribute ?? "un-cloak";
58
+ if (runtimeOptions.autoPrefix) (userConfigDefaults.postprocess = toArray(userConfigDefaults.postprocess)).unshift(autoPrefixer(defaultDocument.createElement("div").style));
59
+ runtimeOptions.configResolved?.(userConfig, userConfigDefaults);
60
+ const uno = await createGenerator(userConfig, userConfigDefaults);
61
+ const inject = (styleElement) => {
62
+ const rootElement = inlineConfig.rootElement?.();
63
+ if (rootElement) {
64
+ rootElement.appendChild(styleElement);
65
+ return;
66
+ }
67
+ runtimeOptions.inject ? runtimeOptions.inject(styleElement) : html().prepend(styleElement);
68
+ };
69
+ const rootElement = () => runtimeOptions.rootElement ? runtimeOptions.rootElement() : defaultDocument.body;
70
+ const styleElements = /* @__PURE__ */ new Map();
71
+ let paused = true;
72
+ const tokens = /* @__PURE__ */ new Set();
73
+ let inspector;
74
+ let _timer;
75
+ let _resolvers = [];
76
+ const scheduleUpdate = () => new Promise((resolve) => {
77
+ _resolvers.push(resolve);
78
+ if (_timer != null) clearTimeout(_timer);
79
+ _timer = setTimeout(() => updateStyle().then(() => {
80
+ const resolvers = _resolvers;
81
+ _resolvers = [];
82
+ resolvers.forEach((r) => r());
83
+ }), 0);
84
+ });
85
+ function removeCloak(node, isAll = false) {
86
+ if (node.nodeType !== 1) return;
87
+ const el = node;
88
+ if (el.hasAttribute(cloakAttribute)) el.removeAttribute(cloakAttribute);
89
+ if (isAll) el.querySelectorAll(`[${cloakAttribute}]`).forEach((n) => {
90
+ n.removeAttribute(cloakAttribute);
91
+ });
92
+ }
93
+ function getStyleElement(layer, previousLayer) {
94
+ let styleElement = styleElements.get(layer);
95
+ if (!styleElement) {
96
+ styleElement = defaultDocument.createElement("style");
97
+ styleElement.setAttribute("data-unocss-runtime-layer", layer);
98
+ styleElements.set(layer, styleElement);
99
+ if (previousLayer == null) inject(styleElement);
100
+ else {
101
+ const previousStyle = getStyleElement(previousLayer);
102
+ const parentNode = previousStyle.parentNode;
103
+ if (parentNode) parentNode.insertBefore(styleElement, previousStyle.nextSibling);
104
+ else inject(styleElement);
105
+ }
106
+ }
107
+ return styleElement;
108
+ }
109
+ async function updateStyle() {
110
+ const currentToken = [...tokens];
111
+ const result = await uno.generate(currentToken);
112
+ result.layers.reduce((previous, current) => {
113
+ getStyleElement(current, previous).innerHTML = result.getLayer(current) ?? "";
114
+ return current;
115
+ }, void 0);
116
+ currentToken.filter((i) => !result.matched.has(i)).forEach((t) => tokens.delete(t));
117
+ return {
118
+ ...result,
119
+ getStyleElement: (layer) => styleElements.get(layer),
120
+ getStyleElements: () => styleElements
121
+ };
122
+ }
123
+ async function extract(str) {
124
+ const tokenSize = tokens.size;
125
+ await uno.applyExtractors(str, void 0, tokens);
126
+ if (tokenSize !== tokens.size) await scheduleUpdate();
127
+ }
128
+ async function extractAll(target = rootElement()) {
129
+ const outerHTML = target && target.outerHTML;
130
+ if (outerHTML) {
131
+ await extract(`${outerHTML} ${decodeHtml(outerHTML)}`);
132
+ removeCloak(html());
133
+ removeCloak(target, true);
134
+ }
135
+ }
136
+ const mutationObserver = new MutationObserver((mutations) => {
137
+ if (paused) return;
138
+ mutations.forEach(async (mutation) => {
139
+ if (mutation.target.nodeType !== 1) return;
140
+ const target = mutation.target;
141
+ for (const item of styleElements) if (target === item[1]) return;
142
+ if (mutation.type === "childList") mutation.addedNodes.forEach(async (node) => {
143
+ if (node.nodeType !== 1) return;
144
+ const el = node;
145
+ if (inspector && !inspector(el)) return;
146
+ await extract(el.outerHTML);
147
+ removeCloak(el);
148
+ });
149
+ else {
150
+ if (inspector && !inspector(target)) return;
151
+ if (mutation.attributeName !== cloakAttribute) {
152
+ const attrs = Array.from(target.attributes).map((i) => i.value ? `${i.name}="${i.value}"` : i.name).join(" ");
153
+ await extract(`<${target.tagName.toLowerCase()} ${attrs}>`);
154
+ }
155
+ removeCloak(target);
156
+ }
157
+ });
158
+ });
159
+ let observing = false;
160
+ function observe() {
161
+ if (observing) return;
162
+ const target = runtimeOptions.observer?.target ? runtimeOptions.observer.target() : rootElement();
163
+ if (!target) return;
164
+ mutationObserver.observe(target, {
165
+ childList: true,
166
+ subtree: true,
167
+ attributes: true,
168
+ attributeFilter: runtimeOptions.observer?.attributeFilter
169
+ });
170
+ observing = true;
171
+ }
172
+ function execute() {
173
+ if (runtimeOptions.bypassDefined) getDefinedCssSelectors(uno.blocked);
174
+ extractAll();
175
+ observe();
176
+ }
177
+ function ready() {
178
+ if (defaultDocument.readyState === "loading") defaultWindow.addEventListener("DOMContentLoaded", execute);
179
+ else execute();
180
+ }
181
+ const unoCssRuntime = defaultWindow.__unocss_runtime = defaultWindow.__unocss_runtime = {
182
+ version: uno.version,
183
+ uno,
184
+ async extract(userTokens) {
185
+ if (!isString(userTokens)) {
186
+ userTokens.forEach((t) => tokens.add(t));
187
+ userTokens = "";
188
+ }
189
+ await extract(userTokens);
190
+ },
191
+ extractAll,
192
+ inspect(callback) {
193
+ inspector = callback;
194
+ },
195
+ toggleObserver(set) {
196
+ if (set === void 0) paused = !paused;
197
+ else paused = !!set;
198
+ if (!observing && !paused) ready();
199
+ },
200
+ update: updateStyle,
201
+ presets: defaultWindow.__unocss_runtime?.presets ?? {}
202
+ };
203
+ if (runtimeOptions.ready?.(unoCssRuntime) !== false) {
204
+ paused = false;
205
+ ready();
206
+ }
237
207
  }
208
+ /**
209
+ * Read all defined css selectors, and add them to the blocked list
210
+ */
238
211
  function getDefinedCssSelectors(selectors = /* @__PURE__ */ new Set()) {
239
- for (let i = 0; i < document.styleSheets.length; i++) {
240
- const sheet = document.styleSheets[i];
241
- let list;
242
- try {
243
- list = sheet.cssRules || sheet.rules;
244
- if (!list)
245
- continue;
246
- Array.from(list).flatMap((r) => r.selectorText?.split(/,/g) || []).forEach((s) => {
247
- if (!s)
248
- return;
249
- s = s.trim();
250
- if (s.startsWith("."))
251
- s = s.slice(1);
252
- selectors.add(s);
253
- });
254
- } catch {
255
- continue;
256
- }
257
- }
258
- return selectors;
212
+ for (let i = 0; i < document.styleSheets.length; i++) {
213
+ const sheet = document.styleSheets[i];
214
+ let list;
215
+ try {
216
+ list = sheet.cssRules || sheet.rules;
217
+ if (!list) continue;
218
+ Array.from(list).flatMap((r) => r.selectorText?.split(/,/g) || []).forEach((s) => {
219
+ if (!s) return;
220
+ s = s.trim();
221
+ if (s.startsWith(".")) s = s.slice(1);
222
+ selectors.add(s);
223
+ });
224
+ } catch {
225
+ continue;
226
+ }
227
+ }
228
+ return selectors;
259
229
  }
260
- export {
261
- init as default,
262
- defineConfig
263
- };
230
+ //#endregion
231
+ export { init as default, defineConfig };