@unocss/runtime 0.58.9 → 0.59.0

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.d.mts DELETED
@@ -1,126 +0,0 @@
1
- import { UserConfig, GenerateResult, UserConfigDefaults, UnoGenerator } from '@unocss/core';
2
-
3
- interface RuntimeGenerateResult extends GenerateResult {
4
- getStyleElement: (name: string) => HTMLStyleElement | undefined;
5
- getStyleElements: () => Map<string, HTMLStyleElement>;
6
- }
7
- interface RuntimeObserverConfig {
8
- /**
9
- * A function that returns an HTML Element for the MutationObserver to watch.
10
- * Defaults to the same as rootElement
11
- */
12
- target?: () => Element;
13
- /**
14
- * An array of attribute names for the MutationObserver to limit which attributes
15
- * are watched for mutations.
16
- */
17
- attributeFilter?: Array<string>;
18
- }
19
- interface RuntimeOptions {
20
- /**
21
- * Default config of UnoCSS
22
- */
23
- defaults?: UserConfigDefaults;
24
- /**
25
- * Enable css property auto prefixer
26
- * @default false
27
- */
28
- autoPrefix?: boolean;
29
- /**
30
- * Attribute to use as cloaking
31
- * @default 'un-cloak'
32
- */
33
- cloakAttribute?: string;
34
- /**
35
- * Callback to modify config
36
- */
37
- configResolved?: (config: UserConfig, defaults: UserConfigDefaults) => void;
38
- /**
39
- * Optional function to control UnoCSS style element(s) injection into DOM.
40
- * When provided, the default injection logic will be overridden.
41
- */
42
- inject?: (styleElement: HTMLStyleElement) => void;
43
- /**
44
- * Callback when the runtime is ready. Returning false will prevent default extraction
45
- */
46
- ready?: (runtime: RuntimeContext) => false | any;
47
- /**
48
- * Runtime MutationObserver configuration options
49
- */
50
- observer?: RuntimeObserverConfig;
51
- /**
52
- * When enabled, UnoCSS will look for the existing selectors defined in the stylesheet and bypass them.
53
- * This is useful when using the runtime alongwith the build-time UnoCSS.
54
- */
55
- bypassDefined?: boolean;
56
- /**
57
- * Optional function to control the root element to extract.
58
- */
59
- rootElement?: () => Element | undefined;
60
- }
61
- type RuntimeInspectorCallback = (element: Element) => boolean;
62
- interface RuntimeContext {
63
- /**
64
- * The UnoCSS instance.
65
- *
66
- * @type {UnoGenerator}
67
- */
68
- uno: UnoGenerator;
69
- /**
70
- * Run extractor on specified tokens
71
- *
72
- * @returns {Promise<void>}
73
- */
74
- extract: (tokens: string | string[]) => Promise<void>;
75
- /**
76
- * Rerun extractor on the whole <body>, regardless of paused status or inspection limitation.
77
- *
78
- * @returns {Promise<void>}
79
- */
80
- extractAll: (target?: Element) => Promise<void>;
81
- /**
82
- * Set/unset inspection callback to allow/ignore element to be extracted.
83
- *
84
- * @param {RuntimeInspectorCallback} [callback] - Callback to determine whether the element will be extracted.
85
- *
86
- * @returns {void}
87
- */
88
- inspect: (callback?: RuntimeInspectorCallback) => void;
89
- /**
90
- * Pause/resume/toggle the runtime.
91
- *
92
- * @param {boolean} [state] - False or True respectively pause or resume the runtime. Undefined parameter toggles the pause/resume state.
93
- *
94
- * @returns {void}
95
- */
96
- toggleObserver: (state?: boolean) => void;
97
- /**
98
- * Manually run the update cycle.
99
- *
100
- * @returns {RuntimeGenerateResult}
101
- */
102
- update: () => Promise<RuntimeGenerateResult>;
103
- /**
104
- * Loaded presets
105
- *
106
- * @type {Record<string, Function>}
107
- */
108
- presets: Record<string, Function>;
109
- /**
110
- * The UnoCSS version.
111
- *
112
- * @type {string}
113
- */
114
- version: string;
115
- }
116
- declare global {
117
- interface Window {
118
- __unocss?: UserConfig & {
119
- runtime?: RuntimeOptions;
120
- };
121
- __unocss_runtime?: RuntimeContext;
122
- }
123
- }
124
- declare function init(inlineConfig?: RuntimeOptions): void;
125
-
126
- export { type RuntimeContext, type RuntimeGenerateResult, type RuntimeInspectorCallback, type RuntimeObserverConfig, type RuntimeOptions, init as default };
package/dist/index.mjs DELETED
@@ -1,249 +0,0 @@
1
- // src/index.ts
2
- import { createGenerator, isString, toArray } from "@unocss/core";
3
-
4
- // src/utils.ts
5
- function camelize(str) {
6
- return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
7
- }
8
- function capitalize(str) {
9
- return str.charAt(0).toUpperCase() + str.slice(1);
10
- }
11
- function hyphenate(str) {
12
- return str.replace(/(?:^|\B)([A-Z])/g, "-$1").toLowerCase();
13
- }
14
- var prefixes = ["Webkit", "Moz", "ms"];
15
- 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
- });
36
- }
37
- function decodeHtml(html) {
38
- return html.replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<");
39
- }
40
-
41
- // src/index.ts
42
- function init(inlineConfig = {}) {
43
- if (typeof window == "undefined") {
44
- console.warn("@unocss/runtime been used in non-browser environment, skipped.");
45
- return;
46
- }
47
- const defaultWindow = window;
48
- const defaultDocument = window.document;
49
- const html = () => defaultDocument.documentElement;
50
- const userConfig = defaultWindow.__unocss || {};
51
- const runtimeOptions = Object.assign({}, inlineConfig, userConfig.runtime);
52
- const userConfigDefaults = runtimeOptions.defaults || {};
53
- const cloakAttribute = runtimeOptions.cloakAttribute ?? "un-cloak";
54
- if (runtimeOptions.autoPrefix) {
55
- const postprocessors = userConfigDefaults.postprocess = toArray(userConfigDefaults.postprocess);
56
- postprocessors.unshift(autoPrefixer(defaultDocument.createElement("div").style));
57
- }
58
- runtimeOptions.configResolved?.(userConfig, userConfigDefaults);
59
- const uno = createGenerator(userConfig, userConfigDefaults);
60
- const inject = (styleElement) => runtimeOptions.inject ? runtimeOptions.inject(styleElement) : html().prepend(styleElement);
61
- const rootElement = () => runtimeOptions.rootElement ? runtimeOptions.rootElement() : defaultDocument.body;
62
- const styleElements = /* @__PURE__ */ new Map();
63
- let paused = true;
64
- let tokens = /* @__PURE__ */ new Set();
65
- let inspector;
66
- let _timer;
67
- let _resolvers = [];
68
- const scheduleUpdate = () => new Promise((resolve) => {
69
- _resolvers.push(resolve);
70
- if (_timer != null)
71
- clearTimeout(_timer);
72
- _timer = setTimeout(() => updateStyle().then(() => {
73
- const resolvers = _resolvers;
74
- _resolvers = [];
75
- resolvers.forEach((r) => r());
76
- }), 0);
77
- });
78
- function removeCloak(node) {
79
- if (node.nodeType !== 1)
80
- return;
81
- const el = node;
82
- if (el.hasAttribute(cloakAttribute))
83
- el.removeAttribute(cloakAttribute);
84
- el.querySelectorAll(`[${cloakAttribute}]`).forEach((n) => {
85
- n.removeAttribute(cloakAttribute);
86
- });
87
- }
88
- function getStyleElement(layer, previousLayer) {
89
- let styleElement = styleElements.get(layer);
90
- if (!styleElement) {
91
- styleElement = defaultDocument.createElement("style");
92
- styleElement.setAttribute("data-unocss-runtime-layer", layer);
93
- styleElements.set(layer, styleElement);
94
- if (previousLayer == null) {
95
- inject(styleElement);
96
- } else {
97
- const previousStyle = getStyleElement(previousLayer);
98
- const parentNode = previousStyle.parentNode;
99
- if (parentNode)
100
- parentNode.insertBefore(styleElement, previousStyle.nextSibling);
101
- else
102
- inject(styleElement);
103
- }
104
- }
105
- return styleElement;
106
- }
107
- async function updateStyle() {
108
- const result = await uno.generate(tokens);
109
- result.layers.reduce((previous, current) => {
110
- getStyleElement(current, previous).innerHTML = result.getLayer(current) ?? "";
111
- return current;
112
- }, void 0);
113
- tokens = result.matched;
114
- return {
115
- ...result,
116
- getStyleElement: (layer) => styleElements.get(layer),
117
- getStyleElements: () => styleElements
118
- };
119
- }
120
- async function extract(str) {
121
- const tokenSize = tokens.size;
122
- await uno.applyExtractors(str, void 0, tokens);
123
- if (tokenSize !== tokens.size)
124
- await scheduleUpdate();
125
- }
126
- async function extractAll(target = rootElement()) {
127
- const outerHTML = target && target.outerHTML;
128
- if (outerHTML) {
129
- await extract(`${outerHTML} ${decodeHtml(outerHTML)}`);
130
- removeCloak(html());
131
- removeCloak(target);
132
- }
133
- }
134
- const mutationObserver = new MutationObserver((mutations) => {
135
- if (paused)
136
- return;
137
- mutations.forEach(async (mutation) => {
138
- if (mutation.target.nodeType !== 1)
139
- return;
140
- const target = mutation.target;
141
- for (const item of styleElements) {
142
- if (target === item[1])
143
- return;
144
- }
145
- if (mutation.type === "childList") {
146
- mutation.addedNodes.forEach(async (node) => {
147
- if (node.nodeType !== 1)
148
- return;
149
- const el = node;
150
- if (inspector && !inspector(el))
151
- return;
152
- await extract(el.outerHTML);
153
- removeCloak(el);
154
- });
155
- } else {
156
- if (inspector && !inspector(target))
157
- return;
158
- if (mutation.attributeName !== cloakAttribute) {
159
- const attrs = Array.from(target.attributes).map((i) => i.value ? `${i.name}="${i.value}"` : i.name).join(" ");
160
- const tag = `<${target.tagName.toLowerCase()} ${attrs}>`;
161
- await extract(tag);
162
- }
163
- if (target.hasAttribute(cloakAttribute))
164
- target.removeAttribute(cloakAttribute);
165
- }
166
- });
167
- });
168
- let observing = false;
169
- function observe() {
170
- if (observing)
171
- return;
172
- const target = runtimeOptions.observer?.target ? runtimeOptions.observer.target() : rootElement();
173
- if (!target)
174
- return;
175
- mutationObserver.observe(target, {
176
- childList: true,
177
- subtree: true,
178
- attributes: true,
179
- attributeFilter: runtimeOptions.observer?.attributeFilter
180
- });
181
- observing = true;
182
- }
183
- function execute() {
184
- if (runtimeOptions.bypassDefined)
185
- getDefinedCssSelectors(uno.blocked);
186
- extractAll();
187
- observe();
188
- }
189
- function ready() {
190
- if (defaultDocument.readyState === "loading")
191
- defaultWindow.addEventListener("DOMContentLoaded", execute);
192
- else
193
- execute();
194
- }
195
- const unoCssRuntime = defaultWindow.__unocss_runtime = defaultWindow.__unocss_runtime = {
196
- version: uno.version,
197
- uno,
198
- async extract(userTokens) {
199
- if (!isString(userTokens)) {
200
- userTokens.forEach((t) => tokens.add(t));
201
- userTokens = "";
202
- }
203
- await extract(userTokens);
204
- },
205
- extractAll,
206
- inspect(callback) {
207
- inspector = callback;
208
- },
209
- toggleObserver(set) {
210
- if (set === void 0)
211
- paused = !paused;
212
- else
213
- paused = !!set;
214
- if (!observing && !paused)
215
- ready();
216
- },
217
- update: updateStyle,
218
- presets: defaultWindow.__unocss_runtime?.presets ?? {}
219
- };
220
- if (runtimeOptions.ready?.(unoCssRuntime) !== false) {
221
- paused = false;
222
- ready();
223
- }
224
- }
225
- function getDefinedCssSelectors(selectors = /* @__PURE__ */ new Set()) {
226
- for (let i = 0; i < document.styleSheets.length; i++) {
227
- const sheet = document.styleSheets[i];
228
- let list;
229
- try {
230
- list = sheet.cssRules || sheet.rules;
231
- if (!list)
232
- continue;
233
- Array.from(list).flatMap((r) => r.selectorText?.split(/,/g) || []).forEach((s) => {
234
- if (!s)
235
- return;
236
- s = s.trim();
237
- if (s.startsWith("."))
238
- s = s.slice(1);
239
- selectors.add(s);
240
- });
241
- } catch (e) {
242
- continue;
243
- }
244
- }
245
- return selectors;
246
- }
247
- export {
248
- init as default
249
- };