cook-ssg 2.4.0 → 2.6.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 +1 -1
- package/scripts/build.js +12 -0
- package/scripts/dev.js +5 -0
- package/scripts/plugins/fingerprint-assets.js +14 -10
- package/scripts/plugins/package-components.js +170 -0
- package/scripts/plugins/theme.js +191 -0
- package/scripts/utils/config/config.js +30 -0
- package/scripts/utils/util/util.js +2 -1
package/package.json
CHANGED
package/scripts/build.js
CHANGED
|
@@ -25,6 +25,8 @@ import generateSitemap from './plugins/generate-sitemap-xml.js';
|
|
|
25
25
|
import htmlCollections from './plugins/html-collections.js';
|
|
26
26
|
import minifySrc from './plugins/minify-src.js';
|
|
27
27
|
import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
|
|
28
|
+
import { themeInject, resetThemeCache } from './plugins/theme.js';
|
|
29
|
+
import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
|
|
28
30
|
import processMarkdown from './plugins/process-markdown.js';
|
|
29
31
|
import repeatCollection from './plugins/repeat-collection.js';
|
|
30
32
|
import replaceComponents from './plugins/replace-components.js';
|
|
@@ -99,6 +101,9 @@ class Build {
|
|
|
99
101
|
// PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
|
|
100
102
|
await optimizeImagesGenerate({store});
|
|
101
103
|
|
|
104
|
+
// PLUGIN: Copy npm web-component packages (with a custom-elements.json) into dist
|
|
105
|
+
await packageComponentsCopy({store});
|
|
106
|
+
|
|
102
107
|
// CUSTOM PLUGINS: Run custom user plugins before file loop
|
|
103
108
|
await customPlugins({store, data, plugins: plugins.before, log: 'Before' });
|
|
104
109
|
|
|
@@ -178,6 +183,12 @@ class Build {
|
|
|
178
183
|
// PLUGIN: Auto-detect custom elements and manage VB JS loading
|
|
179
184
|
await autoComponents({file, store, allowType: ['.html']});
|
|
180
185
|
|
|
186
|
+
// PLUGIN: Add a module script for npm component packages used on the page
|
|
187
|
+
await packageComponentsInject({file, store, allowType: ['.html']});
|
|
188
|
+
|
|
189
|
+
// PLUGIN: Site theme: data-theme/data-mode on <html> (or the article) and theme stylesheet links, from `theme` config
|
|
190
|
+
await themeInject({file, allowType: ['.html']});
|
|
191
|
+
|
|
181
192
|
// PLUGIN: Pre-render Declarative Shadow DOM for web components
|
|
182
193
|
await declarativeShadowDom({file, store, allowType: ['.html']});
|
|
183
194
|
|
|
@@ -271,6 +282,7 @@ export async function runBuild() {
|
|
|
271
282
|
delete store.cachedLayouts;
|
|
272
283
|
delete store.cachedInline;
|
|
273
284
|
}
|
|
285
|
+
resetThemeCache();
|
|
274
286
|
store.bundle = { css: {}, js: {} };
|
|
275
287
|
// Collections are fully rebuilt by processMarkdown every run — stale
|
|
276
288
|
// entries would otherwise accumulate (duplicate blog posts on the
|
package/scripts/dev.js
CHANGED
|
@@ -147,3 +147,8 @@ watchFiles.forEach(watchPath => {
|
|
|
147
147
|
// Watch `/src` files for changes
|
|
148
148
|
browserSync.watch(`${srcPath}${watchPath}`).on('change', file => { rebuild(file); });
|
|
149
149
|
});
|
|
150
|
+
|
|
151
|
+
// config/theme.json lives outside /src; Vanilla Press rewrites it on Apply.
|
|
152
|
+
// A change forces a full rebuild so every page picks up the new theme.
|
|
153
|
+
const themeJson = `${process.cwd()}/config/theme.json`;
|
|
154
|
+
browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
|
|
@@ -22,7 +22,8 @@ import Logger from '../utils/logger/logger.js';
|
|
|
22
22
|
import Util from '../utils/util/util.js';
|
|
23
23
|
|
|
24
24
|
// Config
|
|
25
|
-
import { distPath, fingerprint as fingerprintConfig } from '../utils/config/config.js';
|
|
25
|
+
import { distPath, siteRoot, fingerprint as fingerprintConfig } from '../utils/config/config.js';
|
|
26
|
+
import { siteRootDir } from '../utils/site-root/site-root.js';
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
// ============================================================================
|
|
@@ -140,6 +141,9 @@ class FingerprintAssets {
|
|
|
140
141
|
constructor(opts = {}) {
|
|
141
142
|
// Optional per-call overrides (used by tests and custom pipelines)
|
|
142
143
|
this.distPath = opts.distPath || distPath;
|
|
144
|
+
this.siteRoot = opts.siteRoot ?? siteRoot;
|
|
145
|
+
// Web paths ("/assets/x.css") are relative to the folder served at "/"
|
|
146
|
+
this.rootDir = siteRootDir(this.distPath, this.siteRoot);
|
|
143
147
|
this.config = {
|
|
144
148
|
enabled: false,
|
|
145
149
|
hashLength: 8,
|
|
@@ -168,7 +172,7 @@ class FingerprintAssets {
|
|
|
168
172
|
const manifest = await this.fingerprintFiles(candidates);
|
|
169
173
|
|
|
170
174
|
// Phase 2: Rewrite HTML references
|
|
171
|
-
const htmlFiles = (Util.getPaths(this.
|
|
175
|
+
const htmlFiles = (Util.getPaths(this.rootDir, this.rootDir, []) || [])
|
|
172
176
|
.filter(p => p.endsWith('.html'));
|
|
173
177
|
let totalRewrites = 0;
|
|
174
178
|
for (const htmlPath of htmlFiles) {
|
|
@@ -181,7 +185,7 @@ class FingerprintAssets {
|
|
|
181
185
|
}
|
|
182
186
|
|
|
183
187
|
// Phase 3: Write manifest
|
|
184
|
-
const manifestFsPath = path.join(this.
|
|
188
|
+
const manifestFsPath = path.join(this.rootDir, this.config.manifestPath);
|
|
185
189
|
await fs.writeFile(manifestFsPath, JSON.stringify(manifest, null, 2), 'utf-8');
|
|
186
190
|
|
|
187
191
|
Logger.persist.success(
|
|
@@ -194,7 +198,7 @@ class FingerprintAssets {
|
|
|
194
198
|
* Returns absolute paths.
|
|
195
199
|
*/
|
|
196
200
|
async findCandidates() {
|
|
197
|
-
const all = Util.getPaths(this.
|
|
201
|
+
const all = Util.getPaths(this.rootDir, this.rootDir, []) || [];
|
|
198
202
|
const excludes = this.config.excludePaths.map(p => (p instanceof RegExp ? p : new RegExp(p)));
|
|
199
203
|
return all.filter(p => {
|
|
200
204
|
// Skip source maps in the candidate list — handled alongside their source.
|
|
@@ -279,13 +283,13 @@ class FingerprintAssets {
|
|
|
279
283
|
}
|
|
280
284
|
|
|
281
285
|
// Build manifest keys as web paths starting with `/`
|
|
282
|
-
const relOriginal = '/' + path.relative(this.
|
|
283
|
-
const relNew = '/' + path.relative(this.
|
|
286
|
+
const relOriginal = '/' + path.relative(this.rootDir, absPath).split(path.sep).join('/');
|
|
287
|
+
const relNew = '/' + path.relative(this.rootDir, newAbs).split(path.sep).join('/');
|
|
284
288
|
manifest[relOriginal] = relNew;
|
|
285
289
|
|
|
286
290
|
if (mapNewName) {
|
|
287
|
-
const relMapOriginal = '/' + path.relative(this.
|
|
288
|
-
const relMapNew = '/' + path.relative(this.
|
|
291
|
+
const relMapOriginal = '/' + path.relative(this.rootDir, mapAbs).split(path.sep).join('/');
|
|
292
|
+
const relMapNew = '/' + path.relative(this.rootDir, path.join(dir, mapNewName)).split(path.sep).join('/');
|
|
289
293
|
manifest[relMapOriginal] = relMapNew;
|
|
290
294
|
}
|
|
291
295
|
}
|
|
@@ -306,7 +310,7 @@ class FingerprintAssets {
|
|
|
306
310
|
const clean = splitUrlSuffix(spec).path;
|
|
307
311
|
if (clean.startsWith('/')) return clean;
|
|
308
312
|
if (clean.startsWith('./') || clean.startsWith('../')) {
|
|
309
|
-
const dirRel = path.dirname(path.relative(this.
|
|
313
|
+
const dirRel = path.dirname(path.relative(this.rootDir, absPath));
|
|
310
314
|
const joined = path.normalize(path.join(dirRel, clean));
|
|
311
315
|
return '/' + joined.split(path.sep).join('/');
|
|
312
316
|
}
|
|
@@ -345,7 +349,7 @@ class FingerprintAssets {
|
|
|
345
349
|
* @returns {string[]}
|
|
346
350
|
*/
|
|
347
351
|
orderByDependencies(candidates, contents) {
|
|
348
|
-
const keyOf = p => '/' + path.relative(this.
|
|
352
|
+
const keyOf = p => '/' + path.relative(this.rootDir, p).split(path.sep).join('/');
|
|
349
353
|
const byKey = new Map(candidates.map(p => [keyOf(p), p]));
|
|
350
354
|
|
|
351
355
|
const deps = new Map();
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file package-components.js
|
|
3
|
+
* @description Load npm web-component packages per page.
|
|
4
|
+
*
|
|
5
|
+
* Dependencies in the project's package.json that ship a custom-elements.json
|
|
6
|
+
* manifest get their built files (the entry's whole directory) copied to
|
|
7
|
+
* `<dist>/<path>/<package name>/`. Each page that uses one of the package's
|
|
8
|
+
* tags gets one `<script type="module">` appended to `<head>`.
|
|
9
|
+
*
|
|
10
|
+
* packageComponentsCopy({ store }) once, pre-loop; fills store.packageComponentsMap
|
|
11
|
+
* packageComponentsInject(...) per page, after autoComponents
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// IMPORTS
|
|
15
|
+
// -----------------------------
|
|
16
|
+
import chalk from 'chalk';
|
|
17
|
+
import fs from 'fs-extra';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import Util from '../utils/util/util.js';
|
|
20
|
+
|
|
21
|
+
// Config
|
|
22
|
+
import { distPath, siteRoot, packageComponents as packageComponentsConfig } from '../utils/config/config.js';
|
|
23
|
+
|
|
24
|
+
import { siteRootDir } from '../utils/site-root/site-root.js';
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
// HELPERS
|
|
28
|
+
// -----------------------------
|
|
29
|
+
const getConfig = () => ({
|
|
30
|
+
enabled: true,
|
|
31
|
+
exclude: ['vanilla-breeze', 'cook-ssg'],
|
|
32
|
+
path: 'assets/components',
|
|
33
|
+
...packageComponentsConfig,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const readJson = async (file) => {
|
|
37
|
+
try {
|
|
38
|
+
return await fs.readJson(file);
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Resolve a package's entry file from its package.json
|
|
46
|
+
* @param {Object} pkg - Parsed package.json
|
|
47
|
+
* @returns {string|null} Entry path as written (e.g. './dist/x.js')
|
|
48
|
+
*/
|
|
49
|
+
function resolveEntry(pkg) {
|
|
50
|
+
const root = pkg.exports && pkg.exports['.'];
|
|
51
|
+
const candidates = [
|
|
52
|
+
root && typeof root === 'object' ? root.import : null,
|
|
53
|
+
root && typeof root === 'object' ? root.default : null,
|
|
54
|
+
typeof root === 'string' ? root : null,
|
|
55
|
+
pkg.module,
|
|
56
|
+
pkg.main,
|
|
57
|
+
];
|
|
58
|
+
return candidates.find(c => typeof c === 'string' && c) || null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Collect every tagName declared in a custom-elements manifest
|
|
63
|
+
* @param {Object} manifest
|
|
64
|
+
* @returns {string[]}
|
|
65
|
+
*/
|
|
66
|
+
function manifestTags(manifest) {
|
|
67
|
+
const tags = new Set();
|
|
68
|
+
for (const mod of manifest.modules || []) {
|
|
69
|
+
for (const decl of mod.declarations || []) {
|
|
70
|
+
if (decl.tagName) tags.add(decl.tagName);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return [...tags];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
// COPY (ONCE, PRE-LOOP)
|
|
78
|
+
// -----------------------------
|
|
79
|
+
export async function packageComponentsCopy({ store, siteRoot: siteRootOpt }) {
|
|
80
|
+
const config = getConfig();
|
|
81
|
+
store.packageComponentsMap = {};
|
|
82
|
+
if (!config.enabled) return;
|
|
83
|
+
|
|
84
|
+
const cwd = process.cwd();
|
|
85
|
+
const rootPkg = await readJson(path.join(cwd, 'package.json'));
|
|
86
|
+
if (!rootPkg || !rootPkg.dependencies) return;
|
|
87
|
+
|
|
88
|
+
const names = Object.keys(rootPkg.dependencies).filter(n => !config.exclude.includes(n));
|
|
89
|
+
const urlBase = config.path.replace(/^\/+|\/+$/g, '');
|
|
90
|
+
|
|
91
|
+
for (const name of names) {
|
|
92
|
+
const pkgDir = path.join(cwd, 'node_modules', name);
|
|
93
|
+
const skip = (why) => console.log(chalk.gray(`[package-components] Skipping ${name}: ${why}`));
|
|
94
|
+
|
|
95
|
+
const pkg = await readJson(path.join(pkgDir, 'package.json'));
|
|
96
|
+
if (!pkg) { skip('not installed'); continue; }
|
|
97
|
+
|
|
98
|
+
const manifestFile = typeof pkg.customElements === 'string' ? pkg.customElements : 'custom-elements.json';
|
|
99
|
+
const manifest = await readJson(path.join(pkgDir, manifestFile));
|
|
100
|
+
if (!manifest) { skip('no custom-elements manifest'); continue; }
|
|
101
|
+
|
|
102
|
+
const entry = resolveEntry(pkg);
|
|
103
|
+
if (!entry) { skip('no entry point'); continue; }
|
|
104
|
+
|
|
105
|
+
const entryAbs = path.resolve(pkgDir, entry);
|
|
106
|
+
if (!(await fs.pathExists(entryAbs))) { skip('entry file missing'); continue; }
|
|
107
|
+
|
|
108
|
+
const entryDir = path.dirname(entryAbs);
|
|
109
|
+
// Never copy the whole package root's parent or anything outside the package
|
|
110
|
+
if (path.relative(pkgDir, entryDir).startsWith('..')) { skip('entry outside package'); continue; }
|
|
111
|
+
|
|
112
|
+
const target = path.join(cwd, siteRootDir(distPath, siteRootOpt ?? siteRoot), urlBase, name);
|
|
113
|
+
await fs.copy(entryDir, target);
|
|
114
|
+
|
|
115
|
+
const rel = path.basename(entryAbs);
|
|
116
|
+
const url = `/${urlBase}/${name}/${rel}`;
|
|
117
|
+
for (const tag of manifestTags(manifest)) {
|
|
118
|
+
store.packageComponentsMap[tag] = url;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const count = Object.keys(store.packageComponentsMap).length;
|
|
123
|
+
if (count) console.log(chalk.green(`[package-components] ${count} tag(s) mapped`));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
// INJECT (PER PAGE)
|
|
128
|
+
// -----------------------------
|
|
129
|
+
class PackageComponents {
|
|
130
|
+
constructor({ file, store, allowType, disallowType }) {
|
|
131
|
+
this.opts = { file, allowType, disallowType };
|
|
132
|
+
this.file = file;
|
|
133
|
+
this.store = store;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async init() {
|
|
137
|
+
const map = this.store.packageComponentsMap;
|
|
138
|
+
if (!map || Object.keys(map).length === 0) return;
|
|
139
|
+
if (!Util.isAllowedType(this.opts)) return;
|
|
140
|
+
|
|
141
|
+
const dom = Util.fileDom(this.file);
|
|
142
|
+
const document = dom.window.document;
|
|
143
|
+
const head = document.querySelector('head');
|
|
144
|
+
if (!head) return;
|
|
145
|
+
|
|
146
|
+
const present = new Set(
|
|
147
|
+
[...document.querySelectorAll('script[src]')].map(s => s.getAttribute('src'))
|
|
148
|
+
);
|
|
149
|
+
const added = new Set();
|
|
150
|
+
|
|
151
|
+
for (const el of document.querySelectorAll('*')) {
|
|
152
|
+
const url = map[el.tagName.toLowerCase()];
|
|
153
|
+
if (!url || present.has(url) || added.has(url)) continue;
|
|
154
|
+
const script = document.createElement('script');
|
|
155
|
+
script.setAttribute('type', 'module');
|
|
156
|
+
script.setAttribute('src', url);
|
|
157
|
+
head.appendChild(script);
|
|
158
|
+
added.add(url);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (added.size) Util.commitDom(this.file, dom);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
static async export(opts) {
|
|
165
|
+
return new PackageComponents(opts).init();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export const packageComponentsInject = PackageComponents.export;
|
|
170
|
+
export default packageComponentsInject;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file theme.js
|
|
3
|
+
* @description Site theme setting and the per-page theme plan (pure
|
|
4
|
+
* functions), plus themeInject, the per-page build step that writes
|
|
5
|
+
* data-theme / data-mode and the theme stylesheet links.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import chalk from 'chalk';
|
|
9
|
+
import Util from '../utils/util/util.js';
|
|
10
|
+
import { getTheme } from '../utils/config/config.js';
|
|
11
|
+
|
|
12
|
+
const SAFE_ID = /^[a-z0-9-]+$/;
|
|
13
|
+
const isSafeId = (v) => typeof v === 'string' && SAFE_ID.test(v);
|
|
14
|
+
const has = (obj, key) => !!obj && Object.hasOwn(obj, key);
|
|
15
|
+
const isUrl = (v) => typeof v === 'string'
|
|
16
|
+
&& !/[\s"'`<>\\]/.test(v)
|
|
17
|
+
&& ((v.startsWith('/') && !v.startsWith('//')) || /^https?:\/\/[^/]/.test(v));
|
|
18
|
+
const TAG = '[theme] ';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validate a raw theme setting (config/theme.json or main.js `theme`).
|
|
22
|
+
* @param {unknown} raw
|
|
23
|
+
* @returns {{ setting: object|null, warnings: string[] }}
|
|
24
|
+
*/
|
|
25
|
+
export function normalizeThemeSetting(raw) {
|
|
26
|
+
const warnings = [];
|
|
27
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { setting: null, warnings };
|
|
28
|
+
if (!isSafeId(raw.name)) {
|
|
29
|
+
warnings.push(`${TAG}theme setting ignored: unsafe or missing name ${JSON.stringify(raw.name)}`);
|
|
30
|
+
return { setting: null, warnings };
|
|
31
|
+
}
|
|
32
|
+
let adjust = null;
|
|
33
|
+
if (raw.adjust != null) {
|
|
34
|
+
if (isSafeId(raw.adjust)) adjust = raw.adjust;
|
|
35
|
+
else warnings.push(`${TAG}theme adjust ignored: unsafe id ${JSON.stringify(raw.adjust)}`);
|
|
36
|
+
}
|
|
37
|
+
const mode = ['auto', 'light', 'dark'].includes(raw.mode) ? raw.mode : 'auto';
|
|
38
|
+
const files = Object.create(null);
|
|
39
|
+
for (const [id, url] of Object.entries(raw.files || {})) {
|
|
40
|
+
if (isSafeId(id) && isUrl(url)) files[id] = url;
|
|
41
|
+
else warnings.push(`${TAG}theme file ignored: ${JSON.stringify(id)}`);
|
|
42
|
+
}
|
|
43
|
+
const modes = Object.create(null);
|
|
44
|
+
for (const [id, m] of Object.entries(raw.modes || {})) {
|
|
45
|
+
if (isSafeId(id) && (m === 'light' || m === 'dark')) modes[id] = m;
|
|
46
|
+
else warnings.push(`${TAG}theme mode ignored: ${JSON.stringify(id)}`);
|
|
47
|
+
}
|
|
48
|
+
return { setting: { name: raw.name, mode, adjust, files, modes }, warnings };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Work out what a page gets: data-theme ids, forced scheme, stylesheet links.
|
|
53
|
+
* Ids always start with the theme name, including "default".
|
|
54
|
+
* @param {object|null} setting - Normalized setting
|
|
55
|
+
* @param {object} [frontMatter]
|
|
56
|
+
* @param {string} [pagePath] - For warnings
|
|
57
|
+
*/
|
|
58
|
+
export function pageThemePlan(setting, frontMatter = {}, pagePath = '') {
|
|
59
|
+
if (!setting) return null;
|
|
60
|
+
const warnings = [];
|
|
61
|
+
const where = pagePath || 'page';
|
|
62
|
+
const fm = frontMatter || {};
|
|
63
|
+
|
|
64
|
+
const problems = [];
|
|
65
|
+
let pageTheme = null;
|
|
66
|
+
if (fm.theme != null) {
|
|
67
|
+
if (isSafeId(fm.theme)) pageTheme = fm.theme;
|
|
68
|
+
else problems.push(`theme ${JSON.stringify(fm.theme)} (use a-z, 0-9 and hyphens)`);
|
|
69
|
+
}
|
|
70
|
+
let scope = 'page';
|
|
71
|
+
if (fm.themeScope != null) {
|
|
72
|
+
if (fm.themeScope === 'page' || fm.themeScope === 'article') scope = fm.themeScope;
|
|
73
|
+
else problems.push(`themeScope ${JSON.stringify(fm.themeScope)} (use page or article)`);
|
|
74
|
+
}
|
|
75
|
+
if (problems.length) warnings.push(`${TAG}${where}: front matter ignored: ${problems.join('; ')}`);
|
|
76
|
+
|
|
77
|
+
const siteIds = [setting.name, ...(setting.adjust ? [setting.adjust] : [])];
|
|
78
|
+
const siteForced = setting.mode === 'light' || setting.mode === 'dark' ? setting.mode : null;
|
|
79
|
+
const forced = (id) => (has(setting.modes, id) ? setting.modes[id] : null) || siteForced;
|
|
80
|
+
|
|
81
|
+
let html;
|
|
82
|
+
let scoped = null;
|
|
83
|
+
let linkIds;
|
|
84
|
+
if (pageTheme && scope === 'article') {
|
|
85
|
+
html = { ids: siteIds, mode: forced(setting.name) };
|
|
86
|
+
scoped = { ids: [pageTheme], mode: forced(pageTheme) };
|
|
87
|
+
linkIds = [...siteIds, pageTheme];
|
|
88
|
+
} else if (pageTheme) {
|
|
89
|
+
html = { ids: [pageTheme], mode: forced(pageTheme) };
|
|
90
|
+
linkIds = [pageTheme];
|
|
91
|
+
} else {
|
|
92
|
+
html = { ids: siteIds, mode: forced(setting.name) };
|
|
93
|
+
linkIds = siteIds;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const links = [];
|
|
97
|
+
for (const id of [...new Set(linkIds)]) {
|
|
98
|
+
if (has(setting.files, id) && typeof setting.files[id] === 'string') links.push({ id, href: setting.files[id] });
|
|
99
|
+
}
|
|
100
|
+
return { html, scoped, links, warnings };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
// INJECT (PER PAGE)
|
|
105
|
+
// -----------------------------
|
|
106
|
+
const VB_CSS = /vanilla-breeze[^/]*\.css/;
|
|
107
|
+
let cachedSetting;
|
|
108
|
+
let settingReady = false;
|
|
109
|
+
|
|
110
|
+
/** Forget the cached setting; called at the start of every build. */
|
|
111
|
+
export function resetThemeCache() {
|
|
112
|
+
settingReady = false;
|
|
113
|
+
cachedSetting = undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function getSetting() {
|
|
117
|
+
if (!settingReady) {
|
|
118
|
+
settingReady = true;
|
|
119
|
+
const { setting, warnings } = normalizeThemeSetting(getTheme());
|
|
120
|
+
for (const w of warnings) console.log(chalk.yellow(w));
|
|
121
|
+
cachedSetting = setting;
|
|
122
|
+
}
|
|
123
|
+
return cachedSetting;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function setTheme(el, { ids, mode }) {
|
|
127
|
+
if (ids.length) el.setAttribute('data-theme', ids.join(' '));
|
|
128
|
+
if (mode) el.setAttribute('data-mode', mode);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Per page: theme attributes on <html> (or the article) and stylesheet links.
|
|
133
|
+
* Does nothing when there is no theme setting.
|
|
134
|
+
*/
|
|
135
|
+
export async function themeInject({ file, allowType }) {
|
|
136
|
+
const setting = getSetting();
|
|
137
|
+
if (!setting) return;
|
|
138
|
+
if (!Util.isAllowedType({ file, allowType })) return;
|
|
139
|
+
|
|
140
|
+
const dom = Util.fileDom(file);
|
|
141
|
+
const document = dom.window.document;
|
|
142
|
+
const html = document.documentElement;
|
|
143
|
+
// Partials (no <html>) are not pages: leave them untouched
|
|
144
|
+
if (!html || html.tagName !== 'HTML') return;
|
|
145
|
+
|
|
146
|
+
const plan = pageThemePlan(setting, file.frontMatter, file.path);
|
|
147
|
+
const warnings = [...plan.warnings];
|
|
148
|
+
let head = document.querySelector('head');
|
|
149
|
+
if (!head) {
|
|
150
|
+
head = document.createElement('head');
|
|
151
|
+
html.insertBefore(head, html.firstChild);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let htmlTheme = plan.html;
|
|
155
|
+
let links = plan.links;
|
|
156
|
+
if (plan.scoped) {
|
|
157
|
+
const target = document.querySelector('article') || document.querySelector('main');
|
|
158
|
+
if (target) {
|
|
159
|
+
setTheme(target, plan.scoped);
|
|
160
|
+
} else {
|
|
161
|
+
warnings.push(`[theme] ${file.path}: no <article> or <main> for themeScope article; applied to the whole page`);
|
|
162
|
+
htmlTheme = plan.scoped;
|
|
163
|
+
links = plan.links.filter(l => plan.scoped.ids.includes(l.id));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const w of warnings) console.log(chalk.yellow(w));
|
|
167
|
+
|
|
168
|
+
setTheme(html, htmlTheme);
|
|
169
|
+
html.setAttribute('data-theme-source', 'site');
|
|
170
|
+
|
|
171
|
+
{
|
|
172
|
+
const sheets = [...document.querySelectorAll('link[rel~="stylesheet"]')];
|
|
173
|
+
const present = new Set();
|
|
174
|
+
for (const l of document.querySelectorAll('link')) {
|
|
175
|
+
if (l.hasAttribute('data-vb-theme')) present.add(`id:${l.getAttribute('data-vb-theme')}`);
|
|
176
|
+
}
|
|
177
|
+
for (const l of sheets) present.add(`href:${l.getAttribute('href')}`);
|
|
178
|
+
let anchor = sheets.filter(l => VB_CSS.test(l.getAttribute('href') || '')).pop() || null;
|
|
179
|
+
for (const { id, href } of links) {
|
|
180
|
+
if (present.has(`id:${id}`) || present.has(`href:${href}`)) continue;
|
|
181
|
+
const link = document.createElement('link');
|
|
182
|
+
link.setAttribute('rel', 'stylesheet');
|
|
183
|
+
link.setAttribute('href', href);
|
|
184
|
+
link.setAttribute('data-vb-theme', id);
|
|
185
|
+
if (anchor) anchor.after(link);
|
|
186
|
+
else head.appendChild(link);
|
|
187
|
+
anchor = link;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
Util.commitDom(file, dom);
|
|
191
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// ----------------------------------
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import chalk from 'chalk';
|
|
5
6
|
|
|
6
7
|
const cwd = process.cwd();
|
|
7
8
|
|
|
@@ -16,6 +17,24 @@ if (userConfigPathExists) {
|
|
|
16
17
|
userConfig = userConfigModule.default || userConfigModule;
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
// config/theme.json (written by Vanilla Press); main.js `theme` wins when defined
|
|
21
|
+
const themeJsonPath = `${cwd}/config/theme.json`;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The site theme setting. Re-read on every call so a long-lived process
|
|
25
|
+
* (`cook dev`) sees config/theme.json rewrites; main.js `theme` stays as loaded.
|
|
26
|
+
*/
|
|
27
|
+
function getTheme() {
|
|
28
|
+
if (userConfig.theme !== undefined) return userConfig.theme;
|
|
29
|
+
if (!fs.existsSync(themeJsonPath)) return undefined;
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(fs.readFileSync(themeJsonPath, 'utf8'));
|
|
32
|
+
} catch (err) {
|
|
33
|
+
console.log(chalk.yellow(`[theme] config/theme.json: ${err.message}`));
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
19
38
|
|
|
20
39
|
// DEFINE DEFAULT CONFIG
|
|
21
40
|
// -----------------------------
|
|
@@ -133,6 +152,15 @@ const defaultConfig = {
|
|
|
133
152
|
bundlePattern: /vanilla-breeze[^"']*\.js/,
|
|
134
153
|
},
|
|
135
154
|
|
|
155
|
+
// Package Components: npm web-component packages (dependencies shipping a
|
|
156
|
+
// custom-elements.json) are copied to dist/<path>/<name>/ and loaded per page
|
|
157
|
+
// by a module script, only on pages that use their tags.
|
|
158
|
+
packageComponents: {
|
|
159
|
+
enabled: true,
|
|
160
|
+
exclude: ['vanilla-breeze', 'cook-ssg'],
|
|
161
|
+
path: 'assets/components',
|
|
162
|
+
},
|
|
163
|
+
|
|
136
164
|
// Declarative Shadow DOM: Pre-render shadow DOM content for web components
|
|
137
165
|
// Requires a DSD manifest (JSON mapping tag → shadow DOM HTML)
|
|
138
166
|
// and VB components with: if (!this.shadowRoot) this.attachShadow({ mode: 'open' })
|
|
@@ -307,6 +335,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
|
|
|
307
335
|
export default config;
|
|
308
336
|
|
|
309
337
|
// Named exports for destructuring imports
|
|
338
|
+
export { getTheme };
|
|
310
339
|
export const {
|
|
311
340
|
activeLink,
|
|
312
341
|
autoComponents,
|
|
@@ -328,6 +357,7 @@ export const {
|
|
|
328
357
|
inlineAttr,
|
|
329
358
|
markdown,
|
|
330
359
|
minifyHtmlConfigCustom,
|
|
360
|
+
packageComponents,
|
|
331
361
|
plugins,
|
|
332
362
|
pluginPath,
|
|
333
363
|
repeat,
|
|
@@ -745,7 +745,8 @@ function validatePageChange() {
|
|
|
745
745
|
// single-page fast path would copy the file into dist and leave every
|
|
746
746
|
// dependent page stale. Match whole directory segments only: a PAGE
|
|
747
747
|
// named template-strings-demo.html is still a fast-path page change.
|
|
748
|
-
const isBuildOnly = changedDevPage && /\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage)
|
|
748
|
+
const isBuildOnly = changedDevPage && (/\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage)
|
|
749
|
+
|| /\/config\/theme\.json$/.test(changedDevPage));
|
|
749
750
|
// Return true (valid) if it was a page change AND it wasn't a build-only file
|
|
750
751
|
return changedDevPage && !isBuildOnly;
|
|
751
752
|
}
|