@unocss/transformer-directives 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/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/transformer-directives",
3
- "version": "0.58.9",
3
+ "type": "module",
4
+ "version": "0.59.0",
4
5
  "description": "UnoCSS transformer for `@apply` directive",
5
6
  "author": "hannoeru <me@hanlee.co>",
6
7
  "license": "MIT",
@@ -20,12 +21,11 @@
20
21
  "sideEffects": false,
21
22
  "exports": {
22
23
  ".": {
23
- "types": "./dist/index.d.ts",
24
- "import": "./dist/index.mjs",
25
- "require": "./dist/index.cjs"
24
+ "types": "./dist/index.d.mts",
25
+ "default": "./dist/index.mjs"
26
26
  }
27
27
  },
28
- "main": "./dist/index.cjs",
28
+ "main": "./dist/index.mjs",
29
29
  "module": "./dist/index.mjs",
30
30
  "types": "./dist/index.d.ts",
31
31
  "files": [
@@ -33,11 +33,11 @@
33
33
  ],
34
34
  "dependencies": {
35
35
  "css-tree": "^2.3.1",
36
- "@unocss/core": "0.58.9",
37
- "@unocss/rule-utils": "0.58.9"
36
+ "@unocss/core": "0.59.0",
37
+ "@unocss/rule-utils": "0.59.0"
38
38
  },
39
39
  "devDependencies": {
40
- "magic-string": "^0.30.8"
40
+ "magic-string": "^0.30.9"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "unbuild",
package/dist/index.cjs DELETED
@@ -1,199 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const core = require('@unocss/core');
6
- const cssTree = require('css-tree');
7
- const ruleUtils = require('@unocss/rule-utils');
8
-
9
- function handleThemeFn({ code, uno, options }, node) {
10
- const { throwOnMissing = true } = options;
11
- const offset = node.value.loc.start.offset;
12
- const str = code.original.slice(offset, node.value.loc.end.offset);
13
- code.overwrite(offset, node.value.loc.end.offset, ruleUtils.transformThemeFn(str, uno.config.theme, throwOnMissing));
14
- }
15
-
16
- const screenRuleRE = /(@screen) (.+) /g;
17
- function handleScreen({ code, uno }, node) {
18
- let breakpointName = "";
19
- let prefix = "";
20
- if (node.name === "screen" && node.prelude?.type === "Raw")
21
- breakpointName = node.prelude.value.trim();
22
- if (!breakpointName)
23
- return;
24
- const match = breakpointName.match(/^(?:(lt|at)-)?(\w+)$/);
25
- if (match) {
26
- prefix = match[1];
27
- breakpointName = match[2];
28
- }
29
- const resolveBreakpoints = () => {
30
- let breakpoints;
31
- if (uno.userConfig && uno.userConfig.theme)
32
- breakpoints = uno.userConfig.theme.breakpoints;
33
- if (!breakpoints)
34
- breakpoints = uno.config.theme.breakpoints;
35
- return breakpoints ? Object.entries(breakpoints).sort((a, b) => Number.parseInt(a[1].replace(/[a-z]+/gi, "")) - Number.parseInt(b[1].replace(/[a-z]+/gi, ""))).map(([point, size]) => ({ point, size })) : void 0;
36
- };
37
- const variantEntries = (resolveBreakpoints() ?? []).map(({ point, size }, idx) => [point, size, idx]);
38
- const generateMediaQuery = (breakpointName2, prefix2) => {
39
- const [, size, idx] = variantEntries.find((i) => i[0] === breakpointName2);
40
- if (prefix2) {
41
- if (prefix2 === "lt")
42
- return `@media (max-width: ${calcMaxWidthBySize(size)})`;
43
- else if (prefix2 === "at")
44
- return `@media (min-width: ${size})${variantEntries[idx + 1] ? ` and (max-width: ${calcMaxWidthBySize(variantEntries[idx + 1][1])})` : ""}`;
45
- else
46
- throw new Error(`breakpoint variant not supported: ${prefix2}`);
47
- }
48
- return `@media (min-width: ${size})`;
49
- };
50
- if (!variantEntries.find((i) => i[0] === breakpointName))
51
- throw new Error(`breakpoint ${breakpointName} not found`);
52
- const offset = node.loc.start.offset;
53
- const str = code.original.slice(offset, node.loc.end.offset);
54
- const matches = Array.from(str.matchAll(screenRuleRE));
55
- if (!matches.length)
56
- return;
57
- for (const match2 of matches) {
58
- code.overwrite(
59
- offset + match2.index,
60
- offset + match2.index + match2[0].length,
61
- `${generateMediaQuery(breakpointName, prefix)} `
62
- );
63
- }
64
- }
65
- function calcMaxWidthBySize(size) {
66
- const value = size.match(/^-?[0-9]+\.?[0-9]*/)?.[0] || "";
67
- const unit = size.slice(value.length);
68
- const maxWidth = Number.parseFloat(value) - 0.1;
69
- return Number.isNaN(maxWidth) ? size : `${maxWidth}${unit}`;
70
- }
71
-
72
- async function handleApply(ctx, node) {
73
- const { code, uno, options, filename, offset } = ctx;
74
- const calcOffset = (pos) => offset ? pos + offset : pos;
75
- await Promise.all(
76
- node.block.children.map(async (childNode) => {
77
- if (childNode.type === "Raw")
78
- return transformDirectives(code, uno, options, filename, childNode.value, calcOffset(childNode.loc.start.offset));
79
- await parseApply(ctx, node, childNode);
80
- }).toArray()
81
- );
82
- }
83
- async function parseApply({ code, uno, offset, applyVariable }, node, childNode) {
84
- const calcOffset = (pos) => offset ? pos + offset : pos;
85
- let body;
86
- if (childNode.type === "Atrule" && childNode.name === "apply" && childNode.prelude && childNode.prelude.type === "Raw")
87
- body = childNode.prelude.value.trim();
88
- else if (childNode.type === "Declaration" && applyVariable.includes(childNode.property) && childNode.value.type === "Raw")
89
- body = childNode.value.value.trim();
90
- if (!body)
91
- return;
92
- if (/^(['"]).*\1$/.test(body))
93
- body = body.slice(1, -1);
94
- const classNames = core.expandVariantGroup(body).split(/\s+/g).map((className) => className.trim().replace(/\\/, ""));
95
- const utils = (await Promise.all(
96
- classNames.map((i) => uno.parseToken(i, "-"))
97
- )).filter(core.notNull).flat().sort((a, b) => a[0] - b[0]).sort((a, b) => (a[3] ? uno.parentOrders.get(a[3]) ?? 0 : 0) - (b[3] ? uno.parentOrders.get(b[3]) ?? 0 : 0)).reduce((acc, item) => {
98
- const target = acc.find((i) => i[1] === item[1] && i[3] === item[3]);
99
- if (target)
100
- target[2] += item[2];
101
- else
102
- acc.push([...item]);
103
- return acc;
104
- }, []);
105
- if (!utils.length)
106
- return;
107
- const simicolonOffset = code.toString()[childNode.loc.end.offset] === ";" ? 1 : 0;
108
- for (const i of utils) {
109
- const [, _selector, body2, parent] = i;
110
- const selectorOrGroup = _selector?.replace(core.regexScopePlaceholder, " ") || _selector;
111
- if (parent || selectorOrGroup && selectorOrGroup !== ".\\-") {
112
- let newSelector = cssTree.generate(node.prelude);
113
- if (selectorOrGroup && selectorOrGroup !== ".\\-") {
114
- const ruleAST = cssTree.parse(`${selectorOrGroup}{}`, {
115
- context: "rule"
116
- });
117
- const prelude = cssTree.clone(node.prelude);
118
- prelude.children.forEach((child) => {
119
- const selectorListAst = cssTree.clone(ruleAST.prelude);
120
- const classSelectors = new cssTree.List();
121
- selectorListAst.children.forEach((selectorAst) => {
122
- classSelectors.appendList(selectorAst.children.filter((i2) => i2.type === "ClassSelector" && i2.name === "\\-"));
123
- });
124
- classSelectors.forEach((i2) => Object.assign(i2, cssTree.clone(child)));
125
- Object.assign(child, selectorListAst);
126
- });
127
- newSelector = cssTree.generate(prelude);
128
- }
129
- let css = `${newSelector}{${body2}}`;
130
- if (parent)
131
- css = `${parent}{${css}}`;
132
- code.appendLeft(calcOffset(node.loc.end.offset), css);
133
- } else {
134
- if (body2.includes("@"))
135
- code.appendRight(code.original.length + simicolonOffset, body2);
136
- else
137
- code.appendRight(calcOffset(childNode.loc.end.offset + simicolonOffset), body2);
138
- }
139
- }
140
- code.remove(
141
- calcOffset(childNode.loc.start.offset),
142
- calcOffset(childNode.loc.end.offset + simicolonOffset)
143
- );
144
- }
145
-
146
- function transformerDirectives(options = {}) {
147
- return {
148
- name: "@unocss/transformer-directives",
149
- enforce: options?.enforce,
150
- idFilter: (id) => core.cssIdRE.test(id),
151
- transform: (code, id, ctx) => {
152
- return transformDirectives(code, ctx.uno, options, id);
153
- }
154
- };
155
- }
156
- async function transformDirectives(code, uno, options, filename, originalCode, offset) {
157
- let { applyVariable } = options;
158
- const varStyle = options.varStyle;
159
- if (applyVariable === void 0) {
160
- if (varStyle !== void 0)
161
- applyVariable = varStyle ? [`${varStyle}apply`] : [];
162
- applyVariable = ["--at-apply", "--uno-apply", "--uno"];
163
- }
164
- applyVariable = core.toArray(applyVariable || []);
165
- const hasApply = code.original.includes("@apply") || applyVariable.some((s) => code.original.includes(s));
166
- const hasScreen = code.original.includes("@screen");
167
- const hasThemeFn = ruleUtils.hasThemeFn(code.original);
168
- if (!hasApply && !hasThemeFn && !hasScreen)
169
- return;
170
- const ast = cssTree.parse(originalCode || code.original, {
171
- parseAtrulePrelude: false,
172
- positions: true,
173
- filename
174
- });
175
- if (ast.type !== "StyleSheet")
176
- return;
177
- const stack = [];
178
- const ctx = {
179
- options,
180
- applyVariable,
181
- uno,
182
- code,
183
- filename,
184
- offset
185
- };
186
- const processNode = async (node, _item, _list) => {
187
- if (hasScreen && node.type === "Atrule")
188
- handleScreen(ctx, node);
189
- if (hasThemeFn && node.type === "Declaration")
190
- handleThemeFn(ctx, node);
191
- if (hasApply && node.type === "Rule")
192
- await handleApply(ctx, node);
193
- };
194
- cssTree.walk(ast, (...args) => stack.push(processNode(...args)));
195
- await Promise.all(stack);
196
- }
197
-
198
- exports.default = transformerDirectives;
199
- exports.transformDirectives = transformDirectives;
package/dist/index.d.cts DELETED
@@ -1,41 +0,0 @@
1
- import { SourceCodeTransformer, UnoGenerator } from '@unocss/core';
2
- import MagicString from 'magic-string';
3
-
4
- interface TransformerDirectivesOptions {
5
- enforce?: SourceCodeTransformer['enforce'];
6
- /**
7
- * Throw an error if utils or themes are not found.
8
- *
9
- * @default true
10
- */
11
- throwOnMissing?: boolean;
12
- /**
13
- * Treat CSS custom properties as @apply directives for CSS syntax compatibility.
14
- *
15
- * Pass `false` to disable.
16
- *
17
- * @default ['--at-apply', '--uno-apply', '--uno']
18
- */
19
- applyVariable?: false | string | string[];
20
- /**
21
- * Treat CSS custom properties as directives for CSS syntax compatibility.
22
- *
23
- * Pass `false` to disable, or a string to use as a prefix.
24
- *
25
- * @deprecated use `applyVariable` to specify the full var name instead.
26
- * @default '--at-'
27
- */
28
- varStyle?: false | string;
29
- }
30
- interface TransformerDirectivesContext {
31
- code: MagicString;
32
- uno: UnoGenerator;
33
- options: TransformerDirectivesOptions;
34
- applyVariable: string[];
35
- offset?: number;
36
- filename?: string;
37
- }
38
- declare function transformerDirectives(options?: TransformerDirectivesOptions): SourceCodeTransformer;
39
- declare function transformDirectives(code: MagicString, uno: UnoGenerator, options: TransformerDirectivesOptions, filename?: string, originalCode?: string, offset?: number): Promise<void>;
40
-
41
- export { type TransformerDirectivesContext, type TransformerDirectivesOptions, transformerDirectives as default, transformDirectives };