@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 +21 -0
- package/README.md +7 -0
- package/dist/preprocess.cjs +448 -0
- package/dist/preprocess.d.ts +8 -0
- package/dist/preprocess.mjs +441 -0
- package/dist/types.d-48b837f0.d.ts +44 -0
- package/dist/vite.cjs +165 -0
- package/dist/vite.d.ts +36 -0
- package/dist/vite.mjs +163 -0
- package/package.json +69 -0
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
import { expandVariantGroup, regexScopePlaceholder, warnOnce, toArray, createGenerator } from '@unocss/core';
|
|
2
|
+
import presetUno from '@unocss/preset-uno';
|
|
3
|
+
import { loadConfig } from '@unocss/config';
|
|
4
|
+
import MagicString from 'magic-string';
|
|
5
|
+
import { generate, parse, clone, walk } from 'css-tree';
|
|
6
|
+
|
|
7
|
+
const NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE = /(?<![\d(])/;
|
|
8
|
+
const SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE = /([[\.][\S\s]+?)/;
|
|
9
|
+
const STYLES_RE = /({[\S\s]+?})/;
|
|
10
|
+
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");
|
|
11
|
+
function wrapSelectorsWithGlobal(css) {
|
|
12
|
+
return css.replace(EXTRACT_SELECTOR_RE, ":global($1)$2");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const classesRE$1 = /class=(["'\`])([\S\s]*?)\1/g;
|
|
16
|
+
const classDirectivesRE = /class:([\S]+?)={/g;
|
|
17
|
+
const classDirectivesShorthandRE = /class:([^=>\s/]+)[{>\s/]/g;
|
|
18
|
+
function findClasses(code) {
|
|
19
|
+
const matchedClasses = [...code.matchAll(classesRE$1)];
|
|
20
|
+
const matchedClassDirectives = [...code.matchAll(classDirectivesRE)];
|
|
21
|
+
const matchedClassDirectivesShorthand = [...code.matchAll(classDirectivesShorthandRE)];
|
|
22
|
+
const classes = parseMatches(matchedClasses, "regular", 'class="'.length);
|
|
23
|
+
const classDirectives = parseMatches(matchedClassDirectives, "directive", "class:".length);
|
|
24
|
+
const classDirectivesShorthand = parseMatches(matchedClassDirectivesShorthand, "directiveShorthand", "class:".length);
|
|
25
|
+
return [...classes, ...classDirectives, ...classDirectivesShorthand];
|
|
26
|
+
}
|
|
27
|
+
function parseMatches(matches, type, prefixLength) {
|
|
28
|
+
return matches.map((match) => {
|
|
29
|
+
const body = match[type === "regular" ? 2 : 1];
|
|
30
|
+
const start = match.index + prefixLength;
|
|
31
|
+
return {
|
|
32
|
+
body: body.trim(),
|
|
33
|
+
start,
|
|
34
|
+
end: start + body.length,
|
|
35
|
+
type
|
|
36
|
+
};
|
|
37
|
+
}).filter(hasBody);
|
|
38
|
+
}
|
|
39
|
+
function hasBody(foundClass) {
|
|
40
|
+
return foundClass.body;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const notInCommentRE = /(?<!<!--\s*)/;
|
|
44
|
+
const stylesTagWithCapturedDirectivesRE = /<style([^>]*)>[\s\S]*?<\/style\s*>/;
|
|
45
|
+
const actualStylesTagWithCapturedDirectivesRE = new RegExp(notInCommentRE.source + stylesTagWithCapturedDirectivesRE.source, "g");
|
|
46
|
+
const captureOpeningStyleTagWithAttributesRE = /(<style[^>]*>)/;
|
|
47
|
+
function addGeneratedStylesIntoStyleBlock(code, styles) {
|
|
48
|
+
const preExistingStylesTag = code.match(actualStylesTagWithCapturedDirectivesRE);
|
|
49
|
+
if (preExistingStylesTag)
|
|
50
|
+
return code.replace(captureOpeningStyleTagWithAttributesRE, `$1${styles}`);
|
|
51
|
+
return `${code}
|
|
52
|
+
<style>${styles}</style>`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function needsGenerated(token, uno) {
|
|
56
|
+
const inSafelist = uno.config.safelist.includes(token);
|
|
57
|
+
if (inSafelist)
|
|
58
|
+
return false;
|
|
59
|
+
const result = await uno.parseToken(token);
|
|
60
|
+
return !!result;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function hash(str) {
|
|
64
|
+
let i;
|
|
65
|
+
let l;
|
|
66
|
+
let hval = 2166136261;
|
|
67
|
+
for (i = 0, l = str.length; i < l; i++) {
|
|
68
|
+
hval ^= str.charCodeAt(i);
|
|
69
|
+
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
|
|
70
|
+
}
|
|
71
|
+
return `00000${(hval >>> 0).toString(36)}`.slice(-6);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function generateClassName(body, options, filename) {
|
|
75
|
+
const {
|
|
76
|
+
classPrefix = "uno-",
|
|
77
|
+
combine = true,
|
|
78
|
+
hashFn = hash
|
|
79
|
+
} = options;
|
|
80
|
+
if (combine) {
|
|
81
|
+
const classPlusFilenameHash = hashFn(body + filename);
|
|
82
|
+
return `${classPrefix}${classPlusFilenameHash}`;
|
|
83
|
+
} else {
|
|
84
|
+
const filenameHash = hashFn(filename);
|
|
85
|
+
return `_${body}_${filenameHash}`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isShortcut(token, shortcuts) {
|
|
90
|
+
return shortcuts.some((s) => s[0] === token);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function processDirective({ body: token, start, end, type }, options, uno, filename) {
|
|
94
|
+
const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
|
|
95
|
+
if (!isShortcutOrUtility)
|
|
96
|
+
return;
|
|
97
|
+
const generatedClassName = generateClassName(token, options, filename);
|
|
98
|
+
const content = type === "directiveShorthand" ? `${generatedClassName}={${token}}` : generatedClassName;
|
|
99
|
+
return {
|
|
100
|
+
rulesToGenerate: { [generatedClassName]: [token] },
|
|
101
|
+
codeUpdate: { content, start, end }
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function sortClassesIntoCategories(body, options, uno, filename) {
|
|
106
|
+
const { combine = true } = options;
|
|
107
|
+
const rulesToGenerate = {};
|
|
108
|
+
const ignore = [];
|
|
109
|
+
const classes = body.trim().split(/\s+/);
|
|
110
|
+
const knownClassesToCombine = [];
|
|
111
|
+
for (const token of classes) {
|
|
112
|
+
const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
|
|
113
|
+
if (!isShortcutOrUtility) {
|
|
114
|
+
ignore.push(token);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (combine) {
|
|
118
|
+
knownClassesToCombine.push(token);
|
|
119
|
+
} else {
|
|
120
|
+
const generatedClassName = generateClassName(token, options, filename);
|
|
121
|
+
rulesToGenerate[generatedClassName] = [token];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (knownClassesToCombine.length) {
|
|
125
|
+
const generatedClassName = generateClassName(knownClassesToCombine.join(" "), options, filename);
|
|
126
|
+
rulesToGenerate[generatedClassName] = knownClassesToCombine;
|
|
127
|
+
}
|
|
128
|
+
return { rulesToGenerate, ignore };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const expressionsRE = /{[^{}]+?}/g;
|
|
132
|
+
const classesRE = /(["'\`])([\S\s]+?)\1/g;
|
|
133
|
+
async function processExpressions(body, options, uno, filename) {
|
|
134
|
+
const rulesToGenerate = {};
|
|
135
|
+
const updatedExpressions = [];
|
|
136
|
+
let restOfBody = body;
|
|
137
|
+
const expressions = [...body.matchAll(expressionsRE)];
|
|
138
|
+
for (let [expression] of expressions) {
|
|
139
|
+
restOfBody = restOfBody.replace(expression, "").trim();
|
|
140
|
+
const classes = [...expression.matchAll(classesRE)];
|
|
141
|
+
for (const [withQuotes, quoteMark, withoutQuotes] of classes) {
|
|
142
|
+
const { rulesToGenerate: rulesFromExpression, ignore } = await sortClassesIntoCategories(withoutQuotes, options, uno, filename);
|
|
143
|
+
Object.assign(rulesToGenerate, rulesFromExpression);
|
|
144
|
+
const updatedClasses = Object.keys(rulesFromExpression).concat(ignore).join(" ");
|
|
145
|
+
expression = expression.replace(withQuotes, quoteMark + updatedClasses + quoteMark);
|
|
146
|
+
}
|
|
147
|
+
updatedExpressions.push(expression);
|
|
148
|
+
}
|
|
149
|
+
return { rulesToGenerate, updatedExpressions, restOfBody };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function processClassBody({ body, start, end }, options, uno, filename) {
|
|
153
|
+
const expandedBody = expandVariantGroup(body);
|
|
154
|
+
const { rulesToGenerate: rulesFromExpressions, restOfBody, updatedExpressions } = await processExpressions(expandedBody, options, uno, filename);
|
|
155
|
+
const { rulesToGenerate: rulesFromRegularClasses, ignore } = await sortClassesIntoCategories(restOfBody, options, uno, filename);
|
|
156
|
+
const rulesToGenerate = { ...rulesFromExpressions, ...rulesFromRegularClasses };
|
|
157
|
+
if (!Object.keys(rulesToGenerate).length)
|
|
158
|
+
return {};
|
|
159
|
+
const content = Object.keys(rulesFromRegularClasses).concat(ignore).concat(updatedExpressions).join(" ");
|
|
160
|
+
const codeUpdate = {
|
|
161
|
+
content,
|
|
162
|
+
start,
|
|
163
|
+
end
|
|
164
|
+
};
|
|
165
|
+
return { rulesToGenerate, codeUpdate };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function processClasses(classes, options, uno, filename) {
|
|
169
|
+
const result = {
|
|
170
|
+
rulesToGenerate: {},
|
|
171
|
+
codeUpdates: []
|
|
172
|
+
};
|
|
173
|
+
for (const foundClass of classes) {
|
|
174
|
+
if (foundClass.type === "regular") {
|
|
175
|
+
const { rulesToGenerate, codeUpdate } = await processClassBody(foundClass, options, uno, filename);
|
|
176
|
+
if (rulesToGenerate)
|
|
177
|
+
Object.assign(result.rulesToGenerate, rulesToGenerate);
|
|
178
|
+
if (codeUpdate)
|
|
179
|
+
result.codeUpdates.push(codeUpdate);
|
|
180
|
+
} else {
|
|
181
|
+
const { rulesToGenerate, codeUpdate } = await processDirective(foundClass, options, uno, filename) || {};
|
|
182
|
+
if (rulesToGenerate)
|
|
183
|
+
Object.assign(result.rulesToGenerate, rulesToGenerate);
|
|
184
|
+
if (codeUpdate)
|
|
185
|
+
result.codeUpdates.push(codeUpdate);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function transformClasses({ content, filename, uno, options }) {
|
|
192
|
+
const classesToProcess = findClasses(content);
|
|
193
|
+
if (!classesToProcess.length)
|
|
194
|
+
return;
|
|
195
|
+
const { rulesToGenerate, codeUpdates } = await processClasses(classesToProcess, options, uno, filename);
|
|
196
|
+
if (!Object.keys(rulesToGenerate).length)
|
|
197
|
+
return;
|
|
198
|
+
const { map, code } = updateTemplateCodeIfNeeded(codeUpdates, content, filename);
|
|
199
|
+
const generatedStyles = await generateStyles(rulesToGenerate, uno);
|
|
200
|
+
const codeWithGeneratedStyles = addGeneratedStylesIntoStyleBlock(code, generatedStyles);
|
|
201
|
+
return {
|
|
202
|
+
code: codeWithGeneratedStyles,
|
|
203
|
+
map
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function updateTemplateCodeIfNeeded(codeUpdates, source, filename) {
|
|
207
|
+
if (!codeUpdates.length)
|
|
208
|
+
return { code: source, map: void 0 };
|
|
209
|
+
const s = new MagicString(source);
|
|
210
|
+
for (const { start, end, content } of codeUpdates)
|
|
211
|
+
s.overwrite(start, end, content);
|
|
212
|
+
return {
|
|
213
|
+
code: s.toString(),
|
|
214
|
+
map: s.generateMap({ hires: true, source: filename })
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
const removeCommentsToMakeGlobalWrappingEasy = true;
|
|
218
|
+
async function generateStyles(rulesToGenerate, uno) {
|
|
219
|
+
const originalShortcuts = uno.config.shortcuts;
|
|
220
|
+
const shortcutsForThisComponent = Object.entries(rulesToGenerate);
|
|
221
|
+
uno.config.shortcuts = [...originalShortcuts, ...shortcutsForThisComponent];
|
|
222
|
+
const selectorsToGenerate = Object.keys(rulesToGenerate);
|
|
223
|
+
const { css } = await uno.generate(
|
|
224
|
+
selectorsToGenerate,
|
|
225
|
+
{
|
|
226
|
+
preflights: false,
|
|
227
|
+
safelist: false,
|
|
228
|
+
minify: removeCommentsToMakeGlobalWrappingEasy
|
|
229
|
+
}
|
|
230
|
+
);
|
|
231
|
+
uno.config.shortcuts = originalShortcuts;
|
|
232
|
+
const cssPreparedForSvelteCompiler = wrapSelectorsWithGlobal(css);
|
|
233
|
+
return cssPreparedForSvelteCompiler;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function removeOuterQuotes(input) {
|
|
237
|
+
if (!input)
|
|
238
|
+
return "";
|
|
239
|
+
const match = input.match(/^(['"]).*\1$/);
|
|
240
|
+
return match ? input.slice(1, -1) : input;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function writeUtilStyles([, selector, body, parent], s, node, childNode) {
|
|
244
|
+
if (!selector)
|
|
245
|
+
return;
|
|
246
|
+
const selectorChanged = selector !== ".\\-";
|
|
247
|
+
if (!parent && !selectorChanged)
|
|
248
|
+
return s.appendRight(childNode.loc.end.offset, body);
|
|
249
|
+
const originalSelector = generate(node.prelude);
|
|
250
|
+
if (parent && !selectorChanged) {
|
|
251
|
+
const css2 = `${parent}{${originalSelector}{${body}}}`;
|
|
252
|
+
return s.appendLeft(node.loc.end.offset, css2);
|
|
253
|
+
}
|
|
254
|
+
const utilSelector = selector.replace(regexScopePlaceholder, " ");
|
|
255
|
+
const updatedSelector = generateUpdatedSelector(utilSelector, node.prelude);
|
|
256
|
+
const svelteCompilerReadySelector = surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector);
|
|
257
|
+
const rule = `${svelteCompilerReadySelector}{${body}}`;
|
|
258
|
+
const css = parent ? `${parent}{${rule}}` : rule;
|
|
259
|
+
s.appendLeft(node.loc.end.offset, css);
|
|
260
|
+
}
|
|
261
|
+
function generateUpdatedSelector(selector, _prelude) {
|
|
262
|
+
const selectorAST = parse(selector, {
|
|
263
|
+
context: "selector"
|
|
264
|
+
});
|
|
265
|
+
const prelude = clone(_prelude);
|
|
266
|
+
prelude.children.forEach((child) => {
|
|
267
|
+
const parentSelectorAst = clone(selectorAST);
|
|
268
|
+
parentSelectorAst.children.forEach((i) => {
|
|
269
|
+
if (i.type === "ClassSelector" && i.name === "\\-")
|
|
270
|
+
Object.assign(i, clone(child));
|
|
271
|
+
});
|
|
272
|
+
Object.assign(child, parentSelectorAst);
|
|
273
|
+
});
|
|
274
|
+
return generate(prelude);
|
|
275
|
+
}
|
|
276
|
+
function surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector) {
|
|
277
|
+
const wrapWithGlobal = (str) => `:global(${str})`;
|
|
278
|
+
const originalSelectors = originalSelector.split(",").map((s) => s.trim());
|
|
279
|
+
const updatedSelectors = updatedSelector.split(",").map((s) => s.trim());
|
|
280
|
+
const resultSelectors = originalSelectors.map((original, index) => {
|
|
281
|
+
const updated = updatedSelectors[index];
|
|
282
|
+
const [prefix, suffix] = updated.split(original).map((s) => s.trim());
|
|
283
|
+
const wrappedPrefix = prefix ? wrapWithGlobal(prefix) : "";
|
|
284
|
+
if (!suffix)
|
|
285
|
+
return `${wrappedPrefix} ${original}`.trim();
|
|
286
|
+
const indexOfFirstCombinator = findFirstCombinatorIndex(suffix);
|
|
287
|
+
if (indexOfFirstCombinator === -1)
|
|
288
|
+
return `${wrappedPrefix} ${original}${suffix}`.trim();
|
|
289
|
+
const pseudo = suffix.substring(0, indexOfFirstCombinator).trim();
|
|
290
|
+
const siblingsOrDescendants = suffix.substring(indexOfFirstCombinator).trim();
|
|
291
|
+
return `${wrappedPrefix} ${original}${pseudo} ${wrapWithGlobal(siblingsOrDescendants)}`.trim();
|
|
292
|
+
});
|
|
293
|
+
return resultSelectors.join(", ");
|
|
294
|
+
}
|
|
295
|
+
function findFirstCombinatorIndex(input) {
|
|
296
|
+
const combinators = [" ", ">", "~", "+"];
|
|
297
|
+
for (const c of combinators) {
|
|
298
|
+
const indexOfFirstCombinator = input.indexOf(c);
|
|
299
|
+
if (indexOfFirstCombinator !== -1)
|
|
300
|
+
return indexOfFirstCombinator;
|
|
301
|
+
}
|
|
302
|
+
return -1;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function getUtils(body, uno) {
|
|
306
|
+
const classNames = expandVariantGroup(body).split(/\s+/g).map((className) => className.trim().replace(/\\/, ""));
|
|
307
|
+
const utils = await parseUtils(classNames, uno);
|
|
308
|
+
const sortedByRankIndex = utils.sort(([aIndex], [bIndex]) => aIndex - bIndex);
|
|
309
|
+
const sortedByParentOrders = sortedByRankIndex.sort(([, , , aParent], [, , , bParent]) => (aParent ? uno.parentOrders.get(aParent) ?? 0 : 0) - (bParent ? uno.parentOrders.get(bParent) ?? 0 : 0));
|
|
310
|
+
return sortedByParentOrders.reduce((acc, item) => {
|
|
311
|
+
const [, selector, body2, parent] = item;
|
|
312
|
+
const sibling = acc.find(([, targetSelector, , targetParent]) => targetSelector === selector && targetParent === parent);
|
|
313
|
+
if (sibling)
|
|
314
|
+
sibling[2] += body2;
|
|
315
|
+
else
|
|
316
|
+
acc.push([...item]);
|
|
317
|
+
return acc;
|
|
318
|
+
}, []);
|
|
319
|
+
}
|
|
320
|
+
async function parseUtils(classNames, uno) {
|
|
321
|
+
const foundUtils = [];
|
|
322
|
+
for (const token of classNames) {
|
|
323
|
+
const util = await uno.parseToken(token, "-");
|
|
324
|
+
if (util)
|
|
325
|
+
foundUtils.push(util);
|
|
326
|
+
else
|
|
327
|
+
warnOnce(`'${token}' not found. You have a typo or need to add a preset.`);
|
|
328
|
+
}
|
|
329
|
+
return foundUtils.flat();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const DEFAULT_APPLY_VARIABLES = ["--at-apply"];
|
|
333
|
+
async function transformApply({ content, uno, prepend, applyVariables, filename }) {
|
|
334
|
+
applyVariables = toArray(applyVariables || DEFAULT_APPLY_VARIABLES);
|
|
335
|
+
const hasApply = content.includes("@apply") || applyVariables.some((v) => content.includes(v));
|
|
336
|
+
if (!hasApply)
|
|
337
|
+
return;
|
|
338
|
+
const s = new MagicString(content);
|
|
339
|
+
await walkCss({ s, uno, applyVariables });
|
|
340
|
+
if (!s.hasChanged())
|
|
341
|
+
return;
|
|
342
|
+
if (prepend)
|
|
343
|
+
s.prepend(prepend);
|
|
344
|
+
return {
|
|
345
|
+
code: s.toString(),
|
|
346
|
+
map: s.generateMap({ hires: true, source: filename || "" })
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async function walkCss(ctx) {
|
|
350
|
+
const ast = parse(ctx.s.original, {
|
|
351
|
+
parseAtrulePrelude: false,
|
|
352
|
+
positions: true
|
|
353
|
+
});
|
|
354
|
+
if (ast.type !== "StyleSheet")
|
|
355
|
+
return;
|
|
356
|
+
const stack = [];
|
|
357
|
+
walk(ast, (node) => {
|
|
358
|
+
if (node.type === "Rule")
|
|
359
|
+
stack.push(handleApply(ctx, node));
|
|
360
|
+
});
|
|
361
|
+
await Promise.all(stack);
|
|
362
|
+
}
|
|
363
|
+
async function handleApply(ctx, node) {
|
|
364
|
+
const parsePromises = node.block.children.map(async (childNode) => {
|
|
365
|
+
await parseApply(ctx, node, childNode);
|
|
366
|
+
});
|
|
367
|
+
await Promise.all(parsePromises);
|
|
368
|
+
}
|
|
369
|
+
async function parseApply({ s, uno, applyVariables }, node, childNode) {
|
|
370
|
+
const body = getChildNodeValue(childNode, applyVariables);
|
|
371
|
+
if (!body)
|
|
372
|
+
return;
|
|
373
|
+
const utils = await getUtils(body, uno);
|
|
374
|
+
if (!utils.length)
|
|
375
|
+
return;
|
|
376
|
+
for (const util of utils)
|
|
377
|
+
writeUtilStyles(util, s, node, childNode);
|
|
378
|
+
s.remove(childNode.loc.start.offset, childNode.loc.end.offset);
|
|
379
|
+
}
|
|
380
|
+
function getChildNodeValue(childNode, applyVariables) {
|
|
381
|
+
if (childNode.type === "Atrule" && childNode.name === "apply" && childNode.prelude && childNode.prelude.type === "Raw")
|
|
382
|
+
return childNode.prelude.value.trim();
|
|
383
|
+
if (childNode.type === "Declaration" && applyVariables.includes(childNode.property) && childNode.value.type === "Raw")
|
|
384
|
+
return removeOuterQuotes(childNode.value.value.trim());
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function UnocssSveltePreprocess(options = {}, unoContextFromVite) {
|
|
388
|
+
if (!options.classPrefix)
|
|
389
|
+
options.classPrefix = "spu-";
|
|
390
|
+
let uno;
|
|
391
|
+
return {
|
|
392
|
+
markup: async ({ content, filename }) => {
|
|
393
|
+
if (!uno)
|
|
394
|
+
uno = await getGenerator(options.configOrPath, unoContextFromVite);
|
|
395
|
+
return await transformClasses({ content, filename: filename || "", uno, options });
|
|
396
|
+
},
|
|
397
|
+
style: async ({ content, attributes, filename }) => {
|
|
398
|
+
const addPreflights = !!attributes["uno:preflights"];
|
|
399
|
+
const addSafelist = !!attributes["uno:safelist"];
|
|
400
|
+
const checkForApply = options.applyVariables !== false;
|
|
401
|
+
const changeNeeded = addPreflights || addSafelist || checkForApply;
|
|
402
|
+
if (!changeNeeded)
|
|
403
|
+
return;
|
|
404
|
+
if (!uno)
|
|
405
|
+
uno = await getGenerator(options.configOrPath);
|
|
406
|
+
let preflightsSafelistCss = "";
|
|
407
|
+
if (addPreflights || addSafelist) {
|
|
408
|
+
if (unoContextFromVite)
|
|
409
|
+
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.");
|
|
410
|
+
const { css } = await uno.generate([], { preflights: addPreflights, safelist: addSafelist, minify: true });
|
|
411
|
+
preflightsSafelistCss = css;
|
|
412
|
+
}
|
|
413
|
+
if (checkForApply) {
|
|
414
|
+
return await transformApply({
|
|
415
|
+
content,
|
|
416
|
+
prepend: preflightsSafelistCss,
|
|
417
|
+
uno,
|
|
418
|
+
applyVariables: options.applyVariables,
|
|
419
|
+
filename
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
if (preflightsSafelistCss)
|
|
423
|
+
return { code: preflightsSafelistCss };
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
async function getGenerator(configOrPath, unoContextFromVite) {
|
|
428
|
+
if (unoContextFromVite) {
|
|
429
|
+
await unoContextFromVite.ready;
|
|
430
|
+
return unoContextFromVite.uno;
|
|
431
|
+
}
|
|
432
|
+
const defaults = {
|
|
433
|
+
presets: [
|
|
434
|
+
presetUno()
|
|
435
|
+
]
|
|
436
|
+
};
|
|
437
|
+
const { config } = await loadConfig(process.cwd(), configOrPath);
|
|
438
|
+
return createGenerator(config, defaults);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export { UnocssSveltePreprocess as default };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { UserConfig, UnoGenerator } from '@unocss/core';
|
|
2
|
+
|
|
3
|
+
interface UnocssSveltePreprocessOptions extends TransformClassesOptions, TransformApplyOptions {
|
|
4
|
+
/**
|
|
5
|
+
* UnoCSS config or path to config file. If not provided, will load unocss.config.ts/js. It's recommended to use the separate config file if you are having trouble with the UnoCSS extension in VSCode.
|
|
6
|
+
*/
|
|
7
|
+
configOrPath?: UserConfig | string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface TransformClassesOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Prefix for compiled class names. Distinct between `@unocss/svelte-scoped/vite` and `@unocss/svelte-scoped/preprocessor` to avoid bugs when using a component library built with `@unocss/svelte-scoped/preprocessor` in a project using `@unocss/svelte-scoped/vite`.
|
|
13
|
+
* @default 'uno-' // `@unocss/svelte-scoped/vite`
|
|
14
|
+
* @default 'usp-' // `@unocss/svelte-scoped/preprocessor`
|
|
15
|
+
*/
|
|
16
|
+
classPrefix?: string
|
|
17
|
+
/**
|
|
18
|
+
* Add hash and combine recognized tokens (optimal for production); set false in dev mode for easy dev tools toggling to allow for design adjustments in the browser
|
|
19
|
+
* @default true
|
|
20
|
+
*/
|
|
21
|
+
combine?: boolean
|
|
22
|
+
/**
|
|
23
|
+
* Used to generate hash for compiled class names
|
|
24
|
+
*/
|
|
25
|
+
hashFn?: (str: string) => string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface TransformApplyOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Transform CSS variables (recommended for CSS syntax compatibility) or @apply directives.
|
|
31
|
+
*
|
|
32
|
+
* Pass `false` to disable.
|
|
33
|
+
*
|
|
34
|
+
* @default ['--at-apply', '@apply']
|
|
35
|
+
*/
|
|
36
|
+
applyVariables?: string | string[] | false
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface SvelteScopedContext {
|
|
40
|
+
uno: UnoGenerator<{}>
|
|
41
|
+
ready: Promise<UserConfig<{}>>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { SvelteScopedContext as S, TransformClassesOptions as T, UnocssSveltePreprocessOptions as U, TransformApplyOptions as a };
|
package/dist/vite.cjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const core = require('@unocss/core');
|
|
4
|
+
const config = require('@unocss/config');
|
|
5
|
+
const preprocess = require('./preprocess.cjs');
|
|
6
|
+
const node_fs = require('node:fs');
|
|
7
|
+
const node_path = require('node:path');
|
|
8
|
+
const node_url = require('node:url');
|
|
9
|
+
require('@unocss/preset-uno');
|
|
10
|
+
require('magic-string');
|
|
11
|
+
require('css-tree');
|
|
12
|
+
|
|
13
|
+
function PassPreprocessToSveltePlugin(options = {}, ctx) {
|
|
14
|
+
return {
|
|
15
|
+
name: "unocss:svelte-scoped:pass-preprocess",
|
|
16
|
+
enforce: "pre",
|
|
17
|
+
configResolved(viteConfig) {
|
|
18
|
+
options = { ...options, combine: viteConfig.command === "build" };
|
|
19
|
+
},
|
|
20
|
+
api: {
|
|
21
|
+
sveltePreprocess: preprocess(options, ctx)
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const PLACEHOLDER_USER_SETS_IN_INDEX_HTML = "%unocss-svelte-scoped.global%";
|
|
27
|
+
const GLOBAL_STYLES_PLACEHOLDER = "unocss_svelte_scoped_global_styles";
|
|
28
|
+
const DEV_GLOBAL_STYLES_DATA_TITLE = "unocss-svelte-scoped global styles";
|
|
29
|
+
|
|
30
|
+
const _dirname = typeof __dirname !== "undefined" ? __dirname : node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('vite.cjs', document.baseURI).href))));
|
|
31
|
+
function getReset(injectReset) {
|
|
32
|
+
if (injectReset.startsWith("@unocss/reset")) {
|
|
33
|
+
const resolvedPNPM = node_path.resolve(node_path.resolve(_dirname, `../node_modules/${injectReset}`));
|
|
34
|
+
if (isFile(resolvedPNPM))
|
|
35
|
+
return node_fs.readFileSync(resolvedPNPM, "utf-8");
|
|
36
|
+
const resolvedNPM = node_path.resolve(process.cwd(), "node_modules", injectReset);
|
|
37
|
+
if (isFile(resolvedNPM))
|
|
38
|
+
return node_fs.readFileSync(resolvedNPM, "utf-8");
|
|
39
|
+
throw new Error(`"${injectReset}" given as your injectReset value is not found. Please make sure it is one of the five supported @unocss/reset options. If it is, file a bug report detailing your environment and package manager`);
|
|
40
|
+
}
|
|
41
|
+
if (injectReset.startsWith(".")) {
|
|
42
|
+
const resolved = node_path.resolve(process.cwd(), injectReset);
|
|
43
|
+
if (!isFile(resolved))
|
|
44
|
+
throw new Error(`"${injectReset}" given as your injectReset value is not a valid file path relative to the root of your project, where your vite config file sits. To give an example, if you placed a reset.css in your src directory, "./src/reset.css" would work.`);
|
|
45
|
+
return node_fs.readFileSync(resolved, "utf-8");
|
|
46
|
+
}
|
|
47
|
+
if (injectReset.startsWith("/"))
|
|
48
|
+
throw new Error(`Your injectReset value: "${injectReset}" is not a valid file path. To give an example, if you placed a reset.css in your src directory, "./src/reset.css" would work.`);
|
|
49
|
+
const resolvedFromNodeModules = node_path.resolve(process.cwd(), "node_modules", injectReset);
|
|
50
|
+
if (!isFile(resolvedFromNodeModules))
|
|
51
|
+
throw new Error(`"${injectReset}" given as your injectReset value is not a valid file path relative to your project's node_modules folder. Can you confirm that you've installed "${injectReset}"?`);
|
|
52
|
+
return node_fs.readFileSync(resolvedFromNodeModules, "utf-8");
|
|
53
|
+
}
|
|
54
|
+
function isFile(path) {
|
|
55
|
+
return node_fs.existsSync(path) && node_fs.statSync(path).isFile();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isServerHooksFile(path) {
|
|
59
|
+
return path.includes("hooks") && path.includes("server");
|
|
60
|
+
}
|
|
61
|
+
function replaceGlobalStylesPlaceholder(code, stylesTag) {
|
|
62
|
+
const captureQuoteMark = "([\"'`])";
|
|
63
|
+
const matchCapturedQuoteMark = "\\1";
|
|
64
|
+
const QUOTES_WITH_PLACEHOLDER_RE = new RegExp(captureQuoteMark + GLOBAL_STYLES_PLACEHOLDER + matchCapturedQuoteMark);
|
|
65
|
+
const escapedStylesTag = stylesTag.replaceAll(/`/g, "\\`");
|
|
66
|
+
return code.replace(QUOTES_WITH_PLACEHOLDER_RE, `\`${escapedStylesTag}\``);
|
|
67
|
+
}
|
|
68
|
+
async function generateGlobalCss(uno, injectReset) {
|
|
69
|
+
const { css } = await uno.generate("", { preflights: true, safelist: true, minify: true });
|
|
70
|
+
const reset = injectReset ? getReset(injectReset) : "";
|
|
71
|
+
return reset + css;
|
|
72
|
+
}
|
|
73
|
+
const SVELTE_ERROR = `[unocss] You have not setup the svelte-scoped global styles correctly. You must place '${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}' in your index.html file.
|
|
74
|
+
`;
|
|
75
|
+
const SVELTE_KIT_ERROR = `[unocss] You have not setup the svelte-scoped global styles correctly. You must place '${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}' in your app.html file. You also need to have a transformPageChunk hook in your server hooks file with: \`html.replace('${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}', '${GLOBAL_STYLES_PLACEHOLDER}')\`. You can see an example of the usage at https://github.com/unocss/unocss/tree/main/examples/sveltekit-scoped.`;
|
|
76
|
+
function checkTransformPageChunkHook(server, isSvelteKit) {
|
|
77
|
+
server.middlewares.use((req, res, next) => {
|
|
78
|
+
const originalWrite = res.write;
|
|
79
|
+
res.write = function(chunk, ...rest) {
|
|
80
|
+
const str = chunk instanceof Buffer ? chunk.toString() : Array.isArray(chunk) || "at" in chunk ? Buffer.from(chunk).toString() : `${chunk}`;
|
|
81
|
+
if (str.includes("<head>") && !str.includes(DEV_GLOBAL_STYLES_DATA_TITLE))
|
|
82
|
+
server.config.logger.error(isSvelteKit ? SVELTE_KIT_ERROR : SVELTE_ERROR, { timestamp: true });
|
|
83
|
+
return originalWrite.call(this, chunk, ...rest);
|
|
84
|
+
};
|
|
85
|
+
next();
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function GlobalStylesPlugin({ ready, uno }, injectReset) {
|
|
90
|
+
let isSvelteKit;
|
|
91
|
+
let viteConfig;
|
|
92
|
+
let unoCssFileReferenceId;
|
|
93
|
+
let unoCssHashedLinkTag;
|
|
94
|
+
return {
|
|
95
|
+
name: "unocss:svelte-scoped:global-styles",
|
|
96
|
+
async configResolved(_viteConfig) {
|
|
97
|
+
viteConfig = _viteConfig;
|
|
98
|
+
await ready;
|
|
99
|
+
isSvelteKit = viteConfig.plugins.some((p) => p.name.includes("sveltekit"));
|
|
100
|
+
},
|
|
101
|
+
configureServer: (server) => checkTransformPageChunkHook(server, isSvelteKit),
|
|
102
|
+
async transform(code, id) {
|
|
103
|
+
if (isSvelteKit && viteConfig.command === "serve" && isServerHooksFile(id)) {
|
|
104
|
+
const css = await generateGlobalCss(uno, injectReset);
|
|
105
|
+
return {
|
|
106
|
+
code: replaceGlobalStylesPlaceholder(code, `<style type="text/css" data-title="${DEV_GLOBAL_STYLES_DATA_TITLE}">${css}</style>`)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
async buildStart() {
|
|
111
|
+
if (viteConfig.command === "build") {
|
|
112
|
+
const css = await generateGlobalCss(uno, injectReset);
|
|
113
|
+
unoCssFileReferenceId = this.emitFile({
|
|
114
|
+
type: "asset",
|
|
115
|
+
name: "unocss-svelte-scoped-global.css",
|
|
116
|
+
source: css
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
renderStart() {
|
|
121
|
+
const unoCssFileName = this.getFileName(unoCssFileReferenceId);
|
|
122
|
+
const base = viteConfig.base ?? "/";
|
|
123
|
+
unoCssHashedLinkTag = `<link href="${base}${unoCssFileName}" rel="stylesheet" />`;
|
|
124
|
+
},
|
|
125
|
+
renderChunk(code, chunk) {
|
|
126
|
+
if (isSvelteKit && chunk.moduleIds.some((id) => isServerHooksFile(id)))
|
|
127
|
+
return replaceGlobalStylesPlaceholder(code, unoCssHashedLinkTag);
|
|
128
|
+
},
|
|
129
|
+
async transformIndexHtml(html) {
|
|
130
|
+
if (!isSvelteKit) {
|
|
131
|
+
if (viteConfig.command === "build")
|
|
132
|
+
return html.replace(PLACEHOLDER_USER_SETS_IN_INDEX_HTML, unoCssHashedLinkTag);
|
|
133
|
+
if (viteConfig.command === "serve") {
|
|
134
|
+
const css = await generateGlobalCss(uno, injectReset);
|
|
135
|
+
return html.replace(PLACEHOLDER_USER_SETS_IN_INDEX_HTML, `<style type="text/css" data-title="${DEV_GLOBAL_STYLES_DATA_TITLE}">${css}</style>`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function UnocssSvelteScopedVite(options = {}) {
|
|
143
|
+
const context = createSvelteScopedContext(options.configOrPath);
|
|
144
|
+
const plugins = [
|
|
145
|
+
GlobalStylesPlugin(context, options.injectReset)
|
|
146
|
+
];
|
|
147
|
+
if (!options.onlyGlobal)
|
|
148
|
+
plugins.push(PassPreprocessToSveltePlugin(options, context));
|
|
149
|
+
return plugins;
|
|
150
|
+
}
|
|
151
|
+
function createSvelteScopedContext(configOrPath) {
|
|
152
|
+
const uno = core.createGenerator();
|
|
153
|
+
const ready = reloadConfig();
|
|
154
|
+
async function reloadConfig() {
|
|
155
|
+
const { config: config$1 } = await config.loadConfig(process.cwd(), configOrPath);
|
|
156
|
+
uno.setConfig(config$1);
|
|
157
|
+
return config$1;
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
uno,
|
|
161
|
+
ready
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
module.exports = UnocssSvelteScopedVite;
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Plugin } from 'vite';
|
|
2
|
+
import { U as UnocssSveltePreprocessOptions } from './types.d-48b837f0.js';
|
|
3
|
+
import '@unocss/core';
|
|
4
|
+
|
|
5
|
+
interface UnocssSvelteScopedViteOptions extends UnocssSveltePreprocessOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Prefix for compiled class names
|
|
8
|
+
* @default 'uno-'
|
|
9
|
+
*/
|
|
10
|
+
classPrefix?: string
|
|
11
|
+
/**
|
|
12
|
+
* Inject reset to the beginning of the global stylesheet.
|
|
13
|
+
*
|
|
14
|
+
* You can pass one of the included resets from [@unocss/reset](https://unocss.dev/guide/style-reset):
|
|
15
|
+
* - `@unocss/reset/normalize.css`
|
|
16
|
+
* - `@unocss/reset/eric-meyer.css`
|
|
17
|
+
* - `@unocss/reset/sanitize/sanitize.css`
|
|
18
|
+
* - `@unocss/reset/tailwind.css`
|
|
19
|
+
* - `@unocss/reset/tailwind-compat.css`
|
|
20
|
+
*
|
|
21
|
+
* You can pass your own custom reset by passing the filepath relative to your project root as in `./src/reset.css`
|
|
22
|
+
*
|
|
23
|
+
* You can install a package then pass a path to the CSS file in your node_modules as in `@bob/my-tools/reset.css`.
|
|
24
|
+
* @default undefined
|
|
25
|
+
*/
|
|
26
|
+
injectReset?: string
|
|
27
|
+
/**
|
|
28
|
+
* When building a component library using `@unocss/svelte-scoped/preprocessor` you can also use `@unocss/svelte-scoped/vite` with this set to `true` to add needed global styles for your library demo app: resets, preflights, and safelist
|
|
29
|
+
* @default false
|
|
30
|
+
*/
|
|
31
|
+
onlyGlobal?: boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
declare function UnocssSvelteScopedVite(options?: UnocssSvelteScopedViteOptions): Plugin[];
|
|
35
|
+
|
|
36
|
+
export { UnocssSvelteScopedVite as default };
|