@clarusjs/content 0.1.0 → 0.2.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/dist/highlight.js +6 -9
- package/dist/index.d.ts +10 -0
- package/dist/index.js +124 -35
- package/dist/snippets.js +0 -15
- package/package.json +4 -4
package/dist/highlight.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// Build-time code highlighting with Shiki. Synchronous (the JavaScript regex engine, grammars imported up front),
|
|
2
|
-
// because a page source turns Markdown into .tscl synchronously. Nothing here reaches the browser.
|
|
3
1
|
import { createHighlighterCoreSync } from 'shiki/core';
|
|
4
2
|
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
|
|
5
3
|
import { transformerMetaHighlight, transformerNotationDiff, transformerNotationErrorLevel, transformerNotationFocus, transformerNotationHighlight, } from '@shikijs/transformers';
|
|
@@ -15,13 +13,13 @@ import toml from 'shiki/langs/toml.mjs';
|
|
|
15
13
|
import tsx from 'shiki/langs/tsx.mjs';
|
|
16
14
|
import typescript from 'shiki/langs/typescript.mjs';
|
|
17
15
|
import yaml from 'shiki/langs/yaml.mjs';
|
|
18
|
-
import githubDark from 'shiki/themes/github-dark.mjs';
|
|
19
|
-
import githubLight from 'shiki/themes/github-light.mjs';
|
|
20
|
-
// .tscl templates read like Angular's: {{ }}, [prop], (event) and @if/@for, so they borrow its grammar.
|
|
16
|
+
import githubDark from 'shiki/themes/github-dark-default.mjs';
|
|
17
|
+
import githubLight from 'shiki/themes/github-light-default.mjs';
|
|
21
18
|
const ALIASES = { tscl: 'angular-html', ts: 'typescript', js: 'javascript', sh: 'bash', shell: 'bash', zsh: 'bash', md: 'markdown', yml: 'yaml' };
|
|
19
|
+
const light = JSON.parse(JSON.stringify(githubLight).replace(/#6e7781/gi, '#59636e'));
|
|
22
20
|
let highlighter;
|
|
23
21
|
const get = () => (highlighter ??= createHighlighterCoreSync({
|
|
24
|
-
themes: [
|
|
22
|
+
themes: [light, githubDark],
|
|
25
23
|
langs: [angularHtml, bash, css, diff, html, javascript, json, markdown, toml, tsx, typescript, yaml],
|
|
26
24
|
engine: createJavaScriptRegexEngine(),
|
|
27
25
|
}));
|
|
@@ -32,15 +30,14 @@ const transformers = [
|
|
|
32
30
|
transformerNotationErrorLevel(),
|
|
33
31
|
transformerMetaHighlight(),
|
|
34
32
|
];
|
|
35
|
-
/** Highlighted <pre> for `code` in `lang` (unknown languages are plain text); `meta` carries `{1,3-5}`. */
|
|
36
33
|
export function highlight(code, lang, meta) {
|
|
37
34
|
const hl = get();
|
|
38
35
|
const id = ALIASES[lang] ?? lang;
|
|
39
36
|
const known = hl.getLoadedLanguages().includes(id);
|
|
40
37
|
return hl.codeToHtml(code, {
|
|
41
38
|
lang: known ? id : 'text',
|
|
42
|
-
themes: { light: 'github-light', dark: 'github-dark' },
|
|
43
|
-
defaultColor: false,
|
|
39
|
+
themes: { light: 'github-light-default', dark: 'github-dark-default' },
|
|
40
|
+
defaultColor: false,
|
|
44
41
|
meta: { __raw: meta },
|
|
45
42
|
transformers,
|
|
46
43
|
});
|
package/dist/index.d.ts
CHANGED
|
@@ -17,6 +17,16 @@ export type MarkdownOptions = {
|
|
|
17
17
|
tag: string;
|
|
18
18
|
from: string;
|
|
19
19
|
};
|
|
20
|
+
/**
|
|
21
|
+
* Render `::: quiz` blocks through your quiz component (an island): `<tag [name] [question] [options] [answer]>`
|
|
22
|
+
* with the explanation as its content. Without it they are static HTML that works without JavaScript.
|
|
23
|
+
*/
|
|
24
|
+
quiz?: {
|
|
25
|
+
tag: string;
|
|
26
|
+
from: string;
|
|
27
|
+
};
|
|
28
|
+
/** `::: quiz` is for lessons (frontmatter `steps: true`); 'everywhere' allows it on any page. */
|
|
29
|
+
quizzes?: 'lessons' | 'everywhere';
|
|
20
30
|
};
|
|
21
31
|
/** 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking. */
|
|
22
32
|
export declare function slugify(text: string): string;
|
package/dist/index.js
CHANGED
|
@@ -1,27 +1,20 @@
|
|
|
1
|
-
// Markdown pages for clarusjs. A page source: each .md file under src/pages becomes .tscl text (its HTML inside
|
|
2
|
-
// the layout), then compiles like any page. Build-time only: nothing here reaches the browser.
|
|
3
1
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
4
2
|
import MarkdownIt from 'markdown-it';
|
|
5
3
|
import { parse as parseYaml } from 'yaml';
|
|
6
4
|
import { highlight } from './highlight.js';
|
|
7
5
|
import { expand } from './snippets.js';
|
|
8
|
-
const TYPES = ['tip', 'info', 'warning', 'danger', 'details', 'code-group'];
|
|
6
|
+
const TYPES = ['tip', 'info', 'warning', 'danger', 'details', 'code-group', 'quiz'];
|
|
9
7
|
const TITLES = { tip: 'Tip', info: 'Info', warning: 'Warning', danger: 'Danger', details: 'Details', note: 'Note', important: 'Important', caution: 'Caution' };
|
|
10
|
-
// GitHub alerts → container type (the alert's name stays its title).
|
|
11
8
|
const ALERTS = { note: 'info', tip: 'tip', important: 'info', warning: 'warning', caution: 'danger' };
|
|
12
|
-
/** Text safe inside generated .tscl markup: HTML escaped, and nothing a template would read ({ } @). */
|
|
13
9
|
const inert = (s) => escapeHtml(s).replace(/\{/g, '{').replace(/\}/g, '}').replace(/@/g, '@');
|
|
14
|
-
/** 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking. */
|
|
15
10
|
export function slugify(text) {
|
|
16
11
|
return text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\w\s-]/g, '').trim().replace(/[\s_-]+/g, '-') || 'section';
|
|
17
12
|
}
|
|
18
|
-
/** A JavaScript string literal that is safe inside a double-quoted .tscl attribute. */
|
|
19
13
|
const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\u0022').replace(/\n/g, '\\n')}'`;
|
|
20
14
|
const escapeHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
21
15
|
function renderer(options) {
|
|
22
16
|
const md = new MarkdownIt({ html: true, linkify: true });
|
|
23
17
|
const titles = { ...TITLES, ...options.titles };
|
|
24
|
-
// ::: type [title] … ::: (a longer fence, such as ::::, nests around a shorter one).
|
|
25
18
|
md.block.ruler.before('fence', 'cl_container', (state, startLine, endLine, silent) => {
|
|
26
19
|
const line = state.src.slice(state.bMarks[startLine] + state.tShift[startLine], state.eMarks[startLine]).trim();
|
|
27
20
|
const m = /^(:{3,})\s*([a-z-]+)(?:\s+(.*))?$/.exec(line);
|
|
@@ -29,7 +22,6 @@ function renderer(options) {
|
|
|
29
22
|
return false;
|
|
30
23
|
if (silent)
|
|
31
24
|
return true;
|
|
32
|
-
// The closing ::: is the first one outside fenced code (an example may show ::: itself).
|
|
33
25
|
let close = startLine + 1;
|
|
34
26
|
let fence = '';
|
|
35
27
|
for (; close < endLine; close++) {
|
|
@@ -58,7 +50,6 @@ function renderer(options) {
|
|
|
58
50
|
state.line = Math.min(close + 1, endLine);
|
|
59
51
|
return true;
|
|
60
52
|
});
|
|
61
|
-
// > [!NOTE] … becomes the same block as ::: info, titled with the alert's name.
|
|
62
53
|
md.core.ruler.after('block', 'cl_alerts', (state) => {
|
|
63
54
|
const t = state.tokens;
|
|
64
55
|
for (let i = 0; i < t.length - 2; i++) {
|
|
@@ -79,26 +70,85 @@ function renderer(options) {
|
|
|
79
70
|
}
|
|
80
71
|
}
|
|
81
72
|
Object.assign(t[i], { type: 'cl_container_open', tag: 'div', info: ALERTS[name], meta: { title: titles[name] } });
|
|
82
|
-
// The marker's own paragraph is gone if nothing else was on its line.
|
|
83
73
|
if (!t[i + 2].content.trim())
|
|
84
74
|
t.splice(i + 1, 3);
|
|
85
75
|
}
|
|
86
76
|
});
|
|
87
|
-
|
|
77
|
+
const plain = (src) => (md.parseInline(src, {})[0]?.children ?? []).filter((c) => c.type === 'text' || c.type === 'code_inline').map((c) => c.content).join('');
|
|
78
|
+
md.core.ruler.after('cl_alerts', 'cl_quiz', (state) => {
|
|
79
|
+
const t = state.tokens;
|
|
80
|
+
const env = state.env;
|
|
81
|
+
for (let i = 0; i < t.length; i++) {
|
|
82
|
+
if (t[i].type !== 'cl_container_open' || t[i].info !== 'quiz')
|
|
83
|
+
continue;
|
|
84
|
+
if (!env.quizAllowed)
|
|
85
|
+
throw new Error(`${env.file}: ::: quiz is for lessons (frontmatter steps: true); markdown({ quizzes: 'everywhere' }) allows it on any page`);
|
|
86
|
+
let close = i + 1;
|
|
87
|
+
for (let depth = 1; close < t.length; close++) {
|
|
88
|
+
if (t[close].type === 'cl_container_open')
|
|
89
|
+
depth++;
|
|
90
|
+
else if (t[close].type === 'cl_container_close' && --depth === 0)
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
const start = t.findIndex((tok, j) => j > i && j < close && tok.type === 'bullet_list_open');
|
|
94
|
+
if (start === -1)
|
|
95
|
+
throw new Error(`${env.file}: a quiz needs exactly one right answer (- [x]) in its list of options`);
|
|
96
|
+
let end = start;
|
|
97
|
+
for (let depth = 0; end < t.length; end++) {
|
|
98
|
+
if (t[end].type === 'bullet_list_open')
|
|
99
|
+
depth++;
|
|
100
|
+
else if (t[end].type === 'bullet_list_close' && --depth === 0)
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
const options = [];
|
|
104
|
+
let answer = -1;
|
|
105
|
+
let right = 0;
|
|
106
|
+
for (let j = start; j < end; j++) {
|
|
107
|
+
if (t[j].type !== 'inline' || t[j].level !== t[start].level + 3)
|
|
108
|
+
continue;
|
|
109
|
+
const m = /^\[([ xX])\]\s+/.exec(t[j].content);
|
|
110
|
+
if (m && m[1] !== ' ') {
|
|
111
|
+
answer = options.length;
|
|
112
|
+
right++;
|
|
113
|
+
}
|
|
114
|
+
options.push(plain(t[j].content.replace(/^\[[ xX]\]\s+/, '')));
|
|
115
|
+
}
|
|
116
|
+
if (right !== 1)
|
|
117
|
+
throw new Error(`${env.file}: a quiz needs exactly one right answer (- [x]) in its list of options`);
|
|
118
|
+
const question = t[i].meta.title;
|
|
119
|
+
t[i].meta = { title: plain(question), name: `quiz-${env.quizzes++}`, options, answer, html: md.renderInline(question) };
|
|
120
|
+
const token = new state.Token('cl_quiz', '', 0);
|
|
121
|
+
token.meta = t[i].meta;
|
|
122
|
+
t.splice(start, end - start + 1, token);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
88
125
|
md.renderer.rules.cl_container_open = (tokens, i, _o, env) => {
|
|
89
126
|
const tags = env.tags;
|
|
90
127
|
const { info: type, meta } = tokens[i];
|
|
91
128
|
const { title } = meta;
|
|
92
129
|
if (type === 'details')
|
|
93
130
|
return `<details class="custom-block details"><summary>${escapeHtml(title)}</summary>\n`;
|
|
131
|
+
if (type === 'quiz') {
|
|
132
|
+
const q = meta;
|
|
133
|
+
if (!options.quiz)
|
|
134
|
+
return `<div class="quiz" data-quiz="${q.name}">`;
|
|
135
|
+
tags.push(`<${options.quiz.tag} [name]="${quote(q.name)}" [question]="${escapeHtml(quote(title))}" [options]="[${q.options.map((o) => escapeHtml(quote(o))).join(', ')}]" [answer]="${q.answer}">`);
|
|
136
|
+
return `<!--cl-tag-${tags.length - 1}-->`;
|
|
137
|
+
}
|
|
94
138
|
if (options.container) {
|
|
95
139
|
tags.push(`<${options.container.tag} [type]="'${type}'">@slot('title') {${inert(title)}}`);
|
|
96
140
|
return `<!--cl-tag-${tags.length - 1}-->\n`;
|
|
97
141
|
}
|
|
98
142
|
return `<div class="custom-block ${type}"><p class="custom-block-title">${escapeHtml(title)}</p>\n`;
|
|
99
143
|
};
|
|
100
|
-
|
|
101
|
-
|
|
144
|
+
md.renderer.rules.cl_quiz = (tokens, i) => {
|
|
145
|
+
if (options.quiz)
|
|
146
|
+
return '';
|
|
147
|
+
const { name, html, options: choices, answer } = tokens[i].meta;
|
|
148
|
+
const labels = choices.map((text, n) => `<label><input type="radio" name="${name}" value="${n}"> ${escapeHtml(text)}</label>`).join('');
|
|
149
|
+
return `<p class="quiz-question" id="${name}-q">${html}</p><div class="quiz-options" role="radiogroup" aria-labelledby="${name}-q">${labels}</div>`
|
|
150
|
+
+ `<details class="quiz-answer"><summary>Show the answer</summary><p class="quiz-correct">Answer: ${escapeHtml(choices[answer])}</p>\n`;
|
|
151
|
+
};
|
|
102
152
|
md.renderer.rules.cl_group_open = (_t, _i, _o, env) => {
|
|
103
153
|
const e = env;
|
|
104
154
|
e.group = { id: e.groups++, n: 0 };
|
|
@@ -108,7 +158,6 @@ function renderer(options) {
|
|
|
108
158
|
delete env.group;
|
|
109
159
|
return '</div>\n';
|
|
110
160
|
};
|
|
111
|
-
// ```lang {1,3} [title] :line-numbers
|
|
112
161
|
md.renderer.rules.fence = (tokens, i, _o, env) => {
|
|
113
162
|
const e = env;
|
|
114
163
|
const info = tokens[i].info.trim();
|
|
@@ -140,13 +189,18 @@ function renderer(options) {
|
|
|
140
189
|
const tags = env.tags;
|
|
141
190
|
if (tokens[i].info === 'details')
|
|
142
191
|
return '</details>\n';
|
|
192
|
+
if (tokens[i].info === 'quiz') {
|
|
193
|
+
if (!options.quiz)
|
|
194
|
+
return '</details></div>\n';
|
|
195
|
+
tags.push(`</${options.quiz.tag}>`);
|
|
196
|
+
return `<!--cl-tag-${tags.length - 1}-->\n`;
|
|
197
|
+
}
|
|
143
198
|
if (options.container) {
|
|
144
199
|
tags.push(`</${options.container.tag}>`);
|
|
145
200
|
return `<!--cl-tag-${tags.length - 1}-->\n`;
|
|
146
201
|
}
|
|
147
202
|
return '</div>\n';
|
|
148
203
|
};
|
|
149
|
-
// [text](./other.md): relative links to page source files become their routes, so authors link by file.
|
|
150
204
|
md.core.ruler.push('cl_page_links', (state) => {
|
|
151
205
|
const { file, root } = state.env;
|
|
152
206
|
if (!file || !root)
|
|
@@ -161,13 +215,12 @@ function renderer(options) {
|
|
|
161
215
|
continue;
|
|
162
216
|
const target = resolve(dirname(file), m[1]);
|
|
163
217
|
if (!target.startsWith(pages))
|
|
164
|
-
continue;
|
|
218
|
+
continue;
|
|
165
219
|
const route = `/${relative(pages, target).split(sep).join('/').replace(/\.(md|tscl)$/i, '').replace(/(^|\/)index$/, '')}`;
|
|
166
220
|
token.attrSet('href', (route.length > 1 ? route.replace(/\/$/, '') : route) + (m[2] ?? ''));
|
|
167
221
|
}
|
|
168
222
|
}
|
|
169
223
|
});
|
|
170
|
-
// Headings get an id and an anchor link; ids are unique within the page.
|
|
171
224
|
md.core.ruler.push('cl_anchors', (state) => {
|
|
172
225
|
const used = new Set();
|
|
173
226
|
state.tokens.forEach((token, i) => {
|
|
@@ -182,7 +235,6 @@ function renderer(options) {
|
|
|
182
235
|
used.add(id);
|
|
183
236
|
token.attrSet('id', id);
|
|
184
237
|
token.attrSet('tabindex', '-1');
|
|
185
|
-
// The page title keeps its id, but no anchor link: it would only repeat the heading for screen readers.
|
|
186
238
|
if (token.tag === 'h1')
|
|
187
239
|
return;
|
|
188
240
|
const anchor = new state.Token('html_inline', '', 0);
|
|
@@ -192,17 +244,35 @@ function renderer(options) {
|
|
|
192
244
|
});
|
|
193
245
|
return md;
|
|
194
246
|
}
|
|
195
|
-
|
|
247
|
+
function pageHead(data, title) {
|
|
248
|
+
const tags = [];
|
|
249
|
+
if (data.titleTemplate === false && title !== undefined)
|
|
250
|
+
tags.push(`<title>${escapeHtml(title)}</title>`);
|
|
251
|
+
if (data.sitemap === false)
|
|
252
|
+
tags.push('<meta name="sitemap" content="false">');
|
|
253
|
+
if (typeof data.image === 'string')
|
|
254
|
+
tags.push(`<meta property="og:image" content="${escapeHtml(data.image)}">`);
|
|
255
|
+
const raws = [];
|
|
256
|
+
for (const entry of Array.isArray(data.head) ? data.head : []) {
|
|
257
|
+
const [tag, attrs = {}, content] = entry;
|
|
258
|
+
if (typeof tag !== 'string' || !/^[a-z]+$/.test(tag))
|
|
259
|
+
continue;
|
|
260
|
+
const a = staticHtml(Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escapeHtml(String(v))}"`)).join(''));
|
|
261
|
+
if (tag === 'script') {
|
|
262
|
+
const raw = content ?? '';
|
|
263
|
+
raws.push(attrs.type === 'application/ld+json' ? `<script${a}>${raw.replace(/\{\{/g, '{\\u007b')}</script>` : `<script inline${a}>${raw}</script>`);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
tags.push(['meta', 'link', 'base'].includes(tag) && content === undefined ? `<${tag}${a}>` : `<${tag}${a}>${escapeHtml(content ?? '')}</${tag}>`);
|
|
267
|
+
}
|
|
268
|
+
const ld = [data.jsonLd ?? []].flat().map((value) => `<script type="application/ld+json">${JSON.stringify(value)
|
|
269
|
+
.replace(/[<>&\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`).replace(/\{\{/g, '{\\u007b')}</script>`);
|
|
270
|
+
return tags.length || raws.length || ld.length ? `<cl-head>${staticHtml(tags.join(''))}${raws.join('')}${ld.join('')}</cl-head>` : '';
|
|
271
|
+
}
|
|
196
272
|
function staticHtml(html) {
|
|
197
273
|
return html.replace(/\{\{/g, '{{').replace(/@/g, '@');
|
|
198
274
|
}
|
|
199
|
-
/**
|
|
200
|
-
* Component tags (and any tag with [prop] or (event) bindings) aren't valid CommonMark HTML, so markdown-it would
|
|
201
|
-
* escape them. They are swapped for HTML comments, which it passes through, and put back after rendering.
|
|
202
|
-
*/
|
|
203
275
|
function protectTags(body, components, saved) {
|
|
204
|
-
// Code (fences, then inline spans) is matched first and kept as written: a tag in an example stays text.
|
|
205
|
-
// ponytail: indented code blocks aren't recognised; use a fence to show a component tag in code.
|
|
206
276
|
const code = /(?:^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n[ \t]*\1[`~]*[ \t\r]*(?=\n|$)|$)|(`+)[\s\S]*?[^`]\2(?!`)/;
|
|
207
277
|
const tag = /<\/?([A-Za-z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/;
|
|
208
278
|
const out = body.replace(new RegExp(`${code.source}|${tag.source}`, 'g'), (match, _fence, _ticks, name, attrs) => {
|
|
@@ -222,12 +292,9 @@ export default function markdown(options = {}) {
|
|
|
222
292
|
extension: '.md',
|
|
223
293
|
toTscl(code, file, context) {
|
|
224
294
|
const { route } = context;
|
|
225
|
-
// ---\nyaml\n---: the page's frontmatter.
|
|
226
295
|
const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(code);
|
|
227
296
|
const data = (front ? parseYaml(front[1]) : null) ?? {};
|
|
228
|
-
// Snippets and includes first: what they bring in is Markdown like the rest of the page.
|
|
229
297
|
let body = expand(front ? code.slice(front[0].length) : code, file, context);
|
|
230
|
-
// @import lines at the top pass through, so components can be used in the Markdown.
|
|
231
298
|
const imports = [];
|
|
232
299
|
for (;;) {
|
|
233
300
|
const line = /^[ \t]*(@import\b[^\n]*)\n|^[ \t]*\n/.exec(body);
|
|
@@ -237,31 +304,53 @@ export default function markdown(options = {}) {
|
|
|
237
304
|
imports.push(line[1].trim());
|
|
238
305
|
body = body.slice(line[0].length);
|
|
239
306
|
}
|
|
240
|
-
// Blocks rendered through a component need it imported.
|
|
241
307
|
if (options.container && !imports.some((line) => new RegExp(`^@import\\s+${options.container.tag}\\s+from`).test(line))) {
|
|
242
308
|
imports.unshift(`@import ${options.container.tag} from '${options.container.from}'`);
|
|
243
309
|
}
|
|
244
310
|
const components = new Set(imports.map((line) => /^@import\s+([A-Za-z_$][\w-]*)\s+from/.exec(line)?.[1]).filter((n) => !!n));
|
|
245
|
-
// cl-layout names the generated layout import (tag names must start with a letter, so not __cl_).
|
|
246
311
|
if (components.has('cl-layout'))
|
|
247
312
|
throw new Error(`${file}: cl-layout is reserved for the page's layout; import the component under another name`);
|
|
313
|
+
if (options.quiz && /^\s*:{3,}\s*quiz\b/m.test(body) && !imports.some((line) => new RegExp(`^@import\\s+${options.quiz.tag}\\s+from`).test(line))) {
|
|
314
|
+
imports.unshift(`@import ${options.quiz.tag} from '${options.quiz.from}'`);
|
|
315
|
+
}
|
|
248
316
|
if (options.copy && !imports.some((line) => new RegExp(`^@import\\s+${options.copy.tag}\\s+from`).test(line))) {
|
|
249
317
|
imports.unshift(`@import ${options.copy.tag} from '${options.copy.from}'`);
|
|
250
318
|
}
|
|
251
|
-
const env = { tags: [], groups: 0, file, root: context.root };
|
|
319
|
+
const env = { tags: [], groups: 0, file, root: context.root, quizzes: 0, quizAllowed: data.steps === true || options.quizzes === 'everywhere' };
|
|
252
320
|
const tags = protectTags(body, components, env.tags);
|
|
253
|
-
|
|
321
|
+
let tokens = md.parse(tags.body, env);
|
|
322
|
+
if (data.steps === true && tokens.length) {
|
|
323
|
+
const Token = tokens[0].constructor;
|
|
324
|
+
const html = (content) => Object.assign(new Token('html_block', '', 0), { content });
|
|
325
|
+
let open = false;
|
|
326
|
+
tokens = tokens.flatMap((t) => {
|
|
327
|
+
if (t.type !== 'heading_open' || t.tag !== 'h2' || t.level !== 0)
|
|
328
|
+
return [t];
|
|
329
|
+
const before = open ? [html('</section>\n')] : [];
|
|
330
|
+
open = true;
|
|
331
|
+
return [...before, html(`<section class="step" aria-labelledby="${escapeHtml(String(t.attrGet('id') ?? ''))}">\n`), t];
|
|
332
|
+
});
|
|
333
|
+
if (open)
|
|
334
|
+
tokens.push(html('</section>\n'));
|
|
335
|
+
}
|
|
336
|
+
const headings = tokens.flatMap((t, i) => {
|
|
337
|
+
if (t.type !== 'heading_open' || (t.tag !== 'h2' && t.tag !== 'h3') || t.level !== 0)
|
|
338
|
+
return [];
|
|
339
|
+
const text = (tokens[i + 1].children ?? []).filter((c) => c.type === 'text' || c.type === 'code_inline').map((c) => c.content).join('');
|
|
340
|
+
return [{ id: String(t.attrGet('id') ?? ''), text, level: t.tag === 'h2' ? 2 : 3 }];
|
|
341
|
+
});
|
|
254
342
|
const h1 = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
|
|
255
343
|
const firstHeading = h1 === -1 ? undefined : (tokens[h1 + 1].children ?? []).filter((t) => t.type === 'text' || t.type === 'code_inline').map((t) => t.content).join('');
|
|
256
|
-
const
|
|
344
|
+
const title = typeof data.title === 'string' ? data.title : firstHeading;
|
|
345
|
+
const html = pageHead(data, title) + tags.restore(staticHtml(md.renderer.render(tokens, md.options, env)));
|
|
257
346
|
const layout = data.layout === false ? undefined : (typeof data.layout === 'string' ? data.layout : options.layout);
|
|
258
347
|
if (!layout)
|
|
259
348
|
return [...imports, html].join('\n');
|
|
260
|
-
const title = typeof data.title === 'string' ? data.title : firstHeading;
|
|
261
349
|
const props = [
|
|
262
350
|
title !== undefined ? `[title]="${quote(title)}"` : '',
|
|
263
351
|
typeof data.description === 'string' ? `[description]="${quote(data.description)}"` : '',
|
|
264
352
|
`[path]="${quote(route)}"`,
|
|
353
|
+
headings.length ? `[headings]="[${headings.map((h) => `{ id: ${quote(h.id)}, text: ${quote(h.text)}, level: ${h.level} }`).join(', ')}]"` : '',
|
|
265
354
|
].filter(Boolean).join(' ');
|
|
266
355
|
return [`@import cl-layout from '${layout}'`, ...imports, `<cl-layout ${props}>${html}</cl-layout>`, ''].join('\n');
|
|
267
356
|
},
|
package/dist/snippets.js
CHANGED
|
@@ -1,16 +1,9 @@
|
|
|
1
|
-
// <<< code snippets and <!-- @include: --> Markdown includes, expanded before the Markdown is parsed. Lines inside
|
|
2
|
-
// code fences are left alone, so documentation can show the syntax itself.
|
|
3
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
4
2
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
5
3
|
const SNIPPET = /^[ \t]*<<<[ \t]+(\S+?)(?:#([\w-]+))?(\{[^}]*\})?(?:[ \t]+\[([^\]]+)\])?[ \t]*$/;
|
|
6
4
|
const INCLUDE = /^[ \t]*<!--[ \t]*@include:[ \t]*(\S+?)(?:#([\w-]+))?[ \t]*-->[ \t]*$/;
|
|
7
5
|
const posix = (p) => p.split(sep).join('/');
|
|
8
|
-
// A region marker is a comment line of its own: // #region name, /* #endregion */, <!-- #region name -->, # #region.
|
|
9
6
|
const MARKER = /^[ \t]*(?:\/\/|\/\*|<!--|#|--|;)?[ \t]*#(end)?region(?:[ \t]+([A-Za-z0-9_][\w-]*))?[ \t]*(?:\*\/|-->)?[ \t]*$/;
|
|
10
|
-
/**
|
|
11
|
-
* The lines between `#region name` and its `#endregion`, without markers, dedented. Regions nest: an inner region's
|
|
12
|
-
* unnamed `#endregion` closes the inner one, and the outer selection keeps everything up to its own ending.
|
|
13
|
-
*/
|
|
14
7
|
function region(text, name) {
|
|
15
8
|
let lines = text.replace(/\n$/, '').split('\n');
|
|
16
9
|
if (name) {
|
|
@@ -36,11 +29,6 @@ function region(text, name) {
|
|
|
36
29
|
const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^[ \t]*/.exec(l)[0].length));
|
|
37
30
|
return lines.map((l) => l.slice(Number.isFinite(indent) ? indent : 0)).join('\n');
|
|
38
31
|
}
|
|
39
|
-
/**
|
|
40
|
-
* Apply `fn` to every line outside fenced code, so examples stay as written. A fence may open after list markers;
|
|
41
|
-
* a closing fence uses the same character, is at least as long, has nothing after it, and is indented at most three
|
|
42
|
-
* spaces past where the fence opened (more is code).
|
|
43
|
-
*/
|
|
44
32
|
function outsideFences(text, fn) {
|
|
45
33
|
let fence = null;
|
|
46
34
|
return text.split('\n').map((line) => {
|
|
@@ -58,7 +46,6 @@ function outsideFences(text, fn) {
|
|
|
58
46
|
return fn(line);
|
|
59
47
|
}).join('\n');
|
|
60
48
|
}
|
|
61
|
-
/** Expand snippets and includes in `text` (from `file`; `stack` is the include chain, page first). */
|
|
62
49
|
export function expand(text, file, ctx, stack = [file]) {
|
|
63
50
|
if (!/<<<|@include:/.test(text))
|
|
64
51
|
return text;
|
|
@@ -91,8 +78,6 @@ export function expand(text, file, ctx, stack = [file]) {
|
|
|
91
78
|
fail(`include cycle: ${[...stack, path].map((p) => posix(relative(ctx.root, p))).join(' → ')}`);
|
|
92
79
|
let included = readFileSync(path, 'utf8').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
|
|
93
80
|
included = region(included, name) ?? fail(`@include: ${spec}: region "${name}" not found`);
|
|
94
|
-
// Relative links (inline and reference definitions) in the included file are rewritten to work from the page
|
|
95
|
-
// that includes it; examples in fences stay as written.
|
|
96
81
|
const rebase = (href) => (/^([a-z][\w+.-]*:|\/|#)/i.test(href) ? href : posix(relative(dirname(stack[0]), resolve(dirname(path), href))));
|
|
97
82
|
included = outsideFences(included, (l) => l
|
|
98
83
|
.replace(/(\]\()([^)\s]+)/g, (_, open, href) => open + rebase(href))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarusjs/content",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Markdown pages for clarusjs: frontmatter, layouts, components in Markdown, rendered to static HTML at build time.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"access": "public"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
|
-
"clarusjs": "^0.
|
|
22
|
+
"clarusjs": "^0.8.0"
|
|
23
23
|
},
|
|
24
24
|
"engines": {
|
|
25
25
|
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
|
@@ -50,13 +50,13 @@
|
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/markdown-it": "^14.2.0",
|
|
52
52
|
"@types/node": "^26.6.6",
|
|
53
|
-
"clarusjs": "^0.
|
|
53
|
+
"clarusjs": "^0.8.0",
|
|
54
54
|
"typescript": "^7.0.2",
|
|
55
55
|
"vite": "^8.3.8",
|
|
56
56
|
"vitest": "^5.1.1"
|
|
57
57
|
},
|
|
58
58
|
"scripts": {
|
|
59
|
-
"build": "node -
|
|
59
|
+
"build": "node ../../scripts/build-package.mjs",
|
|
60
60
|
"test": "vitest run",
|
|
61
61
|
"typecheck": "tsc --noEmit"
|
|
62
62
|
}
|