cook-ssg 2.7.0 → 2.8.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/bin/cook.js +27 -0
- package/package.json +3 -2
- package/scripts/build.js +8 -2
- package/scripts/layouts.js +9 -0
- package/scripts/plugins/apply-template.js +32 -35
- package/scripts/plugins/conditional-sections.js +34 -0
- package/scripts/plugins/process-markdown.js +39 -13
- package/scripts/plugins/repeat-collection.js +68 -6
- package/scripts/plugins/replace-include.js +18 -1
- package/scripts/utils/layouts/check.js +667 -0
- package/scripts/utils/layouts/conditionals.js +357 -0
- package/scripts/utils/layouts/list.js +182 -0
- package/scripts/utils/layouts/parse.js +133 -0
- package/scripts/utils/layouts/render.js +309 -0
- package/scripts/utils/layouts/vocabulary.js +87 -0
package/bin/cook.js
CHANGED
|
@@ -23,6 +23,7 @@ Usage:
|
|
|
23
23
|
cook build Build the site (production)
|
|
24
24
|
cook dev Build + live-reload dev server
|
|
25
25
|
cook dev --port N Dev server on a custom port (default: 3000)
|
|
26
|
+
cook check-layouts Check src/layouts and src/includes against the layout format
|
|
26
27
|
cook --help Show this help
|
|
27
28
|
cook --version Show version
|
|
28
29
|
`);
|
|
@@ -48,6 +49,32 @@ switch (command) {
|
|
|
48
49
|
break;
|
|
49
50
|
}
|
|
50
51
|
|
|
52
|
+
case 'check-layouts': {
|
|
53
|
+
const { listLayouts } = await import('../scripts/layouts.js');
|
|
54
|
+
const { layouts, includes, problems } = await listLayouts(process.cwd());
|
|
55
|
+
let failed = false;
|
|
56
|
+
for (const { file, line, message } of problems) {
|
|
57
|
+
failed = true;
|
|
58
|
+
console.log(`${file}:${line}: ${message}`);
|
|
59
|
+
}
|
|
60
|
+
const report = (dir, items) => {
|
|
61
|
+
for (const item of items) {
|
|
62
|
+
for (const { line, message } of item.problems) {
|
|
63
|
+
failed = true;
|
|
64
|
+
console.log(`src/${dir}/${item.file}:${line}: ${message}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
report('layouts', layouts);
|
|
69
|
+
report('includes', includes);
|
|
70
|
+
const plain = layouts.filter(l => l.kind === 'plain').length
|
|
71
|
+
+ includes.filter(i => !i.ok && i.problems.length === 0).length;
|
|
72
|
+
const editable = layouts.filter(l => l.editable).length;
|
|
73
|
+
const withProblems = [...layouts, ...includes].filter(i => i.problems.length > 0).length;
|
|
74
|
+
console.log(`${layouts.length} layouts, ${includes.length} includes: ${editable} editable, ${plain} plain, ${withProblems} with problems`);
|
|
75
|
+
process.exit(failed ? 1 : 0);
|
|
76
|
+
}
|
|
77
|
+
|
|
51
78
|
case '--version':
|
|
52
79
|
case '-v':
|
|
53
80
|
console.log(pkg.version);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cook-ssg",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./scripts/build.js",
|
|
12
12
|
"./build": "./scripts/build.js",
|
|
13
|
-
"./dev": "./scripts/dev.js"
|
|
13
|
+
"./dev": "./scripts/dev.js",
|
|
14
|
+
"./layouts": "./scripts/layouts.js"
|
|
14
15
|
},
|
|
15
16
|
"files": [
|
|
16
17
|
"bin/",
|
package/scripts/build.js
CHANGED
|
@@ -39,6 +39,7 @@ import replaceInclude from './plugins/replace-include.js';
|
|
|
39
39
|
import replaceInline from './plugins/replace-inline.js';
|
|
40
40
|
import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
|
|
41
41
|
import replaceTemplateStrings from './plugins/replace-template-strings.js';
|
|
42
|
+
import conditionalSections from './plugins/conditional-sections.js';
|
|
42
43
|
import setActiveLinks from './plugins/set-active-links.js';
|
|
43
44
|
|
|
44
45
|
// GET SOURCE
|
|
@@ -130,7 +131,8 @@ class Build {
|
|
|
130
131
|
// A failing page is recorded and skipped — one bad page must not
|
|
131
132
|
// kill the other N-1. Failures are reported after the loop and the
|
|
132
133
|
// process exits non-zero so CI/deploys still catch them.
|
|
133
|
-
|
|
134
|
+
// Markdown pages that failed the same way (a broken layout chain) count too.
|
|
135
|
+
const failedPages = [...(store.failedMarkdownPages || [])];
|
|
134
136
|
await runFileLoop(files, fileLoop);
|
|
135
137
|
async function fileLoop(fileName) {
|
|
136
138
|
let file;
|
|
@@ -164,7 +166,7 @@ class Build {
|
|
|
164
166
|
|
|
165
167
|
// PLUGIN: Apply layout template from [data-template] attribute
|
|
166
168
|
// Also checks file.frontMatter.layout as a fallback
|
|
167
|
-
await applyTemplate({file, store, allowType: ['.html']});
|
|
169
|
+
await applyTemplate({file, store, data, allowType: ['.html']});
|
|
168
170
|
|
|
169
171
|
// PLUGIN: Replace `[data-include]` in files
|
|
170
172
|
// Runs after template: includes inside the template get resolved
|
|
@@ -179,6 +181,10 @@ class Build {
|
|
|
179
181
|
// Runs third: components expand templates with attribute values (their own ${var} replacement)
|
|
180
182
|
await replaceComponents({file, store, data, allowType: ['.html']});
|
|
181
183
|
|
|
184
|
+
// PLUGIN: data-if / data-unless left after layouts and repeats (includes, site data)
|
|
185
|
+
// Every remaining key is known here, from data and front matter; a missing one is not set
|
|
186
|
+
conditionalSections({file, data, allowType: ['.html']});
|
|
187
|
+
|
|
182
188
|
// PLUGIN: Render all ES6 template strings
|
|
183
189
|
// Runs last: resolves ${var} across the fully assembled page (includes + components + repeats)
|
|
184
190
|
// Merge front matter data so page-level variables resolve alongside global data
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file layouts.js
|
|
3
|
+
* @description Public entry point (`cook-ssg/layouts`): the layout checker,
|
|
4
|
+
* the layout lister and the format constants.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export { checkLayout } from './utils/layouts/check.js';
|
|
8
|
+
export { listLayouts, loadSiteNames } from './utils/layouts/list.js';
|
|
9
|
+
export { FORMAT, PAGE_LAYOUTS, DOCUMENT_FIELDS } from './utils/layouts/vocabulary.js';
|
|
@@ -20,7 +20,8 @@ import { promises as fs } from 'node:fs';
|
|
|
20
20
|
import { existsSync } from 'node:fs';
|
|
21
21
|
import path from 'node:path';
|
|
22
22
|
import Util from '../utils/util/util.js';
|
|
23
|
-
import {
|
|
23
|
+
import { renderLayout, extractSlots, findTemplatedTag, templateDataAttrs } from '../utils/layouts/render.js';
|
|
24
|
+
import { layoutConditionals } from '../utils/layouts/conditionals.js';
|
|
24
25
|
|
|
25
26
|
// Config
|
|
26
27
|
import { srcPath, distPath } from '../utils/config/config.js';
|
|
@@ -29,10 +30,11 @@ import { srcPath, distPath } from '../utils/config/config.js';
|
|
|
29
30
|
// DEFINE
|
|
30
31
|
// -----------------------------
|
|
31
32
|
class ApplyTemplate {
|
|
32
|
-
constructor({ file, store, allowType, disallowType }) {
|
|
33
|
+
constructor({ file, store, data, allowType, disallowType }) {
|
|
33
34
|
this.opts = { file, allowType, disallowType };
|
|
34
35
|
this.file = file;
|
|
35
36
|
this.store = store;
|
|
37
|
+
this.data = data || {};
|
|
36
38
|
this.allowType = allowType;
|
|
37
39
|
this.disallowType = disallowType;
|
|
38
40
|
|
|
@@ -56,15 +58,14 @@ class ApplyTemplate {
|
|
|
56
58
|
|| null;
|
|
57
59
|
if (!templateName) return;
|
|
58
60
|
|
|
59
|
-
// Load the template
|
|
60
|
-
const templateContent = await this.getTemplate(templateName);
|
|
61
|
-
if (!templateContent) return;
|
|
62
|
-
|
|
63
61
|
// Extract page metadata and content from the source page
|
|
64
62
|
const pageData = this.extractPageData();
|
|
65
63
|
|
|
66
|
-
// Merge page content into the template
|
|
67
|
-
|
|
64
|
+
// Merge page content into the template (and, for a child layout,
|
|
65
|
+
// its parents). null: the layout wasn't found, leave the page as is.
|
|
66
|
+
const rendered = await this.applyTemplate(templateName, pageData);
|
|
67
|
+
if (rendered === null) return;
|
|
68
|
+
this.file.src = rendered;
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
/**
|
|
@@ -74,9 +75,9 @@ class ApplyTemplate {
|
|
|
74
75
|
* @returns {string|null} Template name or null
|
|
75
76
|
*/
|
|
76
77
|
findTemplateName() {
|
|
77
|
-
// Match data-template on <html> or <body
|
|
78
|
-
const
|
|
79
|
-
return
|
|
78
|
+
// Match data-template on <html> or <body>, value in any quoting
|
|
79
|
+
const tag = findTemplatedTag(this.file.src);
|
|
80
|
+
return tag ? tag.name : null;
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
/**
|
|
@@ -139,16 +140,10 @@ class ApplyTemplate {
|
|
|
139
140
|
|
|
140
141
|
// Extract data-* attributes from the element with data-template
|
|
141
142
|
// These become template variables (e.g., data-author="Kim" → ${author})
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
let attrMatch;
|
|
147
|
-
while ((attrMatch = attrPattern.exec(attrs)) !== null) {
|
|
148
|
-
// Convert kebab-case to camelCase for template vars
|
|
149
|
-
const key = attrMatch[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
150
|
-
data[key] = attrMatch[2];
|
|
151
|
-
}
|
|
143
|
+
// (any quoting; kebab-case names become camelCase vars)
|
|
144
|
+
const templateEl = findTemplatedTag(this.file.src);
|
|
145
|
+
if (templateEl) {
|
|
146
|
+
Object.assign(data, templateDataAttrs(templateEl.attrs));
|
|
152
147
|
}
|
|
153
148
|
|
|
154
149
|
// For pages with front matter (no <body> wrapper), the entire file.src IS the content
|
|
@@ -169,37 +164,39 @@ class ApplyTemplate {
|
|
|
169
164
|
}
|
|
170
165
|
}
|
|
171
166
|
|
|
172
|
-
// Extract named slots from <template slot="name"> elements
|
|
167
|
+
// Extract named slots from top-level <template slot="name"> elements
|
|
168
|
+
// (nested <template>s inside a slot are kept whole).
|
|
173
169
|
// These provide content for ${slot:name} placeholders in layouts.
|
|
174
170
|
// Remaining content (after slot extraction) becomes ${content}.
|
|
175
171
|
if (rawContent) {
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
data[`slot:${slotMatch[1]}`] = slotMatch[2].trim();
|
|
172
|
+
const { content, slots } = extractSlots(rawContent);
|
|
173
|
+
for (const [name, value] of Object.entries(slots)) {
|
|
174
|
+
data[`slot:${name}`] = value;
|
|
180
175
|
}
|
|
181
|
-
|
|
182
|
-
data.content = rawContent.replace(slotPattern, '').trim();
|
|
176
|
+
data.content = content;
|
|
183
177
|
}
|
|
184
178
|
|
|
185
179
|
return data;
|
|
186
180
|
}
|
|
187
181
|
|
|
188
182
|
/**
|
|
189
|
-
*
|
|
183
|
+
* Render the page through the named layout and any layouts it extends.
|
|
190
184
|
* Replaces ${content} and other ${var} placeholders.
|
|
191
|
-
* @param {string}
|
|
185
|
+
* @param {string} name - Layout name
|
|
192
186
|
* @param {Object} pageData - Extracted page data
|
|
193
|
-
* @returns {string} Merged HTML
|
|
187
|
+
* @returns {Promise<string|null>} Merged HTML, or null if the layout is missing
|
|
194
188
|
*/
|
|
195
|
-
applyTemplate(
|
|
196
|
-
// Shared interpolator: single pass over
|
|
189
|
+
applyTemplate(name, pageData) {
|
|
190
|
+
// Shared interpolator: single pass over each LAYOUT only, callback
|
|
197
191
|
// insertion (page content with $-patterns and ${...} in code samples
|
|
198
192
|
// is never scanned), unmatched vars deferred to replaceTemplateStrings,
|
|
199
193
|
// unfilled ${slot:...} removed. ${content} always resolves (empty
|
|
200
194
|
// string when the page produced none).
|
|
201
|
-
return
|
|
202
|
-
|
|
195
|
+
return renderLayout(name, { ...pageData, content: pageData.content || '' }, {
|
|
196
|
+
loadLayout: (layoutName) => this.getTemplate(layoutName),
|
|
197
|
+
data: this.data,
|
|
198
|
+
// data-if / data-unless on page fields, slots and site data
|
|
199
|
+
conditionals: layoutConditionals,
|
|
203
200
|
});
|
|
204
201
|
}
|
|
205
202
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file conditional-sections.js
|
|
3
|
+
* @description The late `data-if` / `data-unless` pass, right before
|
|
4
|
+
* `replaceTemplateStrings`. Layouts decide page fields and slots, and
|
|
5
|
+
* `data-repeat` decides `alias.x` keys per item; what is left here (from
|
|
6
|
+
* includes, or keys a layout couldn't know) is decided from
|
|
7
|
+
* `{ ...data, ...file.frontMatter }`. Every key is known here: a missing
|
|
8
|
+
* one is not set.
|
|
9
|
+
*
|
|
10
|
+
* A page with neither marker is left exactly as it is.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// IMPORTS
|
|
14
|
+
// -----------------------------
|
|
15
|
+
import Util from '../utils/util/util.js';
|
|
16
|
+
import { lateConditionals } from '../utils/layouts/conditionals.js';
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
// DEFINE
|
|
20
|
+
// -----------------------------
|
|
21
|
+
/**
|
|
22
|
+
* @param {Object} opts
|
|
23
|
+
* @property {Object} opts.file - Current file info
|
|
24
|
+
* @property {Object} opts.data - User data from config/data.js
|
|
25
|
+
* @property {Array} [opts.allowType] - Allowed file types
|
|
26
|
+
* @property {Array} [opts.disallowType] - Disallowed file types
|
|
27
|
+
*/
|
|
28
|
+
export default function conditionalSections({ file, data, allowType, disallowType }) {
|
|
29
|
+
// Early Exit: File type not allowed
|
|
30
|
+
if (!Util.isAllowedType({ file, allowType, disallowType })) return;
|
|
31
|
+
|
|
32
|
+
const values = file.frontMatter ? { ...data, ...file.frontMatter } : (data || {});
|
|
33
|
+
file.src = lateConditionals(file.src, values);
|
|
34
|
+
}
|
|
@@ -13,7 +13,8 @@ import { marked } from 'marked';
|
|
|
13
13
|
import matter from 'gray-matter';
|
|
14
14
|
import Logger from '../utils/logger/logger.js';
|
|
15
15
|
import Util from '../utils/util/util.js';
|
|
16
|
-
import {
|
|
16
|
+
import { renderLayout, LayoutChainError } from '../utils/layouts/render.js';
|
|
17
|
+
import { layoutConditionals } from '../utils/layouts/conditionals.js';
|
|
17
18
|
|
|
18
19
|
// Config
|
|
19
20
|
import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
|
|
@@ -63,6 +64,10 @@ class ProcessMarkdown {
|
|
|
63
64
|
|
|
64
65
|
// Track processed files
|
|
65
66
|
this.processedFiles = [];
|
|
67
|
+
|
|
68
|
+
// Pages whose layout chain is broken (cycle, too deep): build errors,
|
|
69
|
+
// reported with the page loop's failures. Reset every build.
|
|
70
|
+
this.store.failedMarkdownPages = [];
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
// INIT
|
|
@@ -166,6 +171,13 @@ class ProcessMarkdown {
|
|
|
166
171
|
});
|
|
167
172
|
|
|
168
173
|
} catch (err) {
|
|
174
|
+
if (err instanceof LayoutChainError) {
|
|
175
|
+
// A layout cycle or over-deep chain fails the build, as for HTML pages
|
|
176
|
+
this.store.failedMarkdownPages.push({ page: filePath, error: err });
|
|
177
|
+
console.warn(chalk.yellow(`\n[build] Page failed: ${filePath}`));
|
|
178
|
+
console.warn(` ${err.message}`);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
169
181
|
Util.customWarn(err, `ProcessMarkdown: ${filePath} (page skipped)`);
|
|
170
182
|
}
|
|
171
183
|
}
|
|
@@ -221,24 +233,38 @@ class ProcessMarkdown {
|
|
|
221
233
|
* @returns {string} Final HTML
|
|
222
234
|
*/
|
|
223
235
|
async applyLayout(layoutName, pageData) {
|
|
224
|
-
//
|
|
225
|
-
const layoutContent = await this.getLayout(layoutName);
|
|
226
|
-
|
|
227
|
-
if (!layoutContent) {
|
|
228
|
-
// Fallback to basic HTML if layout not found
|
|
229
|
-
console.log(chalk.yellow(` Layout "${layoutName}" not found, using basic HTML`));
|
|
230
|
-
return this.buildBasicHtml(pageData);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Shared interpolator: single pass over the LAYOUT only — markdown
|
|
236
|
+
// Shared interpolator: single pass over each LAYOUT only — markdown
|
|
234
237
|
// content (which legitimately contains ${...} and $-patterns in code
|
|
235
238
|
// samples) is never scanned for substitution. Page data wins over
|
|
236
|
-
// global data; ${content} always resolves.
|
|
237
|
-
|
|
239
|
+
// global data; ${content} always resolves. A child layout is applied,
|
|
240
|
+
// then its parent, and so on.
|
|
241
|
+
let missingParent = false;
|
|
242
|
+
const finalHtml = await renderLayout(layoutName, {
|
|
238
243
|
...this.data,
|
|
239
244
|
...pageData,
|
|
240
245
|
content: pageData.content ?? '',
|
|
246
|
+
}, {
|
|
247
|
+
loadLayout: (name) => this.getLayout(name),
|
|
248
|
+
data: this.data,
|
|
249
|
+
// data-if / data-unless on page fields, slots and site data. Page
|
|
250
|
+
// fields are decided here: by the page loop they are gone (ruling P5).
|
|
251
|
+
conditionals: layoutConditionals,
|
|
252
|
+
// A plain layout keeps unfilled ${slot:x}, as it always has here
|
|
253
|
+
removeUnmatchedSlots: false,
|
|
254
|
+
// The layout exists but a layout it extends doesn't: say which
|
|
255
|
+
onMissingParent: (message) => {
|
|
256
|
+
missingParent = true;
|
|
257
|
+
console.log(chalk.yellow(` ${message}, using basic HTML`));
|
|
258
|
+
},
|
|
241
259
|
});
|
|
260
|
+
|
|
261
|
+
if (finalHtml === null) {
|
|
262
|
+
// Fallback to basic HTML if layout not found
|
|
263
|
+
if (!missingParent) console.log(chalk.yellow(` Layout "${layoutName}" not found, using basic HTML`));
|
|
264
|
+
return this.buildBasicHtml(pageData);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return finalHtml;
|
|
242
268
|
}
|
|
243
269
|
|
|
244
270
|
/**
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import chalk from 'chalk';
|
|
23
23
|
import Util from '../utils/util/util.js';
|
|
24
24
|
import { renderTemplate as interpolate, getNested } from '../utils/interpolate/interpolate.js';
|
|
25
|
+
import { applyConditionals, isSet } from '../utils/layouts/conditionals.js';
|
|
25
26
|
|
|
26
27
|
// Config
|
|
27
28
|
import { repeat as repeatConfig } from '../utils/config/config.js';
|
|
@@ -111,8 +112,9 @@ class RepeatCollection {
|
|
|
111
112
|
* @param {Element} element - The element with data-repeat
|
|
112
113
|
* @param {Document} document - The document object
|
|
113
114
|
* @param {Object} outerContext - Enclosing iteration context (loop vars)
|
|
115
|
+
* @param {string[]} [outerAliases] - Loop variable names of enclosing repeats
|
|
114
116
|
*/
|
|
115
|
-
processRepeatElement(element, document, outerContext = {}) {
|
|
117
|
+
processRepeatElement(element, document, outerContext = {}, outerAliases = []) {
|
|
116
118
|
const expression = element.getAttribute(this.config.attribute);
|
|
117
119
|
if (!expression) return;
|
|
118
120
|
|
|
@@ -156,6 +158,10 @@ class RepeatCollection {
|
|
|
156
158
|
// Create a document fragment to hold all repeated elements
|
|
157
159
|
const fragment = document.createDocumentFragment();
|
|
158
160
|
|
|
161
|
+
// Loop variable names visible inside this repeat: data-if/data-unless
|
|
162
|
+
// keys under one of them (`post.image`) are decided per item here
|
|
163
|
+
const aliases = [...outerAliases, parsed.itemName, ...(parsed.indexName ? [parsed.indexName] : [])];
|
|
164
|
+
|
|
159
165
|
// Generate repeated elements
|
|
160
166
|
collection.forEach((item, index) => {
|
|
161
167
|
// Clone the original element
|
|
@@ -179,8 +185,13 @@ class RepeatCollection {
|
|
|
179
185
|
context[parsed.indexName] = index;
|
|
180
186
|
}
|
|
181
187
|
|
|
182
|
-
//
|
|
183
|
-
|
|
188
|
+
// The element's own data-if/data-unless on a loop variable: decide it
|
|
189
|
+
if (!this.keepForItem(clone, aliases, context)) return;
|
|
190
|
+
|
|
191
|
+
// data-if/data-unless on loop variables inside the item, then
|
|
192
|
+
// replace template variables in the content
|
|
193
|
+
const itemTemplate = this.applyItemConditionals(template, aliases, context);
|
|
194
|
+
const renderedContent = this.renderTemplate(itemTemplate, context);
|
|
184
195
|
clone.innerHTML = renderedContent;
|
|
185
196
|
|
|
186
197
|
// Also process attributes on the clone itself
|
|
@@ -188,7 +199,7 @@ class RepeatCollection {
|
|
|
188
199
|
|
|
189
200
|
// Recursively expand nested data-repeat elements with this
|
|
190
201
|
// iteration's context, so they can loop over loop variables
|
|
191
|
-
this.processNestedRepeats(clone, document, context);
|
|
202
|
+
this.processNestedRepeats(clone, document, context, aliases);
|
|
192
203
|
|
|
193
204
|
fragment.appendChild(clone);
|
|
194
205
|
});
|
|
@@ -203,8 +214,9 @@ class RepeatCollection {
|
|
|
203
214
|
* @param {Element} container - The clone to search within
|
|
204
215
|
* @param {Document} document - The document object
|
|
205
216
|
* @param {Object} context - The iteration context of the enclosing loop
|
|
217
|
+
* @param {string[]} aliases - Loop variable names of the enclosing loops
|
|
206
218
|
*/
|
|
207
|
-
processNestedRepeats(container, document, context) {
|
|
219
|
+
processNestedRepeats(container, document, context, aliases) {
|
|
208
220
|
const nested = Array.from(container.querySelectorAll(`[${this.config.attribute}]`))
|
|
209
221
|
.filter(el => {
|
|
210
222
|
// Keep only repeats whose nearest repeat ancestor is the container
|
|
@@ -216,8 +228,58 @@ class RepeatCollection {
|
|
|
216
228
|
return true;
|
|
217
229
|
});
|
|
218
230
|
for (const el of nested) {
|
|
219
|
-
this.processRepeatElement(el, document, context);
|
|
231
|
+
this.processRepeatElement(el, document, context, aliases);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Lookup for data-if/data-unless inside a repeated item: keys under a
|
|
237
|
+
* loop variable are known (from the iteration context); any other key
|
|
238
|
+
* is left for the late pass.
|
|
239
|
+
* @param {string[]} aliases
|
|
240
|
+
* @param {Object} context
|
|
241
|
+
* @returns {(key: string) => { known: boolean, value?: any }}
|
|
242
|
+
*/
|
|
243
|
+
itemLookup(aliases, context) {
|
|
244
|
+
return (key) => (aliases.includes(key.split('.')[0])
|
|
245
|
+
? { known: true, value: this.getNestedValue(context, key) }
|
|
246
|
+
: { known: false });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Apply data-if/data-unless on loop variables to an item's template.
|
|
251
|
+
* Returns the template itself when it has neither marker.
|
|
252
|
+
* @param {string} template
|
|
253
|
+
* @param {string[]} aliases
|
|
254
|
+
* @param {Object} context
|
|
255
|
+
* @returns {string}
|
|
256
|
+
*/
|
|
257
|
+
applyItemConditionals(template, aliases, context) {
|
|
258
|
+
return applyConditionals(template, this.itemLookup(aliases, context));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Decide the repeated element's own data-if/data-unless when its key is
|
|
263
|
+
* a loop variable: false drops this item; true strips the attribute.
|
|
264
|
+
* Other keys stay for the late pass.
|
|
265
|
+
* @param {Element} clone
|
|
266
|
+
* @param {string[]} aliases
|
|
267
|
+
* @param {Object} context
|
|
268
|
+
* @returns {boolean} Whether the item is kept
|
|
269
|
+
*/
|
|
270
|
+
keepForItem(clone, aliases, context) {
|
|
271
|
+
const lookup = this.itemLookup(aliases, context);
|
|
272
|
+
for (const name of ['data-if', 'data-unless']) {
|
|
273
|
+
if (!clone.hasAttribute(name)) continue;
|
|
274
|
+
const key = clone.getAttribute(name).trim();
|
|
275
|
+
if (!key) continue;
|
|
276
|
+
const result = lookup(key);
|
|
277
|
+
if (!result.known) continue;
|
|
278
|
+
const set = isSet(result.value);
|
|
279
|
+
if (name === 'data-if' ? !set : set) return false;
|
|
280
|
+
clone.removeAttribute(name);
|
|
220
281
|
}
|
|
282
|
+
return true;
|
|
221
283
|
}
|
|
222
284
|
|
|
223
285
|
/**
|
|
@@ -14,6 +14,22 @@ import Util from '../utils/util/util.js';
|
|
|
14
14
|
import { convertPageToDirectory, distPath, srcPath } from '../utils/config/config.js';
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
// A format-1 fragment's leading marker (see utils/layouts/list.js) and the
|
|
18
|
+
// line break after it. It is for `cook check-layouts`, not for the page.
|
|
19
|
+
const FRAGMENT_MARKER = /^(\s*)<!--\s*layout-fragment\s*-->[ \t]*\r?\n?/;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Remove a leading `<!-- layout-fragment -->` marker from include content.
|
|
23
|
+
* Content without the marker is returned as is.
|
|
24
|
+
* @param {string} content
|
|
25
|
+
* @returns {string}
|
|
26
|
+
*/
|
|
27
|
+
function stripFragmentMarker(content) {
|
|
28
|
+
if (typeof content !== 'string' || !content.includes('layout-fragment')) return content;
|
|
29
|
+
return content.replace(FRAGMENT_MARKER, '$1');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
17
33
|
// DEFINE
|
|
18
34
|
// -----------------------------
|
|
19
35
|
/**
|
|
@@ -139,6 +155,7 @@ class ReplaceInclude {
|
|
|
139
155
|
console.warn(chalk.yellow(` [include] Not found: "${filePath}" referenced in ${this.file.path}`));
|
|
140
156
|
content = `<!-- cook:include-not-found ${filePath} -->`;
|
|
141
157
|
}
|
|
158
|
+
content = stripFragmentMarker(content);
|
|
142
159
|
src = src.substring(0, match.index) + content + src.substring(match.index + match[0].length);
|
|
143
160
|
onReplace();
|
|
144
161
|
}
|
|
@@ -195,7 +212,7 @@ class ReplaceInclude {
|
|
|
195
212
|
// ADD CONTENT TO DOM
|
|
196
213
|
// Replace the include element with the fetched content using outerHTML.
|
|
197
214
|
// This keeps content in the correct DOM context (e.g., <head> stays in <head>).
|
|
198
|
-
el.outerHTML = content;
|
|
215
|
+
el.outerHTML = stripFragmentMarker(content);
|
|
199
216
|
}
|
|
200
217
|
catch (err) {
|
|
201
218
|
Util.customWarn(err, `replace-includes.js: ${this.file.path}`);
|