Skip to content

Commit 4d68df3

Browse files
authored
fix: expand on shadowDom support
1 parent e784d08 commit 4d68df3

File tree

1 file changed

+96
-62
lines changed

1 file changed

+96
-62
lines changed

server/presets.mjs

Lines changed: 96 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,85 @@
1-
import { readFile, mkdir, writeFile } from 'node:fs/promises';
2-
import { createReadStream, existsSync } from 'node:fs';
3-
import { join, dirname } from 'node:path';
4-
import tailwind from 'tailwindcss';
5-
import resolveConfig from 'tailwindcss/resolveConfig.js';
6-
import postcss from 'postcss';
7-
import autoprefixer from 'autoprefixer';
8-
import cssnano from 'cssnano';
9-
import Yaml from 'yaml';
10-
import { defaultPlugins, allPlugins } from './constants.mjs';
1+
import { readFile, mkdir, writeFile } from "node:fs/promises";
2+
import { createReadStream, existsSync } from "node:fs";
3+
import { join, dirname } from "node:path";
4+
import tailwind from "tailwindcss";
5+
import resolveConfig from "tailwindcss/resolveConfig.js";
6+
import postcss from "postcss";
7+
import autoprefixer from "autoprefixer";
8+
import cssnano from "cssnano";
9+
import Yaml from "yaml";
10+
import { defaultPlugins, allPlugins } from "./constants.mjs";
1111

1212
const CWD = process.cwd();
13-
const getPresetPath = (name) => join(CWD, 'systems', name + '.yml');
13+
const getPresetPath = (name) => join(CWD, "systems", name + ".yml");
14+
const each = (v) => (!v ? [] : Object.entries(v));
1415

1516
function generateComponentParts(name, def, separator) {
16-
return !def ? [] : Object.entries(def).map(([part, classes]) => `.${name}${separator}${part} {\n @apply ${classes} ;\n}\n`);
17+
return each(def).map(([part, c]) => [`.${name}${separator}${part}`, c]);
1718
}
1819

19-
function generateShadowComponentParts(name, def) {
20-
return !def ? [] : Object.entries(def).map(([part, classes]) => `${name}::part(${part}) {\n @apply ${classes} ;\n}\n`);
20+
function generateShadowComponentParts(name, parts) {
21+
return each(parts).map(([part, c]) => [`${name}::part(${part})`, c]);
2122
}
2223

2324
function generateShadowComponentStates(name, def) {
24-
return !def ? [] : Object.entries(def).map(([part, classes]) => `${name}::part(component):${part} {\n @apply ${classes} ;\n}\n`);
25+
return each(def).map(([part, c]) => [`${name}::part(component):${part}`, c]);
2526
}
2627

27-
function defineComponent(name, def, useShadowDom) {
28-
if (useShadowDom) {
29-
return [
30-
`${name}::part(component) {\n${(def.apply && ' @apply ' + def.apply + ';\n') || ''}}\n`,
31-
generateShadowComponentParts(name, def.parts),
32-
generateShadowComponentStates(name, def.states),
33-
]
34-
.flat()
35-
.join('');
36-
}
28+
function generateShadowComponentVariants(name, variants) {
29+
return each(variants).map(
30+
([variant, classes]) =>
31+
`.${name}.${name}-${variant}::part(component) {\n @apply ${classes} ;\n}\n`
32+
);
33+
}
3734

38-
return [
39-
`.${name} {\n${(def.apply && ' @apply ' + def.apply + ';\n') || ''}}\n`,
40-
generateComponentParts(name, def.parts, '__'),
41-
generateComponentParts(name, def.modifiers, '--'),
42-
generateComponentParts(name, def.variants, '-'),
43-
generateComponentParts(name, def.states, ':'),
44-
]
45-
.flat()
46-
.join('');
35+
function generateComponent(name, def, prefix = "") {
36+
return !def ? [] : [`${prefix}${name}::part(component)`, def.apply];
37+
}
38+
39+
function defineComponent(name, def, useShadowDom) {
40+
const all = useShadowDom
41+
? [
42+
generateComponent(name, def.apply),
43+
generateShadowComponentParts(name, def.parts),
44+
generateShadowComponentStates(name, def.states),
45+
generateShadowComponentVariants(name, def.variants, "-"),
46+
]
47+
: [
48+
generateComponent(name, def.apply, "."),
49+
generateComponentParts(name, def.parts, "__"),
50+
generateComponentParts(name, def.modifiers, "--"),
51+
generateComponentParts(name, def.variants, "-"),
52+
generateComponentParts(name, def.states, ":"),
53+
];
54+
55+
return all
56+
.flatMap((item) => item[0] + `{\n @apply ${item[1]} ;\n}\n`)
57+
.join("");
4758
}
4859

4960
function generateCssSafelist(presets) {
5061
const classes = [];
5162

52-
presets.forEach(next => {
53-
if (!(next.components && typeof next.components === 'object')) return;
63+
presets.forEach((next) => {
64+
if (!(next.components && typeof next.components === "object")) return;
5465

5566
Object.entries(next.components).forEach(([name, def]) => {
5667
classes.push(name);
5768

5869
if (def.parts) {
59-
classes.push(...Object.keys(def.parts).map(key => name + '__' + key));
70+
classes.push(...Object.keys(def.parts).map((key) => name + "__" + key));
6071
}
6172

6273
if (def.modifiers) {
63-
classes.push(...Object.keys(def.modifiers).map(key => name + '--' + key));
74+
classes.push(
75+
...Object.keys(def.modifiers).map((key) => name + "--" + key)
76+
);
6477
}
6578

6679
if (def.variants) {
67-
classes.push(...Object.keys(def.variants).map(key => name + '-' + key));
80+
classes.push(
81+
...Object.keys(def.variants).map((key) => name + "-" + key)
82+
);
6883
}
6984
});
7085
});
@@ -84,7 +99,7 @@ function generateCssTemplate(presets, useShadowDom) {
8499
chain.variables = Object.assign({}, chain.variables, next.variables);
85100
}
86101

87-
if (next.components && typeof next.components === 'object') {
102+
if (next.components && typeof next.components === "object") {
88103
Object.assign(chain, next.components);
89104
}
90105

@@ -99,8 +114,12 @@ function generateCssTemplate(presets, useShadowDom) {
99114
return chain;
100115
}, {});
101116

102-
const components = Object.entries(chain).map(([name, def]) => defineComponent(name, def, useShadowDom)).join('');
103-
const allVariables = Object.entries(variables).map(([key, value]) => `--${key}: ${value};`).join('\n');
117+
const components = Object.entries(chain)
118+
.map(([name, def]) => defineComponent(name, def, useShadowDom))
119+
.join("");
120+
const allVariables = Object.entries(variables)
121+
.map(([key, value]) => `--${key}: ${value};`)
122+
.join("\n");
104123
const css = `:root{
105124
${allVariables}
106125
}
@@ -112,7 +131,7 @@ function generateCssTemplate(presets, useShadowDom) {
112131
${components}
113132
}
114133
115-
${styles.join('')}
134+
${styles.join("")}
116135
`;
117136

118137
return css;
@@ -130,7 +149,9 @@ export async function generatePreset(input) {
130149
}
131150

132151
const allPresets = [...presetChain, input];
133-
const pluginChain = allPresets.flatMap(p => transformPlugins(p.corePlugins)).filter(Boolean);
152+
const pluginChain = allPresets
153+
.flatMap((p) => transformPlugins(p.corePlugins))
154+
.filter(Boolean);
134155
const resolvedPlugins = [...new Set(pluginChain)];
135156

136157
if (resolvedPlugins.length) {
@@ -142,34 +163,44 @@ export async function generatePreset(input) {
142163
if (input.autoPurge) {
143164
tailwindConfig.purge = {
144165
enabled: true,
145-
content: ['*.xyz'],
166+
content: ["*.xyz"],
146167
safelist: generateCssSafelist(allPresets),
147168
};
148169
}
149170

150171
const json = JSON.stringify(tailwindConfig, null, 2);
151-
const cssTemplate = generateCssTemplate(allPresets, (input.shadowDom || input['shadow-dom']));
152-
const plugins = [tailwind(tailwindConfig), autoprefixer(), input.minify && cssnano()].filter(Boolean);
172+
const cssTemplate = generateCssTemplate(
173+
allPresets,
174+
input.shadowDom || input["shadow-dom"]
175+
);
176+
const plugins = [
177+
tailwind(tailwindConfig),
178+
autoprefixer(),
179+
input.minify && cssnano(),
180+
].filter(Boolean);
153181
const processor = postcss(...plugins);
154182

155183
try {
156-
const output = await processor.process(cssTemplate, { from: '/web-design-system.css', to: '/index.css' });
184+
const output = await processor.process(cssTemplate, {
185+
from: "/web-design-system.css",
186+
to: "/index.css",
187+
});
157188
const { css } = output;
158189

159190
return { error: null, css, json };
160191
} catch (error) {
161-
return { error, css: '', json };
192+
return { error, css: "", json };
162193
}
163194
}
164195

165196
export async function readPreset(name) {
166197
const path = getPresetPath(name);
167198

168199
if (!existsSync(path)) {
169-
return '';
200+
return "";
170201
}
171202

172-
return await readFile(path, 'utf-8');
203+
return await readFile(path, "utf-8");
173204
}
174205

175206
/**
@@ -188,7 +219,7 @@ export async function loadPreset(name) {
188219
export async function loadPresetChain(nameOrPreset, presets = []) {
189220
let preset = nameOrPreset;
190221

191-
if (typeof nameOrPreset === 'string') {
222+
if (typeof nameOrPreset === "string") {
192223
preset = await loadPreset(nameOrPreset);
193224
}
194225

@@ -197,7 +228,10 @@ export async function loadPresetChain(nameOrPreset, presets = []) {
197228
}
198229

199230
if (preset.extends) {
200-
const extensions = typeof preset.extends === 'string' ? [preset.extends] : preset.extends || [];
231+
const extensions =
232+
typeof preset.extends === "string"
233+
? [preset.extends]
234+
: preset.extends || [];
201235

202236
for (const extension of extensions.reverse()) {
203237
const next = await loadPreset(extension);
@@ -215,19 +249,19 @@ export async function loadPresetChain(nameOrPreset, presets = []) {
215249
export async function savePreset(name, preset) {
216250
const path = getPresetPath(name);
217251
await ensureFolder(dirname(path));
218-
await writeFile(path, preset, 'utf-8');
252+
await writeFile(path, preset, "utf-8");
219253
}
220254

221255
export async function savePresetAssets(name, preset) {
222256
const { json, css } = preset;
223-
const basePath = join(CWD, 'presets', name);
257+
const basePath = join(CWD, "presets", name);
224258
await ensureFolder(dirname(basePath));
225-
await writeFile(basePath + '.mjs', 'export default ' + json);
226-
await writeFile(basePath + '.css', css);
259+
await writeFile(basePath + ".mjs", "export default " + json);
260+
await writeFile(basePath + ".css", css);
227261
}
228262

229263
export function loadPresetAsset(name) {
230-
const path = join(CWD, 'presets', name);
264+
const path = join(CWD, "presets", name);
231265

232266
if (existsSync(path)) {
233267
return createReadStream(path);
@@ -240,15 +274,15 @@ export function loadPresetAsset(name) {
240274
* @returns {string[]} plugins after transforming the keywords
241275
*/
242276
export function transformPlugins(plugins) {
243-
if (plugins === 'all') {
277+
if (plugins === "all") {
244278
return allPlugins;
245279
}
246280

247-
if (plugins === 'none') {
281+
if (plugins === "none") {
248282
return [];
249283
}
250284

251-
if (plugins === 'default') {
285+
if (plugins === "default") {
252286
plugins = defaultPlugins;
253287
}
254288

@@ -257,7 +291,7 @@ export function transformPlugins(plugins) {
257291
}
258292

259293
return plugins.flatMap((next) => {
260-
if (next.endsWith('*')) {
294+
if (next.endsWith("*")) {
261295
const stem = next.slice(0, -1);
262296
return allPlugins.filter((p) => p.startsWith(stem));
263297
}

0 commit comments

Comments
 (0)