@clarusjs/content 0.6.1 → 0.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.
@@ -1,2 +1,8 @@
1
- /** Highlighted <pre> for `code` in `lang` (unknown languages are plain text); `meta` carries `{1,3-5}`. */
1
+ import { type LanguageRegistration } from 'shiki/core';
2
+ /**
3
+ * More languages: names of Shiki's grammars (`'rust'`, `'go'`), loaded from this package's own Shiki, or grammars
4
+ * of your own. A language already loaded is left as is.
5
+ */
6
+ export declare function addLanguages(langs: (string | LanguageRegistration | LanguageRegistration[])[]): void;
7
+ /** Highlighted <pre> for `code` in `lang` (any language Shiki has, loaded on first use; others are plain text); `meta` carries `{1,3-5}`. */
2
8
  export declare function highlight(code: string, lang: string, meta: string): string;
package/dist/highlight.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { createHighlighterCoreSync } from 'shiki/core';
2
3
  import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
4
+ import { bundledLanguagesInfo } from 'shiki/langs';
3
5
  import { transformerMetaHighlight, transformerNotationDiff, transformerNotationErrorLevel, transformerNotationFocus, transformerNotationHighlight, } from '@shikijs/transformers';
4
6
  import angularHtml from 'shiki/langs/angular-html.mjs';
5
7
  import bash from 'shiki/langs/bash.mjs';
@@ -13,6 +15,7 @@ import toml from 'shiki/langs/toml.mjs';
13
15
  import tsx from 'shiki/langs/tsx.mjs';
14
16
  import typescript from 'shiki/langs/typescript.mjs';
15
17
  import yaml from 'shiki/langs/yaml.mjs';
18
+ import zig from 'shiki/langs/zig.mjs';
16
19
  import githubDark from 'shiki/themes/github-dark-default.mjs';
17
20
  import githubLight from 'shiki/themes/github-light-default.mjs';
18
21
  const ALIASES = { tscl: 'angular-html', ts: 'typescript', js: 'javascript', sh: 'bash', shell: 'bash', zsh: 'bash', md: 'markdown', yml: 'yaml' };
@@ -20,9 +23,45 @@ const light = JSON.parse(JSON.stringify(githubLight).replace(/#6e7781/gi, '#5963
20
23
  let highlighter;
21
24
  const get = () => (highlighter ??= createHighlighterCoreSync({
22
25
  themes: [light, githubDark],
23
- langs: [angularHtml, bash, css, diff, html, javascript, json, markdown, toml, tsx, typescript, yaml],
26
+ langs: [angularHtml, bash, css, diff, html, javascript, json, markdown, toml, tsx, typescript, yaml, zig],
24
27
  engine: createJavaScriptRegexEngine(),
25
28
  }));
29
+ const load = createRequire(import.meta.url);
30
+ function grammar(name) {
31
+ const fail = () => { throw new Error(`@clarusjs/content: Shiki has no grammar "${name}"`); };
32
+ if (!/^[a-z0-9][a-z0-9+#.-]*$/i.test(name) || name.includes('..'))
33
+ fail();
34
+ try {
35
+ return load(`shiki/langs/${name}.mjs`).default;
36
+ }
37
+ catch {
38
+ return fail();
39
+ }
40
+ }
41
+ export function addLanguages(langs) {
42
+ const hl = get();
43
+ const loaded = new Set(hl.getLoadedLanguages());
44
+ const add = langs.flatMap((l) => (typeof l === 'string' ? (loaded.has(l) ? [] : grammar(l)) : l)).filter((l) => !loaded.has(l.name));
45
+ if (add.length)
46
+ hl.loadLanguageSync(add);
47
+ }
48
+ const SHIKI = new Map(bundledLanguagesInfo.flatMap((l) => [l.id, ...(l.aliases ?? [])].map((name) => [name, l.id])));
49
+ const unavailable = new Set();
50
+ function language(hl, id) {
51
+ if (hl.getLoadedLanguages().includes(id))
52
+ return id;
53
+ const shiki = SHIKI.get(id.toLowerCase());
54
+ if (!shiki || unavailable.has(shiki))
55
+ return undefined;
56
+ try {
57
+ addLanguages([shiki]);
58
+ return shiki;
59
+ }
60
+ catch {
61
+ unavailable.add(shiki);
62
+ return undefined;
63
+ }
64
+ }
26
65
  const transformers = [
27
66
  transformerNotationDiff(),
28
67
  transformerNotationFocus(),
@@ -32,10 +71,8 @@ const transformers = [
32
71
  ];
33
72
  export function highlight(code, lang, meta) {
34
73
  const hl = get();
35
- const id = ALIASES[lang] ?? lang;
36
- const known = hl.getLoadedLanguages().includes(id);
37
74
  return hl.codeToHtml(code, {
38
- lang: known ? id : 'text',
75
+ lang: language(hl, Object.hasOwn(ALIASES, lang) ? ALIASES[lang] : lang) ?? 'text',
39
76
  themes: { light: 'github-light-default', dark: 'github-dark-default' },
40
77
  defaultColor: false,
41
78
  meta: { __raw: meta },
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { LanguageRegistration } from 'shiki/core';
1
2
  import type { Source } from 'clarusjs/vite';
2
3
  /**
3
4
  * `markdown()`'s options: the layout, components for blocks, code copy and quizzes, and frontmatter schemas.
@@ -24,6 +25,26 @@ export type MarkdownOptions = {
24
25
  tag: string;
25
26
  from: string;
26
27
  };
28
+ /**
29
+ * Render ```mermaid blocks as diagrams: each becomes its source in `<pre class="mermaid">` (not highlighted) with your
30
+ * diagram component after it, `<tag attach="visible" />`, which draws it in the browser. theme-docs ships one:
31
+ * `{ tag: 'diagram', from: '@clarusjs/theme-docs/mermaid.tscl' }` (install `mermaid` beside it). Without this option
32
+ * a ```mermaid block is code, as any other.
33
+ */
34
+ mermaid?: {
35
+ tag: string;
36
+ from: string;
37
+ };
38
+ /**
39
+ * Synced tabs: `::: code-group sdk` names a group, and groups with the same name switch together (tabs matched by
40
+ * their label). Your component goes in each named group, `<tag />`, and does the syncing in the browser; theme-docs
41
+ * ships one: `{ tag: 'codeTabs', from: '@clarusjs/theme-docs/code-tabs.tscl' }`. Without JavaScript, or without this
42
+ * option, each group works on its own.
43
+ */
44
+ codeGroups?: {
45
+ tag: string;
46
+ from: string;
47
+ };
27
48
  /**
28
49
  * Render `::: quiz` blocks through your quiz component (an island): `<tag [name] [question] [options] [answer]>`
29
50
  * with the explanation as its content. Without it they are static HTML that works without JavaScript.
@@ -39,6 +60,14 @@ export type MarkdownOptions = {
39
60
  * @see https://clarusjs.com/guide/markdown#code
40
61
  */
41
62
  lineNumbers?: boolean;
63
+ /**
64
+ * Every language Shiki has is highlighted already, loaded the first time a page uses it (by name or alias:
65
+ * ```` ```rust ````, ```` ```py ````), from this package's own Shiki (nothing to install). Add grammars of your own
66
+ * here, or names of Shiki's (`markdown({ langs: ['rust'] })`) to load them up front, where a typo is a build error.
67
+ * A language Shiki doesn't have is plain text.
68
+ * @see https://clarusjs.com/guide/markdown#code
69
+ */
70
+ langs?: (string | LanguageRegistration | LanguageRegistration[])[];
42
71
  /** `::: quiz` is for lessons (frontmatter `steps: true`); 'everywhere' allows it on any page. */
43
72
  quizzes?: 'lessons' | 'everywhere';
44
73
  /**
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { existsSync } from 'node:fs';
2
2
  import { dirname, relative, resolve, sep } from 'node:path';
3
3
  import MarkdownIt from 'markdown-it';
4
4
  import { parse as parseYaml } from 'yaml';
5
- import { highlight } from './highlight.js';
5
+ import { addLanguages, highlight } from './highlight.js';
6
6
  import { expand } from './snippets.js';
7
7
  const SHELL = new Set(['sh', 'bash', 'shell', 'zsh', 'console', 'powershell', 'ps1']);
8
8
  function globToRegex(glob) {
@@ -71,7 +71,7 @@ function renderer(options) {
71
71
  }
72
72
  const open = state.push(m[2] === 'code-group' ? 'cl_group_open' : 'cl_container_open', 'div', 1);
73
73
  open.info = m[2];
74
- open.meta = { title: m[3]?.trim() || titles[m[2]] };
74
+ open.meta = { title: m[3]?.trim() || titles[m[2]], name: m[3]?.trim() || undefined };
75
75
  const oldMax = state.lineMax;
76
76
  state.lineMax = close;
77
77
  state.md.block.tokenize(state, startLine + 1, close);
@@ -179,14 +179,21 @@ function renderer(options) {
179
179
  return `<p class="quiz-question" id="${name}-q">${html}</p><div class="quiz-options" role="radiogroup" aria-labelledby="${name}-q">${labels}</div>`
180
180
  + `<details class="quiz-answer"><summary>Show the answer</summary><p class="quiz-correct">Answer: ${escapeHtml(choices[answer])}</p>\n`;
181
181
  };
182
- md.renderer.rules.cl_group_open = (_t, _i, _o, env) => {
182
+ md.renderer.rules.cl_group_open = (tokens, i, _o, env) => {
183
183
  const e = env;
184
- e.group = { id: e.groups++, n: 0 };
185
- return '<div class="code-group">';
184
+ const sync = tokens[i].meta.name;
185
+ e.group = { id: e.groups++, n: 0, ...(sync ? { sync } : {}) };
186
+ return `<div class="code-group"${sync ? ` data-sync="${inert(sync)}"` : ''}>`;
186
187
  };
187
188
  md.renderer.rules.cl_group_close = (_t, _i, _o, env) => {
188
- delete env.group;
189
- return '</div>\n';
189
+ const e = env;
190
+ let out = '';
191
+ if (e.group?.sync && options.codeGroups) {
192
+ e.tags.push(`<${options.codeGroups.tag} />`);
193
+ out = `<!--cl-tag-${e.tags.length - 1}-->`;
194
+ }
195
+ delete e.group;
196
+ return out + '</div>\n';
190
197
  };
191
198
  md.renderer.rules.table_open = (tokens, i, options, _env, self) => {
192
199
  tokens[i].attrSet('tabindex', '0');
@@ -196,6 +203,10 @@ function renderer(options) {
196
203
  const e = env;
197
204
  const info = tokens[i].info.trim();
198
205
  const lang = /^[^\s{[:]+/.exec(info)?.[0] ?? 'text';
206
+ if (options.mermaid && lang === 'mermaid' && !e.group) {
207
+ e.tags.push(`<${options.mermaid.tag} attach="visible" />`);
208
+ return `<div class="mermaid-diagram"><pre class="mermaid" tabindex="0">${inert(tokens[i].content.replace(/\n$/, ''))}</pre><!--cl-tag-${e.tags.length - 1}--></div>\n`;
209
+ }
199
210
  const title = /\[([^\]]+)\]/.exec(info)?.[1];
200
211
  const code = tokens[i].content;
201
212
  const command = SHELL.has(lang.toLowerCase()) && !title && !code.startsWith('#!');
@@ -387,6 +398,8 @@ function protectTags(body, components, saved) {
387
398
  return { body: out, restore: (html) => html.replace(/<!--cl-tag-(\d+)-->/g, (_, i) => saved[Number(i)]) };
388
399
  }
389
400
  export default function markdown(options = {}) {
401
+ if (options.langs?.length)
402
+ addLanguages(options.langs);
390
403
  const md = renderer(options);
391
404
  return {
392
405
  extension: '.md',
@@ -417,6 +430,12 @@ export default function markdown(options = {}) {
417
430
  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))) {
418
431
  imports.unshift(`@import ${options.quiz.tag} from '${options.quiz.from}'`);
419
432
  }
433
+ if (options.codeGroups && /^\s*:{3,}\s*code-group[^\S\n]+\S/m.test(body) && !imports.some((line) => new RegExp(`^@import\\s+${options.codeGroups.tag}\\s+from`).test(line))) {
434
+ imports.unshift(`@import ${options.codeGroups.tag} from '${options.codeGroups.from}'`);
435
+ }
436
+ if (options.mermaid && /^\s*(`{3,}|~{3,})\s*mermaid\b/m.test(body) && !imports.some((line) => new RegExp(`^@import\\s+${options.mermaid.tag}\\s+from`).test(line))) {
437
+ imports.unshift(`@import ${options.mermaid.tag} from '${options.mermaid.from}'`);
438
+ }
420
439
  if (options.copy && !imports.some((line) => new RegExp(`^@import\\s+${options.copy.tag}\\s+from`).test(line))) {
421
440
  imports.unshift(`@import ${options.copy.tag} from '${options.copy.from}'`);
422
441
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clarusjs/content",
3
- "version": "0.6.1",
3
+ "version": "0.8.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.18.0"
22
+ "clarusjs": "^0.19.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.18.0",
53
+ "clarusjs": "^0.19.0",
54
54
  "typescript": "^7.0.2",
55
55
  "vite": "^8.3.8",
56
56
  "vitest": "^5.1.1"