@clarusjs/content 0.2.2 → 0.3.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/index.d.ts +39 -3
- package/dist/index.js +27 -2
- package/dist/templates.d.ts +22 -0
- package/dist/templates.js +47 -0
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { Source } from 'clarusjs/vite';
|
|
2
|
+
/**
|
|
3
|
+
* `markdown()`'s options: the layout, components for blocks, code copy and quizzes, and frontmatter schemas.
|
|
4
|
+
* @see https://clarusjs.com/reference/content#markdown
|
|
5
|
+
*/
|
|
2
6
|
export type MarkdownOptions = {
|
|
3
7
|
/** The layout every page renders in, root-relative (`/src/layouts/docs.tscl`). Frontmatter `layout` overrides it; `false` means none. */
|
|
4
8
|
layout?: string | false;
|
|
@@ -34,9 +38,18 @@ export type MarkdownOptions = {
|
|
|
34
38
|
* Synchronous schemas only.
|
|
35
39
|
* @see https://clarusjs.com/guide/markdown#frontmatter-schemas
|
|
36
40
|
*/
|
|
41
|
+
/**
|
|
42
|
+
* Folders of components a page can use by tag without importing them: `'/src/components'` (root-relative), or
|
|
43
|
+
* several, searched in order. `<counter />` imports counter.tscl, `<todoSummary />` todo-summary.tscl. An explicit
|
|
44
|
+
* `@import` wins; an unknown camelCase tag is an error; tags in code stay text.
|
|
45
|
+
*/
|
|
46
|
+
components?: string | string[];
|
|
37
47
|
schema?: StandardSchema | Record<string, StandardSchema>;
|
|
38
48
|
};
|
|
39
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* The Standard Schema interface (https://standardschema.dev), as much of it as validating frontmatter needs.
|
|
51
|
+
* @see https://clarusjs.com/reference/content#markdown
|
|
52
|
+
*/
|
|
40
53
|
export type StandardSchema<Output = unknown> = {
|
|
41
54
|
readonly '~standard': {
|
|
42
55
|
readonly version: 1;
|
|
@@ -55,7 +68,30 @@ type StandardResult<Output> = {
|
|
|
55
68
|
}>;
|
|
56
69
|
}>;
|
|
57
70
|
};
|
|
58
|
-
|
|
71
|
+
export { highlightTemplates } from './templates.ts';
|
|
72
|
+
/**
|
|
73
|
+
* 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking.
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* slugify('Getting started!') // 'getting-started'
|
|
77
|
+
* ```
|
|
78
|
+
* @see https://clarusjs.com/reference/content#slugify
|
|
79
|
+
*/
|
|
59
80
|
export declare function slugify(text: string): string;
|
|
81
|
+
/**
|
|
82
|
+
* Markdown pages as a page source: `src/pages/**\/*.md` become pages, rendered in your layout, with frontmatter, headings
|
|
83
|
+
* with anchors, highlighted code, `::: tip` blocks, components imported at the top, and (in lessons) quizzes.
|
|
84
|
+
* Build-time only: nothing of it reaches the browser.
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* // vite.config.ts
|
|
88
|
+
* import clarusjs from 'clarusjs/vite'
|
|
89
|
+
* import markdown from '@clarusjs/content'
|
|
90
|
+
*
|
|
91
|
+
* export default defineConfig({
|
|
92
|
+
* plugins: [clarusjs({ sources: [markdown({ layout: '/src/layouts/docs.tscl' })] })],
|
|
93
|
+
* })
|
|
94
|
+
* ```
|
|
95
|
+
* @see https://clarusjs.com/reference/content#markdown
|
|
96
|
+
*/
|
|
60
97
|
export default function markdown(options?: MarkdownOptions): Source;
|
|
61
|
-
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
1
2
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
2
3
|
import MarkdownIt from 'markdown-it';
|
|
3
4
|
import { parse as parseYaml } from 'yaml';
|
|
@@ -34,6 +35,7 @@ const TYPES = ['tip', 'info', 'warning', 'danger', 'details', 'code-group', 'qui
|
|
|
34
35
|
const TITLES = { tip: 'Tip', info: 'Info', warning: 'Warning', danger: 'Danger', details: 'Details', note: 'Note', important: 'Important', caution: 'Caution' };
|
|
35
36
|
const ALERTS = { note: 'info', tip: 'tip', important: 'info', warning: 'warning', caution: 'danger' };
|
|
36
37
|
const inert = (s) => escapeHtml(s).replace(/\{/g, '{').replace(/\}/g, '}').replace(/@/g, '@');
|
|
38
|
+
export { highlightTemplates } from './templates.js';
|
|
37
39
|
export function slugify(text) {
|
|
38
40
|
return text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\w\s-]/g, '').trim().replace(/[\s_-]+/g, '-') || 'section';
|
|
39
41
|
}
|
|
@@ -159,7 +161,7 @@ function renderer(options) {
|
|
|
159
161
|
const q = meta;
|
|
160
162
|
if (!options.quiz)
|
|
161
163
|
return `<div class="quiz" data-quiz="${q.name}">`;
|
|
162
|
-
tags.push(`<${options.quiz.tag} [name]="${quote(q.name)}" [question]="${
|
|
164
|
+
tags.push(`<${options.quiz.tag} [name]="${quote(q.name)}" [question]="${quote(title)}" [options]="[${q.options.map(quote).join(', ')}]" [answer]="${q.answer}">`);
|
|
163
165
|
return `<!--cl-tag-${tags.length - 1}-->`;
|
|
164
166
|
}
|
|
165
167
|
if (options.container) {
|
|
@@ -313,8 +315,27 @@ function staticHtml(html) {
|
|
|
313
315
|
}
|
|
314
316
|
return out + inertText(html.slice(at));
|
|
315
317
|
}
|
|
318
|
+
const CODE = /(?:^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n[ \t]*\1[`~]*[ \t\r]*(?=\n|$)|$)|(`+)[\s\S]*?[^`]\2(?!`)/;
|
|
319
|
+
const HTML_TAGS = new Set('a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul var video wbr svg math'.split(' '));
|
|
320
|
+
function autoImports(body, dirs, root, file, imported) {
|
|
321
|
+
const out = [];
|
|
322
|
+
const seen = new Set(imported);
|
|
323
|
+
const text = body.replace(new RegExp(CODE.source, 'g'), '');
|
|
324
|
+
for (const [, name] of text.matchAll(/<([A-Za-z][\w-]*)/g)) {
|
|
325
|
+
if (seen.has(name) || HTML_TAGS.has(name))
|
|
326
|
+
continue;
|
|
327
|
+
seen.add(name);
|
|
328
|
+
const kebab = name.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());
|
|
329
|
+
const found = dirs.flatMap((dir) => [name, kebab].map((f) => `${dir.replace(/\/$/, '')}/${f}.tscl`)).find((f) => existsSync(resolve(root, '.' + f)));
|
|
330
|
+
if (found)
|
|
331
|
+
out.push(`@import ${name} from '${found}'`);
|
|
332
|
+
else if (/[A-Z]/.test(name))
|
|
333
|
+
throw new Error(`${file}: <${name}> is not a component in ${dirs.join(', ')} (check the name, or @import it)`);
|
|
334
|
+
}
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
316
337
|
function protectTags(body, components, saved) {
|
|
317
|
-
const code =
|
|
338
|
+
const code = CODE;
|
|
318
339
|
const tag = /<\/?([A-Za-z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/;
|
|
319
340
|
const out = body.replace(new RegExp(`${code.source}|${tag.source}`, 'g'), (match, _fence, _ticks, name, attrs) => {
|
|
320
341
|
if (name === undefined)
|
|
@@ -345,6 +366,10 @@ export default function markdown(options = {}) {
|
|
|
345
366
|
imports.push(line[1].trim());
|
|
346
367
|
body = body.slice(line[0].length);
|
|
347
368
|
}
|
|
369
|
+
if (options.components) {
|
|
370
|
+
const explicit = new Set(imports.map((line) => /^@import\s+([A-Za-z_$][\w-]*)\s+from/.exec(line)?.[1]).filter((n) => !!n));
|
|
371
|
+
imports.push(...autoImports(body, [options.components].flat(), context.root, file, explicit));
|
|
372
|
+
}
|
|
348
373
|
if (options.container && !imports.some((line) => new RegExp(`^@import\\s+${options.container.tag}\\s+from`).test(line))) {
|
|
349
374
|
imports.unshift(`@import ${options.container.tag} from '${options.container.from}'`);
|
|
350
375
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
/**
|
|
3
|
+
* `source` with its static code blocks highlighted: `<pre verbatim lang="x">…</pre>` (the content is the code), and
|
|
4
|
+
* `<pre><code lang="x">…</code></pre>` (`verbatim` on the code: as written; without it, template text with entities
|
|
5
|
+
* decoded). A block with `{{ }}` holes, or without a `lang`, is left as written; `warn` hears about holes.
|
|
6
|
+
*/
|
|
7
|
+
export declare function highlightBlocks(source: string, warn?: (message: string) => void): string;
|
|
8
|
+
/**
|
|
9
|
+
* Highlights code blocks in .tscl templates at build, with the same Shiki setup as Markdown pages. Add it before
|
|
10
|
+
* clarusjs: `plugins: [highlightTemplates(), clarusjs(...)]`. Mark a block with its language:
|
|
11
|
+
* `<pre><code verbatim lang="ts">…</code></pre>`.
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* // vite.config.ts
|
|
15
|
+
* import clarusjs from 'clarusjs/vite'
|
|
16
|
+
* import markdown, { highlightTemplates } from '@clarusjs/content'
|
|
17
|
+
*
|
|
18
|
+
* export default defineConfig({ plugins: [highlightTemplates(), clarusjs({ sources: [markdown()] })] })
|
|
19
|
+
* ```
|
|
20
|
+
* @see https://clarusjs.com/guide/markdown#code-in-templates
|
|
21
|
+
*/
|
|
22
|
+
export declare function highlightTemplates(): Plugin;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { highlight } from './highlight.js';
|
|
2
|
+
const escapeHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
3
|
+
const decode = (s) => s.replace(/&(lt|gt|quot|#39|#0*64|#0*123|#0*125|amp);/g, (_, e) => ({ lt: '<', gt: '>', quot: '"', '#39': "'", amp: '&' }[e] ?? String.fromCharCode(Number(e.slice(1)))));
|
|
4
|
+
const inert = (html) => html.replace(/\{/g, '{').replace(/\}/g, '}').replace(/@/g, '@');
|
|
5
|
+
const attr = (attrs, name) => new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`).exec(attrs)?.slice(1).find((v) => v !== undefined);
|
|
6
|
+
const flag = (attrs, name) => new RegExp(`(?:^|\\s)${name}(?=[\\s/>=]|$)`).test(attrs.replace(/=\s*("[^"]*"|'[^']*'|[^\s>]*)/g, ''));
|
|
7
|
+
const block = (code, lang) => inert(`<div class="code-block language-${escapeHtml(lang)}"><span class="lang">${escapeHtml(lang)}</span>${highlight(code.replace(/^\n/, '').replace(/\n$/, ''), lang, '')}</div>`);
|
|
8
|
+
export function highlightBlocks(source, warn = () => { }) {
|
|
9
|
+
return source.replace(/<pre\b([^>]*)>([\s\S]*?)<\/pre\s*>/g, (whole, preAttrs, inner, at) => {
|
|
10
|
+
const line = source.slice(0, at).split('\n').length;
|
|
11
|
+
let lang = attr(preAttrs, 'lang');
|
|
12
|
+
let code;
|
|
13
|
+
if (lang && flag(preAttrs, 'verbatim'))
|
|
14
|
+
code = inner;
|
|
15
|
+
else {
|
|
16
|
+
const m = /^\s*<code\b([^>]*)>([\s\S]*)<\/code\s*>\s*$/.exec(inner);
|
|
17
|
+
if (!m)
|
|
18
|
+
return whole;
|
|
19
|
+
lang = attr(m[1], 'lang');
|
|
20
|
+
if (!lang)
|
|
21
|
+
return whole;
|
|
22
|
+
if (flag(m[1], 'verbatim'))
|
|
23
|
+
code = m[2];
|
|
24
|
+
else {
|
|
25
|
+
if (m[2].includes('{{')) {
|
|
26
|
+
warn(`line ${line}: a code block with {{ }} holes isn't static, so it's left as written (not highlighted)`);
|
|
27
|
+
return whole;
|
|
28
|
+
}
|
|
29
|
+
code = decode(m[2]);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return block(code, lang);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
export function highlightTemplates() {
|
|
36
|
+
return {
|
|
37
|
+
name: 'clarusjs-content:highlight-templates',
|
|
38
|
+
enforce: 'pre',
|
|
39
|
+
transform: {
|
|
40
|
+
filter: { id: /\.tscl(\?.*)?$/ },
|
|
41
|
+
handler(code, id) {
|
|
42
|
+
const out = highlightBlocks(code, (message) => this.warn(`${id.replace(/\?.*$/, '')}: ${message}`));
|
|
43
|
+
return out === code ? null : { code: out, map: null };
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarusjs/content",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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.11.0"
|
|
23
23
|
},
|
|
24
24
|
"engines": {
|
|
25
25
|
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/markdown-it": "^14.2.0",
|
|
52
52
|
"@types/node": "^26.6.6",
|
|
53
|
-
"clarusjs": "^0.
|
|
53
|
+
"clarusjs": "^0.11.0",
|
|
54
54
|
"typescript": "^7.0.2",
|
|
55
55
|
"vite": "^8.3.8",
|
|
56
56
|
"vitest": "^5.1.1"
|