cook-ssg 2.5.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 +5 -0
- package/scripts/dev.js +5 -0
- package/scripts/plugins/theme.js +191 -0
- package/scripts/utils/config/config.js +20 -0
- package/scripts/utils/util/util.js +2 -1
package/package.json
CHANGED
package/scripts/build.js
CHANGED
|
@@ -25,6 +25,7 @@ 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';
|
|
28
29
|
import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
|
|
29
30
|
import processMarkdown from './plugins/process-markdown.js';
|
|
30
31
|
import repeatCollection from './plugins/repeat-collection.js';
|
|
@@ -185,6 +186,9 @@ class Build {
|
|
|
185
186
|
// PLUGIN: Add a module script for npm component packages used on the page
|
|
186
187
|
await packageComponentsInject({file, store, allowType: ['.html']});
|
|
187
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
|
+
|
|
188
192
|
// PLUGIN: Pre-render Declarative Shadow DOM for web components
|
|
189
193
|
await declarativeShadowDom({file, store, allowType: ['.html']});
|
|
190
194
|
|
|
@@ -278,6 +282,7 @@ export async function runBuild() {
|
|
|
278
282
|
delete store.cachedLayouts;
|
|
279
283
|
delete store.cachedInline;
|
|
280
284
|
}
|
|
285
|
+
resetThemeCache();
|
|
281
286
|
store.bundle = { css: {}, js: {} };
|
|
282
287
|
// Collections are fully rebuilt by processMarkdown every run — stale
|
|
283
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); });
|
|
@@ -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
|
// -----------------------------
|
|
@@ -316,6 +335,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
|
|
|
316
335
|
export default config;
|
|
317
336
|
|
|
318
337
|
// Named exports for destructuring imports
|
|
338
|
+
export { getTheme };
|
|
319
339
|
export const {
|
|
320
340
|
activeLink,
|
|
321
341
|
autoComponents,
|
|
@@ -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
|
}
|