@unocss/svelte-scoped 0.52.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @unocss/svelte-scoped
2
+
3
+ Place generated CSS for each Svelte component's utility styles directly into the Svelte component's `<style>` block instead of in a global CSS file.
4
+
5
+ ## Documentation
6
+
7
+ Please refer to the [documentation](https://unocss.dev/integrations/svelte-scoped).
@@ -0,0 +1,448 @@
1
+ 'use strict';
2
+
3
+ const core = require('@unocss/core');
4
+ const presetUno = require('@unocss/preset-uno');
5
+ const config = require('@unocss/config');
6
+ const MagicString = require('magic-string');
7
+ const cssTree = require('css-tree');
8
+
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
10
+
11
+ const presetUno__default = /*#__PURE__*/_interopDefaultLegacy(presetUno);
12
+ const MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
13
+
14
+ const NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE = /(?<![\d(])/;
15
+ const SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE = /([[\.][\S\s]+?)/;
16
+ const STYLES_RE = /({[\S\s]+?})/;
17
+ const EXTRACT_SELECTOR_RE = new RegExp(NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE.source + SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE.source + STYLES_RE.source, "g");
18
+ function wrapSelectorsWithGlobal(css) {
19
+ return css.replace(EXTRACT_SELECTOR_RE, ":global($1)$2");
20
+ }
21
+
22
+ const classesRE$1 = /class=(["'\`])([\S\s]*?)\1/g;
23
+ const classDirectivesRE = /class:([\S]+?)={/g;
24
+ const classDirectivesShorthandRE = /class:([^=>\s/]+)[{>\s/]/g;
25
+ function findClasses(code) {
26
+ const matchedClasses = [...code.matchAll(classesRE$1)];
27
+ const matchedClassDirectives = [...code.matchAll(classDirectivesRE)];
28
+ const matchedClassDirectivesShorthand = [...code.matchAll(classDirectivesShorthandRE)];
29
+ const classes = parseMatches(matchedClasses, "regular", 'class="'.length);
30
+ const classDirectives = parseMatches(matchedClassDirectives, "directive", "class:".length);
31
+ const classDirectivesShorthand = parseMatches(matchedClassDirectivesShorthand, "directiveShorthand", "class:".length);
32
+ return [...classes, ...classDirectives, ...classDirectivesShorthand];
33
+ }
34
+ function parseMatches(matches, type, prefixLength) {
35
+ return matches.map((match) => {
36
+ const body = match[type === "regular" ? 2 : 1];
37
+ const start = match.index + prefixLength;
38
+ return {
39
+ body: body.trim(),
40
+ start,
41
+ end: start + body.length,
42
+ type
43
+ };
44
+ }).filter(hasBody);
45
+ }
46
+ function hasBody(foundClass) {
47
+ return foundClass.body;
48
+ }
49
+
50
+ const notInCommentRE = /(?<!<!--\s*)/;
51
+ const stylesTagWithCapturedDirectivesRE = /<style([^>]*)>[\s\S]*?<\/style\s*>/;
52
+ const actualStylesTagWithCapturedDirectivesRE = new RegExp(notInCommentRE.source + stylesTagWithCapturedDirectivesRE.source, "g");
53
+ const captureOpeningStyleTagWithAttributesRE = /(<style[^>]*>)/;
54
+ function addGeneratedStylesIntoStyleBlock(code, styles) {
55
+ const preExistingStylesTag = code.match(actualStylesTagWithCapturedDirectivesRE);
56
+ if (preExistingStylesTag)
57
+ return code.replace(captureOpeningStyleTagWithAttributesRE, `$1${styles}`);
58
+ return `${code}
59
+ <style>${styles}</style>`;
60
+ }
61
+
62
+ async function needsGenerated(token, uno) {
63
+ const inSafelist = uno.config.safelist.includes(token);
64
+ if (inSafelist)
65
+ return false;
66
+ const result = await uno.parseToken(token);
67
+ return !!result;
68
+ }
69
+
70
+ function hash(str) {
71
+ let i;
72
+ let l;
73
+ let hval = 2166136261;
74
+ for (i = 0, l = str.length; i < l; i++) {
75
+ hval ^= str.charCodeAt(i);
76
+ hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
77
+ }
78
+ return `00000${(hval >>> 0).toString(36)}`.slice(-6);
79
+ }
80
+
81
+ function generateClassName(body, options, filename) {
82
+ const {
83
+ classPrefix = "uno-",
84
+ combine = true,
85
+ hashFn = hash
86
+ } = options;
87
+ if (combine) {
88
+ const classPlusFilenameHash = hashFn(body + filename);
89
+ return `${classPrefix}${classPlusFilenameHash}`;
90
+ } else {
91
+ const filenameHash = hashFn(filename);
92
+ return `_${body}_${filenameHash}`;
93
+ }
94
+ }
95
+
96
+ function isShortcut(token, shortcuts) {
97
+ return shortcuts.some((s) => s[0] === token);
98
+ }
99
+
100
+ async function processDirective({ body: token, start, end, type }, options, uno, filename) {
101
+ const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
102
+ if (!isShortcutOrUtility)
103
+ return;
104
+ const generatedClassName = generateClassName(token, options, filename);
105
+ const content = type === "directiveShorthand" ? `${generatedClassName}={${token}}` : generatedClassName;
106
+ return {
107
+ rulesToGenerate: { [generatedClassName]: [token] },
108
+ codeUpdate: { content, start, end }
109
+ };
110
+ }
111
+
112
+ async function sortClassesIntoCategories(body, options, uno, filename) {
113
+ const { combine = true } = options;
114
+ const rulesToGenerate = {};
115
+ const ignore = [];
116
+ const classes = body.trim().split(/\s+/);
117
+ const knownClassesToCombine = [];
118
+ for (const token of classes) {
119
+ const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
120
+ if (!isShortcutOrUtility) {
121
+ ignore.push(token);
122
+ continue;
123
+ }
124
+ if (combine) {
125
+ knownClassesToCombine.push(token);
126
+ } else {
127
+ const generatedClassName = generateClassName(token, options, filename);
128
+ rulesToGenerate[generatedClassName] = [token];
129
+ }
130
+ }
131
+ if (knownClassesToCombine.length) {
132
+ const generatedClassName = generateClassName(knownClassesToCombine.join(" "), options, filename);
133
+ rulesToGenerate[generatedClassName] = knownClassesToCombine;
134
+ }
135
+ return { rulesToGenerate, ignore };
136
+ }
137
+
138
+ const expressionsRE = /{[^{}]+?}/g;
139
+ const classesRE = /(["'\`])([\S\s]+?)\1/g;
140
+ async function processExpressions(body, options, uno, filename) {
141
+ const rulesToGenerate = {};
142
+ const updatedExpressions = [];
143
+ let restOfBody = body;
144
+ const expressions = [...body.matchAll(expressionsRE)];
145
+ for (let [expression] of expressions) {
146
+ restOfBody = restOfBody.replace(expression, "").trim();
147
+ const classes = [...expression.matchAll(classesRE)];
148
+ for (const [withQuotes, quoteMark, withoutQuotes] of classes) {
149
+ const { rulesToGenerate: rulesFromExpression, ignore } = await sortClassesIntoCategories(withoutQuotes, options, uno, filename);
150
+ Object.assign(rulesToGenerate, rulesFromExpression);
151
+ const updatedClasses = Object.keys(rulesFromExpression).concat(ignore).join(" ");
152
+ expression = expression.replace(withQuotes, quoteMark + updatedClasses + quoteMark);
153
+ }
154
+ updatedExpressions.push(expression);
155
+ }
156
+ return { rulesToGenerate, updatedExpressions, restOfBody };
157
+ }
158
+
159
+ async function processClassBody({ body, start, end }, options, uno, filename) {
160
+ const expandedBody = core.expandVariantGroup(body);
161
+ const { rulesToGenerate: rulesFromExpressions, restOfBody, updatedExpressions } = await processExpressions(expandedBody, options, uno, filename);
162
+ const { rulesToGenerate: rulesFromRegularClasses, ignore } = await sortClassesIntoCategories(restOfBody, options, uno, filename);
163
+ const rulesToGenerate = { ...rulesFromExpressions, ...rulesFromRegularClasses };
164
+ if (!Object.keys(rulesToGenerate).length)
165
+ return {};
166
+ const content = Object.keys(rulesFromRegularClasses).concat(ignore).concat(updatedExpressions).join(" ");
167
+ const codeUpdate = {
168
+ content,
169
+ start,
170
+ end
171
+ };
172
+ return { rulesToGenerate, codeUpdate };
173
+ }
174
+
175
+ async function processClasses(classes, options, uno, filename) {
176
+ const result = {
177
+ rulesToGenerate: {},
178
+ codeUpdates: []
179
+ };
180
+ for (const foundClass of classes) {
181
+ if (foundClass.type === "regular") {
182
+ const { rulesToGenerate, codeUpdate } = await processClassBody(foundClass, options, uno, filename);
183
+ if (rulesToGenerate)
184
+ Object.assign(result.rulesToGenerate, rulesToGenerate);
185
+ if (codeUpdate)
186
+ result.codeUpdates.push(codeUpdate);
187
+ } else {
188
+ const { rulesToGenerate, codeUpdate } = await processDirective(foundClass, options, uno, filename) || {};
189
+ if (rulesToGenerate)
190
+ Object.assign(result.rulesToGenerate, rulesToGenerate);
191
+ if (codeUpdate)
192
+ result.codeUpdates.push(codeUpdate);
193
+ }
194
+ }
195
+ return result;
196
+ }
197
+
198
+ async function transformClasses({ content, filename, uno, options }) {
199
+ const classesToProcess = findClasses(content);
200
+ if (!classesToProcess.length)
201
+ return;
202
+ const { rulesToGenerate, codeUpdates } = await processClasses(classesToProcess, options, uno, filename);
203
+ if (!Object.keys(rulesToGenerate).length)
204
+ return;
205
+ const { map, code } = updateTemplateCodeIfNeeded(codeUpdates, content, filename);
206
+ const generatedStyles = await generateStyles(rulesToGenerate, uno);
207
+ const codeWithGeneratedStyles = addGeneratedStylesIntoStyleBlock(code, generatedStyles);
208
+ return {
209
+ code: codeWithGeneratedStyles,
210
+ map
211
+ };
212
+ }
213
+ function updateTemplateCodeIfNeeded(codeUpdates, source, filename) {
214
+ if (!codeUpdates.length)
215
+ return { code: source, map: void 0 };
216
+ const s = new MagicString__default(source);
217
+ for (const { start, end, content } of codeUpdates)
218
+ s.overwrite(start, end, content);
219
+ return {
220
+ code: s.toString(),
221
+ map: s.generateMap({ hires: true, source: filename })
222
+ };
223
+ }
224
+ const removeCommentsToMakeGlobalWrappingEasy = true;
225
+ async function generateStyles(rulesToGenerate, uno) {
226
+ const originalShortcuts = uno.config.shortcuts;
227
+ const shortcutsForThisComponent = Object.entries(rulesToGenerate);
228
+ uno.config.shortcuts = [...originalShortcuts, ...shortcutsForThisComponent];
229
+ const selectorsToGenerate = Object.keys(rulesToGenerate);
230
+ const { css } = await uno.generate(
231
+ selectorsToGenerate,
232
+ {
233
+ preflights: false,
234
+ safelist: false,
235
+ minify: removeCommentsToMakeGlobalWrappingEasy
236
+ }
237
+ );
238
+ uno.config.shortcuts = originalShortcuts;
239
+ const cssPreparedForSvelteCompiler = wrapSelectorsWithGlobal(css);
240
+ return cssPreparedForSvelteCompiler;
241
+ }
242
+
243
+ function removeOuterQuotes(input) {
244
+ if (!input)
245
+ return "";
246
+ const match = input.match(/^(['"]).*\1$/);
247
+ return match ? input.slice(1, -1) : input;
248
+ }
249
+
250
+ function writeUtilStyles([, selector, body, parent], s, node, childNode) {
251
+ if (!selector)
252
+ return;
253
+ const selectorChanged = selector !== ".\\-";
254
+ if (!parent && !selectorChanged)
255
+ return s.appendRight(childNode.loc.end.offset, body);
256
+ const originalSelector = cssTree.generate(node.prelude);
257
+ if (parent && !selectorChanged) {
258
+ const css2 = `${parent}{${originalSelector}{${body}}}`;
259
+ return s.appendLeft(node.loc.end.offset, css2);
260
+ }
261
+ const utilSelector = selector.replace(core.regexScopePlaceholder, " ");
262
+ const updatedSelector = generateUpdatedSelector(utilSelector, node.prelude);
263
+ const svelteCompilerReadySelector = surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector);
264
+ const rule = `${svelteCompilerReadySelector}{${body}}`;
265
+ const css = parent ? `${parent}{${rule}}` : rule;
266
+ s.appendLeft(node.loc.end.offset, css);
267
+ }
268
+ function generateUpdatedSelector(selector, _prelude) {
269
+ const selectorAST = cssTree.parse(selector, {
270
+ context: "selector"
271
+ });
272
+ const prelude = cssTree.clone(_prelude);
273
+ prelude.children.forEach((child) => {
274
+ const parentSelectorAst = cssTree.clone(selectorAST);
275
+ parentSelectorAst.children.forEach((i) => {
276
+ if (i.type === "ClassSelector" && i.name === "\\-")
277
+ Object.assign(i, cssTree.clone(child));
278
+ });
279
+ Object.assign(child, parentSelectorAst);
280
+ });
281
+ return cssTree.generate(prelude);
282
+ }
283
+ function surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector) {
284
+ const wrapWithGlobal = (str) => `:global(${str})`;
285
+ const originalSelectors = originalSelector.split(",").map((s) => s.trim());
286
+ const updatedSelectors = updatedSelector.split(",").map((s) => s.trim());
287
+ const resultSelectors = originalSelectors.map((original, index) => {
288
+ const updated = updatedSelectors[index];
289
+ const [prefix, suffix] = updated.split(original).map((s) => s.trim());
290
+ const wrappedPrefix = prefix ? wrapWithGlobal(prefix) : "";
291
+ if (!suffix)
292
+ return `${wrappedPrefix} ${original}`.trim();
293
+ const indexOfFirstCombinator = findFirstCombinatorIndex(suffix);
294
+ if (indexOfFirstCombinator === -1)
295
+ return `${wrappedPrefix} ${original}${suffix}`.trim();
296
+ const pseudo = suffix.substring(0, indexOfFirstCombinator).trim();
297
+ const siblingsOrDescendants = suffix.substring(indexOfFirstCombinator).trim();
298
+ return `${wrappedPrefix} ${original}${pseudo} ${wrapWithGlobal(siblingsOrDescendants)}`.trim();
299
+ });
300
+ return resultSelectors.join(", ");
301
+ }
302
+ function findFirstCombinatorIndex(input) {
303
+ const combinators = [" ", ">", "~", "+"];
304
+ for (const c of combinators) {
305
+ const indexOfFirstCombinator = input.indexOf(c);
306
+ if (indexOfFirstCombinator !== -1)
307
+ return indexOfFirstCombinator;
308
+ }
309
+ return -1;
310
+ }
311
+
312
+ async function getUtils(body, uno) {
313
+ const classNames = core.expandVariantGroup(body).split(/\s+/g).map((className) => className.trim().replace(/\\/, ""));
314
+ const utils = await parseUtils(classNames, uno);
315
+ const sortedByRankIndex = utils.sort(([aIndex], [bIndex]) => aIndex - bIndex);
316
+ const sortedByParentOrders = sortedByRankIndex.sort(([, , , aParent], [, , , bParent]) => (aParent ? uno.parentOrders.get(aParent) ?? 0 : 0) - (bParent ? uno.parentOrders.get(bParent) ?? 0 : 0));
317
+ return sortedByParentOrders.reduce((acc, item) => {
318
+ const [, selector, body2, parent] = item;
319
+ const sibling = acc.find(([, targetSelector, , targetParent]) => targetSelector === selector && targetParent === parent);
320
+ if (sibling)
321
+ sibling[2] += body2;
322
+ else
323
+ acc.push([...item]);
324
+ return acc;
325
+ }, []);
326
+ }
327
+ async function parseUtils(classNames, uno) {
328
+ const foundUtils = [];
329
+ for (const token of classNames) {
330
+ const util = await uno.parseToken(token, "-");
331
+ if (util)
332
+ foundUtils.push(util);
333
+ else
334
+ core.warnOnce(`'${token}' not found. You have a typo or need to add a preset.`);
335
+ }
336
+ return foundUtils.flat();
337
+ }
338
+
339
+ const DEFAULT_APPLY_VARIABLES = ["--at-apply"];
340
+ async function transformApply({ content, uno, prepend, applyVariables, filename }) {
341
+ applyVariables = core.toArray(applyVariables || DEFAULT_APPLY_VARIABLES);
342
+ const hasApply = content.includes("@apply") || applyVariables.some((v) => content.includes(v));
343
+ if (!hasApply)
344
+ return;
345
+ const s = new MagicString__default(content);
346
+ await walkCss({ s, uno, applyVariables });
347
+ if (!s.hasChanged())
348
+ return;
349
+ if (prepend)
350
+ s.prepend(prepend);
351
+ return {
352
+ code: s.toString(),
353
+ map: s.generateMap({ hires: true, source: filename || "" })
354
+ };
355
+ }
356
+ async function walkCss(ctx) {
357
+ const ast = cssTree.parse(ctx.s.original, {
358
+ parseAtrulePrelude: false,
359
+ positions: true
360
+ });
361
+ if (ast.type !== "StyleSheet")
362
+ return;
363
+ const stack = [];
364
+ cssTree.walk(ast, (node) => {
365
+ if (node.type === "Rule")
366
+ stack.push(handleApply(ctx, node));
367
+ });
368
+ await Promise.all(stack);
369
+ }
370
+ async function handleApply(ctx, node) {
371
+ const parsePromises = node.block.children.map(async (childNode) => {
372
+ await parseApply(ctx, node, childNode);
373
+ });
374
+ await Promise.all(parsePromises);
375
+ }
376
+ async function parseApply({ s, uno, applyVariables }, node, childNode) {
377
+ const body = getChildNodeValue(childNode, applyVariables);
378
+ if (!body)
379
+ return;
380
+ const utils = await getUtils(body, uno);
381
+ if (!utils.length)
382
+ return;
383
+ for (const util of utils)
384
+ writeUtilStyles(util, s, node, childNode);
385
+ s.remove(childNode.loc.start.offset, childNode.loc.end.offset);
386
+ }
387
+ function getChildNodeValue(childNode, applyVariables) {
388
+ if (childNode.type === "Atrule" && childNode.name === "apply" && childNode.prelude && childNode.prelude.type === "Raw")
389
+ return childNode.prelude.value.trim();
390
+ if (childNode.type === "Declaration" && applyVariables.includes(childNode.property) && childNode.value.type === "Raw")
391
+ return removeOuterQuotes(childNode.value.value.trim());
392
+ }
393
+
394
+ function UnocssSveltePreprocess(options = {}, unoContextFromVite) {
395
+ if (!options.classPrefix)
396
+ options.classPrefix = "spu-";
397
+ let uno;
398
+ return {
399
+ markup: async ({ content, filename }) => {
400
+ if (!uno)
401
+ uno = await getGenerator(options.configOrPath, unoContextFromVite);
402
+ return await transformClasses({ content, filename: filename || "", uno, options });
403
+ },
404
+ style: async ({ content, attributes, filename }) => {
405
+ const addPreflights = !!attributes["uno:preflights"];
406
+ const addSafelist = !!attributes["uno:safelist"];
407
+ const checkForApply = options.applyVariables !== false;
408
+ const changeNeeded = addPreflights || addSafelist || checkForApply;
409
+ if (!changeNeeded)
410
+ return;
411
+ if (!uno)
412
+ uno = await getGenerator(options.configOrPath);
413
+ let preflightsSafelistCss = "";
414
+ if (addPreflights || addSafelist) {
415
+ if (unoContextFromVite)
416
+ core.warnOnce("Do not place preflights or safelist within an individual component as they already placed in your global styles injected into the head tag. These options are only for component libraries.");
417
+ const { css } = await uno.generate([], { preflights: addPreflights, safelist: addSafelist, minify: true });
418
+ preflightsSafelistCss = css;
419
+ }
420
+ if (checkForApply) {
421
+ return await transformApply({
422
+ content,
423
+ prepend: preflightsSafelistCss,
424
+ uno,
425
+ applyVariables: options.applyVariables,
426
+ filename
427
+ });
428
+ }
429
+ if (preflightsSafelistCss)
430
+ return { code: preflightsSafelistCss };
431
+ }
432
+ };
433
+ }
434
+ async function getGenerator(configOrPath, unoContextFromVite) {
435
+ if (unoContextFromVite) {
436
+ await unoContextFromVite.ready;
437
+ return unoContextFromVite.uno;
438
+ }
439
+ const defaults = {
440
+ presets: [
441
+ presetUno__default()
442
+ ]
443
+ };
444
+ const { config: config$1 } = await config.loadConfig(process.cwd(), configOrPath);
445
+ return core.createGenerator(config$1, defaults);
446
+ }
447
+
448
+ module.exports = UnocssSveltePreprocess;
@@ -0,0 +1,8 @@
1
+ import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
2
+ import { U as UnocssSveltePreprocessOptions, S as SvelteScopedContext } from './types.d-48b837f0.js';
3
+ export { S as SvelteScopedContext, a as TransformApplyOptions, T as TransformClassesOptions, U as UnocssSveltePreprocessOptions } from './types.d-48b837f0.js';
4
+ import '@unocss/core';
5
+
6
+ declare function UnocssSveltePreprocess(options?: UnocssSveltePreprocessOptions, unoContextFromVite?: SvelteScopedContext): PreprocessorGroup;
7
+
8
+ export { UnocssSveltePreprocess as default };