yuhwa 1.3.0 → 1.4.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.
Files changed (57) hide show
  1. package/README.md +5 -3
  2. package/dist/astro.d.ts +1 -1
  3. package/dist/astro.js +4 -3
  4. package/dist/browser.d.ts +10 -4
  5. package/dist/browser.js +85 -22
  6. package/dist/canvas.d.ts +2 -0
  7. package/dist/canvas.js +40 -0
  8. package/dist/cli.js +485 -236
  9. package/dist/editor/assets/index-DWm3xV_v.js +689 -0
  10. package/dist/editor/assets/{lsp.worker-CMSpDTsX.js → lsp.worker-N6A9m364.js} +23 -17
  11. package/dist/editor/index.html +4 -1
  12. package/dist/{figure-QAwSU1Ry.d.ts → figure-BLHfxz_e.d.ts} +28 -5
  13. package/dist/{index-6ZPJGThY.d.ts → index-xVW43gqW.d.ts} +48 -3
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +5 -3
  16. package/dist/ironmark.d.ts +1 -1
  17. package/dist/ironmark.js +1 -1
  18. package/dist/lsp-browser.d.ts +2 -2
  19. package/dist/lsp-browser.js +2 -1
  20. package/dist/lsp-node.js +46 -26
  21. package/dist/lsp-server.d.ts +5 -1
  22. package/dist/lsp-server.js +1 -1
  23. package/dist/lsp.d.ts +1 -1
  24. package/dist/lsp.js +1 -1
  25. package/dist/markdown-it.d.ts +1 -1
  26. package/dist/markdown-it.js +5 -3
  27. package/dist/{node-CLu2Pp_2.js → node-CkrQnPFb.js} +90 -13
  28. package/dist/{plugin-Bs4eiAuz.js → parse--ljBMU60.js} +25 -307
  29. package/dist/plugin-CitzbblK.js +301 -0
  30. package/dist/{plugin-NSkNyoUj.d.ts → plugin-NMP_uf1a.d.ts} +15 -1
  31. package/dist/plugin.d.ts +1 -1
  32. package/dist/plugin.js +3 -1
  33. package/dist/raster-iqi6XRPU.js +299 -0
  34. package/dist/remark.d.ts +1 -1
  35. package/dist/remark.js +1 -1
  36. package/dist/rolldown-runtime-CEjnN5Q1.js +37 -0
  37. package/dist/{server-D6BSNC1P.js → server-BTYtmr6B.js} +41 -63
  38. package/dist/{server--jHjJjOS.d.ts → server-DMAOtqqK.d.ts} +1 -1
  39. package/dist/{service-D7DNWBAU.js → service-C60VdeKS.js} +34 -3
  40. package/dist/{service-Brvpt7Do.d.ts → service-DimTFsE3.d.ts} +2 -0
  41. package/dist/{shared-6aCU_HaV.js → shared-h8tkFLY4.js} +231 -21
  42. package/dist/{src-BjOhvTAB.js → src-NCXCTK_4.js} +81 -45
  43. package/dist/svg-uri-Dx8SGV-n.js +7 -0
  44. package/dist/vite.d.ts +1 -1
  45. package/dist/vite.js +3 -3
  46. package/dist/vuepress.d.ts +3 -2
  47. package/dist/vuepress.js +4 -2
  48. package/dist/watch-2VeW5DUN.js +35 -0
  49. package/dist/yuhwa.iife.js +55 -54
  50. package/dist/zoom-script-CaJ5MNUw.js +29 -0
  51. package/dist/{zoom-QeqB6QlH.js → zoom-yxhxX16c.js} +1 -1
  52. package/dist/zoom.d.ts +16 -7
  53. package/dist/zoom.js +2 -2
  54. package/package.json +19 -2
  55. package/skills/yuhwa/SKILL.md +12 -0
  56. package/dist/editor/assets/index-DAk6b1UB.js +0 -689
  57. package/dist/zoom-script-CVdAzMhX.js +0 -51
package/README.md CHANGED
@@ -140,9 +140,10 @@ pnpm dlx yuhwa render hello.yu -o hello.svg # pnpm
140
140
  ```bash
141
141
  npx yuhwa edit hello.yu # visual editor, saves back to the file
142
142
  npx yuhwa check hello.yu # diagnostics, exit 1 on errors
143
+ # pnpm: pnpm dlx yuhwa edit hello.yu, pnpm dlx yuhwa check hello.yu
143
144
  ```
144
145
 
145
- **4. Keep it around.** Install globally to drop the `npx`, or add it to a
146
+ **4. Keep it around.** Install globally to drop the `npx` or `pnpm dlx`, or add it to a
146
147
  project:
147
148
 
148
149
  ```bash
@@ -208,8 +209,8 @@ const { svg, diagnostics } = render('a -> b -> c', { theme: 'midnight' });
208
209
 
209
210
  `render()` never throws. Problems come back as `diagnostics` with line, message and severity.
210
211
 
211
- **In Markdown on GitHub or GitLab**: `npx yuhwa md README.md` renders every
212
- ` ```yuhwa ` block to an SVG file and links it in ([details](https://ph1p.github.io/yuhwa/guide/markdown)).
212
+ **In Markdown on GitHub or GitLab**: `npx yuhwa md README.md` (or `pnpm dlx yuhwa md README.md`) renders every
213
+ ` ```yuhwa ` (or ` ```yu `) block to an SVG file and links it in ([details](https://ph1p.github.io/yuhwa/guide/markdown)).
213
214
 
214
215
  **In docs sites**: `pnpm add -D yuhwa`, write ` ```yuhwa ` blocks, get SVG
215
216
  figures at build time.
@@ -247,6 +248,7 @@ Also: an [HTTP render service](https://ph1p.github.io/yuhwa/guide/embedding) for
247
248
  ```bash
248
249
  npx yuhwa guide # language reference, written for agents
249
250
  npx yuhwa check x.yu --json # diagnostics that name the fix
251
+ # pnpm: pnpm dlx yuhwa guide, pnpm dlx yuhwa check x.yu --json
250
252
  ```
251
253
 
252
254
  Point your agent at `yuhwa guide`, let it write source, loop on `check --json`
package/dist/astro.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as YuhwaDocsOptions } from "./figure-QAwSU1Ry.js";
1
+ import { t as YuhwaDocsOptions } from "./figure-BLHfxz_e.js";
2
2
  interface SetupParams {
3
3
  updateConfig: (config: {
4
4
  markdown: {
package/dist/astro.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import remarkYuhwa from "./remark.js";
2
+ import { r as clientImports } from "./node-CkrQnPFb.js";
2
3
  // src/integrations/astro.ts
3
4
  /**
4
5
  * Astro integration, also for Starlight: renders ```yuhwa blocks in .md and
@@ -8,7 +9,8 @@ import remarkYuhwa from "./remark.js";
8
9
  * import yuhwa from 'yuhwa/astro';
9
10
  * export default defineConfig({ integrations: [starlight({...}), yuhwa()] });
10
11
  *
11
- * `yuhwa({ zoom: true })` also loads the pan and zoom script.
12
+ * `yuhwa({ zoom: true })` also loads the pan and zoom script. The canvas
13
+ * script always loads, for `output=canvas` fences.
12
14
  */
13
15
  function yuhwa(opts = {}) {
14
16
  const docs = opts.zoom ? {
@@ -19,8 +21,7 @@ function yuhwa(opts = {}) {
19
21
  name: "yuhwa",
20
22
  hooks: { "astro:config:setup": ({ updateConfig, injectScript }) => {
21
23
  updateConfig({ markdown: { remarkPlugins: [[remarkYuhwa, docs]] } });
22
- injectScript("page-ssr", `import 'yuhwa/style.css';`);
23
- if (opts.zoom) injectScript("page", `import 'yuhwa/zoom';`);
24
+ for (const m of clientImports(opts)) injectScript(m.endsWith(".css") ? "page-ssr" : "page", `import '${m}';`);
24
25
  } }
25
26
  };
26
27
  }
package/dist/browser.d.ts CHANGED
@@ -1,18 +1,24 @@
1
1
  /**
2
2
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
3
- * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`), `pre.yuhwa` and
3
+ * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`, `.language-yu`,
4
+ * `.lang-yu`), `pre.yuhwa` and
4
5
  * `div.yuhwa` element on the page, and defines the <yuhwa-diagram>
5
6
  * custom element:
6
7
  *
7
8
  * <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
8
9
  * <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
9
10
  * <yuhwa-diagram src="big.yu" zoom="480px"></yuhwa-diagram> // pan and zoom
11
+ * <yuhwa-diagram render="canvas">a -> b</yuhwa-diagram> // or png; default svg
10
12
  * el.source = 'a -> b' // re-renders
11
13
  */
12
- import { $ as PanelDecl, A as setLineProp, At as registry, B as EdgeDecl, C as isYuhwaPath, Ct as RowKind, D as parse, Dt as optionKind, E as onlyColor, Et as YuhwaPlugin, F as Component, Ft as renderHead, G as LaidEdge, Gt as segsW, H as GroupDecl, Ht as parseInline, I as Curve, It as InkColors, J as LaidPanel, Jt as tspans, K as LaidGroup, L as Diagnostic, Lt as Seg, M as splitTrailingProps, Mt as use, Nt as MarkerKind, O as parseProps, Ot as perPass, P as Box, Pt as ShapeKind, Q as NodeOverride, Qt as RAMPS, R as Diagram, Rt as esc, S as blockBraces, St as RowCtx, T as lex, Tt as StatementKind, U as HeadKind, V as EdgeOverride, W as LabelRef, Wt as renderSegs, X as LayoutOverrides, Xt as LineStyle, Y as Layout, Z as NodeDecl, _ as PANELS, _n as themeNames, _t as Decoration, an as ThemeInput, at as PartEdit, b as Tok, bn as canvasMeasure, bt as PanelKind, ct as ResolvedEdgeStyle, dn as isSafeCss, dt as Side, en as THEMES, et as PanelHandle, f as portOn, fn as isSafeLink, ft as SourceRef, g as LexedLine, gt as layout, h as KNOWN_SETTINGS, hn as registerTheme, ht as groupPath, in as Theme, it as PartChange, j as setTrailingProp, jt as unuse, k as serializeProps, kt as recolor, ln as getTheme, lt as ResolvedNodeStyle, mn as ramp, nn as THEME_NAMES, nt as PanelPart, o as lineStyle, ot as Point, pn as isToneOrHex, pt as GRID, q as LaidNode, r as dashFor, rn as TONES, rt as PartAction, sn as createTheme, st as Props, tn as THEME_KEYS, tt as PanelOverride, u as SHAPES, ut as ShapeName, v as ParseOptions, vt as FrameKind, w as joinPath, wt as RowPaint, x as TokKind, xt as PanelOption, y as SETTING_VALUES, yn as approxMeasure, yt as PanelCtx, z as Direction } from "./plugin-NSkNyoUj.js";
13
- import { $ as JsonResult, A as GROUP_PROPS, B as MdResult, C as markers, D as COLORS, E as BOOLS, F as ConvertResult, G as formatLayout, H as processMarkdown, I as fromMermaid, J as setProp, K as setLabel, L as isMermaid, M as NUMBERS, N as PANEL_PROPS, O as EDGE_PROPS, P as lint, Q as DiagramJSON, R as MdBlock, S as themes, T as GUIDE, U as replaceBlockSource, V as findBlocks, W as editPart, X as writeLayout, Y as setSetting, Z as writePanelDrag, _ as legend, b as tables, c as treeview, d as gantt, et as fromJSON, f as mindmap, g as sequence, h as timeline, i as hash, j as NODE_PROPS, k as ENUMS, l as kanban, m as chart, n as Options, o as toSource, p as git, q as setPartTone, r as Result, s as builtins, t as InputFormat, tt as renderSvg, u as quadrant, v as footer, w as shapes, x as charts, y as frames, z as MdOptions } from "./index-6ZPJGThY.js";
14
+ import { $ as PanelDecl, A as setLineProp, At as registry, B as EdgeDecl, C as isYuhwaPath, Cn as canvasMeasure, Ct as RowKind, D as parse, Dt as optionKind, E as onlyColor, Et as YuhwaPlugin, F as Component, Ft as renderHead, G as LaidEdge, Gt as segsW, H as GroupDecl, Ht as parseInline, I as Curve, It as InkColors, J as LaidPanel, Jt as tspans, K as LaidGroup, L as Diagnostic, Lt as Seg, M as splitTrailingProps, Mt as use, Nt as MarkerKind, O as parseProps, Ot as perPass, P as Box, Pt as ShapeKind, Q as NodeOverride, Qt as RAMPS, R as Diagram, Rt as esc, S as blockBraces, Sn as approxMeasure, St as RowCtx, T as lex, Tt as StatementKind, U as HeadKind, V as EdgeOverride, W as LabelRef, Wt as renderSegs, X as LayoutOverrides, Xt as LineStyle, Y as Layout, Z as NodeDecl, _ as PANELS, _n as ramp, _t as Decoration, an as ThemeInput, at as PartEdit, b as Tok, bn as themeNames, bt as PanelKind, ct as ResolvedEdgeStyle, dn as getTheme, dt as Side, en as THEMES, et as PanelHandle, f as portOn, ft as SourceRef, g as LexedLine, gn as isToneOrHex, gt as layout, h as KNOWN_SETTINGS, hn as isSafeLink, ht as groupPath, in as Theme, it as PartChange, j as setTrailingProp, jt as unuse, k as serializeProps, kt as recolor, ln as fontFamilies, lt as ResolvedNodeStyle, mn as isSafeCss, nn as THEME_NAMES, nt as PanelPart, o as lineStyle, ot as Point, pn as isGenericFont, pt as GRID, q as LaidNode, r as dashFor, rn as TONES, rt as PartAction, sn as createTheme, st as Props, tn as THEME_KEYS, tt as PanelOverride, u as SHAPES, un as fontStack, ut as ShapeName, v as ParseOptions, vn as registerTheme, vt as FrameKind, w as joinPath, wt as RowPaint, x as TokKind, xt as PanelOption, y as SETTING_VALUES, yt as PanelCtx, z as Direction } from "./plugin-NMP_uf1a.js";
15
+ import { $ as setPartTone, A as GROUP_PROPS, B as MdOptions, C as markers, D as COLORS, E as BOOLS, F as ConvertResult, G as FontSource, H as findBlocks, I as fromMermaid, J as loadFonts, K as RasterOptions, L as isMermaid, M as NUMBERS, N as PANEL_PROPS, O as EDGE_PROPS, P as lint, Q as setLabel, R as MD_LANGUAGES, S as themes, T as GUIDE, U as processMarkdown, V as MdResult, W as replaceBlockSource, X as editPart, Y as svgToCanvas, Z as formatLayout, _ as legend, at as JsonResult, b as tables, c as treeview, d as gantt, et as setProp, f as mindmap, g as sequence, h as timeline, i as hash, it as DiagramJSON, j as NODE_PROPS, k as ENUMS, l as kanban, m as chart, n as Options, nt as writeLayout, o as toSource, ot as fromJSON, p as git, q as embedFonts, r as Result, rt as writePanelDrag, s as builtins, st as renderSvg, t as InputFormat, tt as setSetting, u as quadrant, v as footer, w as shapes, x as charts, y as frames, z as MdBlock } from "./index-xVW43gqW.js";
14
16
  import { i as zoomable, n as Zoomer, r as zoomHeight, t as ZoomOptions } from "./zoom-CCSUbX1X.js";
15
17
  export declare function render(source: string, opts?: Options): Result;
18
+ /** `render`, then draw the diagram into a canvas. */
19
+ export declare function renderCanvas(source: string, opts?: Options & RasterOptions): Promise<Result & {
20
+ canvas: HTMLCanvasElement;
21
+ }>;
16
22
  /**
17
23
  * Fetches every file that `source` imports, and what those import, so
18
24
  * `render` can resolve them synchronously. Paths join against `file` (a URL
@@ -35,4 +41,4 @@ export declare class YuhwaDiagram extends Base {
35
41
  connectedCallback(): void;
36
42
  attributeChangedCallback(): void;
37
43
  }
38
- export { BOOLS, type Box, COLORS, type Component, type ConvertResult, type Curve, type Decoration, type Diagnostic, type Diagram, type DiagramJSON, type Direction, EDGE_PROPS, ENUMS, type EdgeDecl, type EdgeOverride, type FrameKind, GRID, GROUP_PROPS, GUIDE, type GroupDecl, type HeadKind, type InkColors, InputFormat, type JsonResult, KNOWN_SETTINGS, type LabelRef, type LaidEdge, type LaidGroup, type LaidNode, type LaidPanel, type Layout, type LayoutOverrides, type LexedLine, type LineStyle, type MarkerKind, type MdBlock, type MdOptions, type MdResult, NODE_PROPS, NUMBERS, type NodeDecl, type NodeOverride, Options, PANELS, PANEL_PROPS, type PanelCtx, type PanelDecl, type PanelHandle, type PanelKind, type PanelOption, type PanelOverride, type PanelPart, type ParseOptions, type PartAction, type PartChange, type PartEdit, type Point, type Props, RAMPS, type ResolvedEdgeStyle, type ResolvedNodeStyle, Result, type RowCtx, type RowKind, type RowPaint, SETTING_VALUES, SHAPES, type Seg, type ShapeKind, type ShapeName, type Side, type SourceRef, type StatementKind, THEMES, THEME_KEYS, THEME_NAMES, TONES, type Theme, type ThemeInput, type Tok, type TokKind, type YuhwaPlugin, type ZoomOptions, type Zoomer, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, esc, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, gantt, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, kanban, layout, legend, lex, lineStyle, lint, markers, mindmap, onlyColor, optionKind, parse, parseInline, parseProps, perPass, portOn, processMarkdown, quadrant, ramp, recolor, registerTheme, registry, renderHead, renderSegs, renderSvg, replaceBlockSource, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, shapes, splitTrailingProps, tables, themeNames, themes, timeline, toSource, treeview, tspans, unuse, use, writeLayout, writePanelDrag, zoomHeight, zoomable };
44
+ export { BOOLS, type Box, COLORS, type Component, type ConvertResult, type Curve, type Decoration, type Diagnostic, type Diagram, type DiagramJSON, type Direction, EDGE_PROPS, ENUMS, type EdgeDecl, type EdgeOverride, type FontSource, type FrameKind, GRID, GROUP_PROPS, GUIDE, type GroupDecl, type HeadKind, type InkColors, InputFormat, type JsonResult, KNOWN_SETTINGS, type LabelRef, type LaidEdge, type LaidGroup, type LaidNode, type LaidPanel, type Layout, type LayoutOverrides, type LexedLine, type LineStyle, MD_LANGUAGES, type MarkerKind, type MdBlock, type MdOptions, type MdResult, NODE_PROPS, NUMBERS, type NodeDecl, type NodeOverride, Options, PANELS, PANEL_PROPS, type PanelCtx, type PanelDecl, type PanelHandle, type PanelKind, type PanelOption, type PanelOverride, type PanelPart, type ParseOptions, type PartAction, type PartChange, type PartEdit, type Point, type Props, RAMPS, type RasterOptions, type ResolvedEdgeStyle, type ResolvedNodeStyle, Result, type RowCtx, type RowKind, type RowPaint, SETTING_VALUES, SHAPES, type Seg, type ShapeKind, type ShapeName, type Side, type SourceRef, type StatementKind, THEMES, THEME_KEYS, THEME_NAMES, TONES, type Theme, type ThemeInput, type Tok, type TokKind, type YuhwaPlugin, type ZoomOptions, type Zoomer, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, embedFonts, esc, findBlocks, fontFamilies, fontStack, footer, formatLayout, frames, fromJSON, fromMermaid, gantt, getTheme, git, groupPath, hash, isGenericFont, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, kanban, layout, legend, lex, lineStyle, lint, loadFonts, markers, mindmap, onlyColor, optionKind, parse, parseInline, parseProps, perPass, portOn, processMarkdown, quadrant, ramp, recolor, registerTheme, registry, renderHead, renderSegs, renderSvg, replaceBlockSource, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, shapes, splitTrailingProps, svgToCanvas, tables, themeNames, themes, timeline, toSource, treeview, tspans, unuse, use, writeLayout, writePanelDrag, zoomHeight, zoomable };
package/dist/browser.js CHANGED
@@ -1,19 +1,27 @@
1
- import { A as chart, B as shapes, C as builtins, D as gantt, E as quadrant, F as frames, I as tables, L as charts, M as sequence, N as legend, O as mindmap, P as footer, R as themes, S as layout, T as kanban, _ as isMermaid, a as findBlocks, b as GRID, c as editPart, d as setPartTone, f as setProp, g as fromMermaid, h as writePanelDrag, i as GUIDE, j as timeline, k as git, l as formatLayout, m as writeLayout, n as render$1, o as processMarkdown, p as setSetting, r as toSource, s as replaceBlockSource, t as hash, u as setLabel, v as fromJSON, w as treeview, x as groupPath, y as renderSvg, z as markers } from "./src-BjOhvTAB.js";
2
- import { A as ENUMS, At as tspans, Bt as createTheme, C as setLineProp, Ct as segsW, D as BOOLS, Ft as THEMES, Gt as isSafeCss, I as lint, It as THEME_KEYS, Jt as ramp, Kt as isSafeLink, Lt as THEME_NAMES, M as NODE_PROPS, N as NUMBERS, Nt as RAMPS, O as COLORS, P as PANEL_PROPS, Rt as TONES, S as serializeProps, T as splitTrailingProps, Ut as getTheme, V as portOn, Y as renderHead, Yt as registerTheme, Z as dashFor, Zt as themeNames, _ as onlyColor, _t as parseInline, a as perPass, bt as renderSegs, c as unuse, d as PANELS, f as SETTING_VALUES, ft as esc, g as lex, h as joinPath, i as optionKind, j as GROUP_PROPS, k as EDGE_PROPS, l as use, m as isYuhwaPath, n as approxMeasure, o as recolor, p as blockBraces, qt as isToneOrHex, r as canvasMeasure, s as registry, tt as lineStyle, u as KNOWN_SETTINGS, v as parse, w as setTrailingProp, y as parseProps, z as SHAPES } from "./plugin-Bs4eiAuz.js";
3
- import { n as zoomable, t as zoomHeight } from "./zoom-QeqB6QlH.js";
1
+ import { A as gantt, B as charts, C as GRID, D as treeview, E as builtins, F as sequence, H as markers, I as legend, L as footer, M as git, N as chart, O as kanban, P as timeline, R as frames, S as renderSvg, T as layout, U as shapes, V as themes, _ as writeLayout, a as MD_LANGUAGES, b as isMermaid, d as editPart, f as formatLayout, g as setSetting, h as setProp, i as GUIDE, j as mindmap, k as quadrant, l as processMarkdown, m as setPartTone, n as render$1, o as findBlocks, p as setLabel, r as toSource, t as hash, u as replaceBlockSource, v as writePanelDrag, w as groupPath, x as fromJSON, y as fromMermaid, z as tables } from "./src-NCXCTK_4.js";
2
+ import { a as perPass, c as unuse, i as optionKind, l as use, n as approxMeasure, o as recolor, r as canvasMeasure, s as registry } from "./plugin-CitzbblK.js";
3
+ import { n as zoomable, t as zoomHeight } from "./zoom-yxhxX16c.js";
4
+ import { a as svgFamilies, c as swapForRaster, n as embedFonts, r as loadFonts, s as svgToCanvas } from "./raster-iqi6XRPU.js";
5
+ import { Bt as getTheme, C as ENUMS, D as PANEL_PROPS, E as NUMBERS, Et as tspans, F as portOn, G as renderHead, Gt as isToneOrHex, Ht as isGenericFont, It as createTheme, Kt as ramp, M as SHAPES, Mt as THEME_KEYS, Nt as THEME_NAMES, Pt as TONES, Rt as fontFamilies, S as EDGE_PROPS, T as NODE_PROPS, Ut as isSafeCss, Wt as isSafeLink, Yt as themeNames, Z as lineStyle, _ as setTrailingProp, b as BOOLS, c as joinPath, ct as esc, d as parse, f as parseProps, g as setLineProp, gt as renderSegs, h as serializeProps, jt as THEMES, k as lint, kt as RAMPS, l as lex, n as PANELS, o as blockBraces, pt as parseInline, q as dashFor, qt as registerTheme, r as SETTING_VALUES, s as isYuhwaPath, t as KNOWN_SETTINGS, u as onlyColor, v as splitTrailingProps, w as GROUP_PROPS, x as COLORS, y as unquote, yt as segsW, zt as fontStack } from "./parse--ljBMU60.js";
4
6
  // src/browser.ts
5
7
  /**
6
8
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
7
- * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`), `pre.yuhwa` and
9
+ * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`, `.language-yu`,
10
+ * `.lang-yu`), `pre.yuhwa` and
8
11
  * `div.yuhwa` element on the page, and defines the <yuhwa-diagram>
9
12
  * custom element:
10
13
  *
11
14
  * <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
12
15
  * <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
13
16
  * <yuhwa-diagram src="big.yu" zoom="480px"></yuhwa-diagram> // pan and zoom
17
+ * <yuhwa-diagram render="canvas">a -> b</yuhwa-diagram> // or png; default svg
14
18
  * el.source = 'a -> b' // re-renders
15
19
  */
16
- const SELECTOR = "pre > code.language-yuhwa, pre > code.lang-yuhwa, pre.yuhwa, div.yuhwa:not([data-rendered])";
20
+ const SELECTOR = [
21
+ ...MD_LANGUAGES.flatMap((l) => [`pre > code.language-${l}`, `pre > code.lang-${l}`]),
22
+ "pre.yuhwa",
23
+ "div.yuhwa:not([data-rendered])"
24
+ ].join(", ");
17
25
  function prefersDark() {
18
26
  return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
19
27
  }
@@ -29,6 +37,15 @@ function render(source, opts = {}) {
29
37
  theme
30
38
  });
31
39
  }
40
+ /** `render`, then draw the diagram into a canvas. */
41
+ async function renderCanvas(source, opts = {}) {
42
+ let r = render(source, opts);
43
+ if (await loadFonts(r.svg)) r = render(source, opts);
44
+ return {
45
+ ...r,
46
+ canvas: await svgToCanvas(r.svg, opts)
47
+ };
48
+ }
32
49
  const IMPORT_RE = /^\s*import\s+(?:\{[^}]*\}\s*from\s+)?"([^"]+)"/gm;
33
50
  /**
34
51
  * Fetches every file that `source` imports, and what those import, so
@@ -55,12 +72,49 @@ async function fetchImports(source, file, load = fetchText) {
55
72
  return files;
56
73
  }
57
74
  const fetchText = (url) => fetch(url).then((r) => r.ok ? r.text() : Promise.reject(/* @__PURE__ */ new Error(`${url}: HTTP ${r.status}`)));
58
- function fit(svg) {
59
- if (!svg) return;
60
- svg.removeAttribute("height");
61
- svg.style.maxWidth = "100%";
62
- svg.style.height = "auto";
63
- svg.style.display = "block";
75
+ function fit(el) {
76
+ if (!el) return;
77
+ el.removeAttribute("height");
78
+ el.style.maxWidth = "100%";
79
+ el.style.height = "auto";
80
+ el.style.display = "block";
81
+ }
82
+ /** diagrams to redraw when one of their web fonts loads: the families each names, and its redraw */
83
+ const waiting = /* @__PURE__ */ new Map();
84
+ let listening = false;
85
+ /**
86
+ * Redraws `node` once a web font it names (in `svg`) finishes loading, so
87
+ * boxes fit the real text. Text is measured when the diagram renders, and a
88
+ * font still loading is measured with its fallback. One `loadingdone`
89
+ * listener serves every diagram; a node that left the page drops out.
90
+ */
91
+ function redrawOnFonts(node, svg, redraw) {
92
+ const fonts = typeof document === "undefined" ? void 0 : document.fonts;
93
+ if (!fonts) return;
94
+ waiting.set(node, {
95
+ families: svgFamilies(svg),
96
+ redraw
97
+ });
98
+ if (listening) return;
99
+ listening = true;
100
+ fonts.addEventListener("loadingdone", (e) => {
101
+ const loaded = new Set(e.fontfaces.map((f) => unquote(f.family).toLowerCase()));
102
+ for (const [el, { families, redraw }] of waiting) if (!el.isConnected) waiting.delete(el);
103
+ else if ([...families].some((f) => loaded.has(f))) redraw();
104
+ });
105
+ }
106
+ /**
107
+ * Puts the SVG into `host`. `render="png"` or `"canvas"` then draws it and
108
+ * swaps the drawing in for the SVG, unless `current()` says a newer draw came.
109
+ */
110
+ function show(host, svg, mode, label, current) {
111
+ host.querySelectorAll("img[src^=\"blob:\"]").forEach((img) => URL.revokeObjectURL(img.src));
112
+ host.innerHTML = svg;
113
+ const node = host.querySelector("svg");
114
+ fit(node);
115
+ const fonts = loadFonts(svg);
116
+ if (!node || mode !== "png" && mode !== "canvas") return;
117
+ fonts.then((changed) => changed ? void 0 : swapForRaster(node, svg, mode, label, current)).then(fit, (e) => console.warn(`yuhwa: ${mode} drawing failed: ${e.message}`));
64
118
  }
65
119
  function run(root = document, opts = {}) {
66
120
  root.querySelectorAll(SELECTOR).forEach((el) => {
@@ -70,22 +124,27 @@ function run(root = document, opts = {}) {
70
124
  out.className = "yuhwa";
71
125
  out.dataset.rendered = "true";
72
126
  out.dataset.source = source;
73
- let ok = false;
74
- try {
127
+ let draws = 0;
128
+ const paint = () => {
75
129
  const r = render(source, {
76
130
  theme: host.dataset.theme,
77
131
  ...opts
78
132
  });
79
- out.innerHTML = r.svg;
80
- fit(out.querySelector("svg"));
133
+ out.yuhwaZoom?.destroy();
134
+ const draw = ++draws;
135
+ show(out, r.svg, host.dataset.render, r.diagram.settings.title ?? "diagram", () => draw === draws);
136
+ if (host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
137
+ redrawOnFonts(out, r.svg, paint);
138
+ return r;
139
+ };
140
+ host.replaceWith(out);
141
+ try {
142
+ const r = paint();
81
143
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
82
- ok = true;
83
144
  } catch (e) {
84
145
  out.textContent = `yuhwa error: ${e.message}`;
85
146
  out.style.color = "crimson";
86
147
  }
87
- host.replaceWith(out);
88
- if (ok && host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
89
148
  });
90
149
  }
91
150
  const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
@@ -99,13 +158,15 @@ var YuhwaDiagram = class extends Base {
99
158
  "theme",
100
159
  "src",
101
160
  "zoom",
102
- "wheel"
161
+ "wheel",
162
+ "render"
103
163
  ];
104
164
  #source = null;
105
165
  #fetched = null;
106
166
  #request = 0;
107
167
  #file;
108
168
  #files = {};
169
+ #draws = 0;
109
170
  get source() {
110
171
  return this.#source ?? "";
111
172
  }
@@ -151,8 +212,9 @@ var YuhwaDiagram = class extends Base {
151
212
  resolve: (p) => files[p]
152
213
  });
153
214
  this.yuhwaZoom?.destroy();
154
- this.innerHTML = r.svg;
155
- fit(this.querySelector("svg"));
215
+ const draw = ++this.#draws;
216
+ const label = this.getAttribute("aria-label") ?? r.diagram.settings.title ?? "diagram";
217
+ show(this, r.svg, this.getAttribute("render") ?? void 0, label, () => draw === this.#draws);
156
218
  const zoom = this.getAttribute("zoom");
157
219
  this.setAttribute("role", zoom === null ? "img" : "group");
158
220
  if (zoom !== null) zoomable(this, {
@@ -165,6 +227,7 @@ var YuhwaDiagram = class extends Base {
165
227
  else if (this.dataset.autoLabel) this.removeAttribute("aria-label"), delete this.dataset.autoLabel;
166
228
  }
167
229
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
230
+ redrawOnFonts(this, r.svg, () => this.#draw());
168
231
  this.dispatchEvent(new CustomEvent("yuhwa:render", { detail: {
169
232
  diagnostics: r.diagnostics,
170
233
  format: r.format
@@ -185,4 +248,4 @@ if (typeof document !== "undefined") {
185
248
  else run();
186
249
  }
187
250
  }
188
- export { BOOLS, COLORS, EDGE_PROPS, ENUMS, GRID, GROUP_PROPS, GUIDE, KNOWN_SETTINGS, NODE_PROPS, NUMBERS, PANELS, PANEL_PROPS, RAMPS, SETTING_VALUES, SHAPES, THEMES, THEME_KEYS, THEME_NAMES, TONES, YuhwaDiagram, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, esc, fetchImports, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, gantt, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, kanban, layout, legend, lex, lineStyle, lint, markers, mindmap, onlyColor, optionKind, parse, parseInline, parseProps, perPass, portOn, processMarkdown, quadrant, ramp, recolor, registerTheme, registry, render, renderHead, renderSegs, renderSvg, replaceBlockSource, run, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, shapes, splitTrailingProps, tables, themeNames, themes, timeline, toSource, treeview, tspans, unuse, use, writeLayout, writePanelDrag, zoomHeight, zoomable };
251
+ export { BOOLS, COLORS, EDGE_PROPS, ENUMS, GRID, GROUP_PROPS, GUIDE, KNOWN_SETTINGS, MD_LANGUAGES, NODE_PROPS, NUMBERS, PANELS, PANEL_PROPS, RAMPS, SETTING_VALUES, SHAPES, THEMES, THEME_KEYS, THEME_NAMES, TONES, YuhwaDiagram, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, embedFonts, esc, fetchImports, findBlocks, fontFamilies, fontStack, footer, formatLayout, frames, fromJSON, fromMermaid, gantt, getTheme, git, groupPath, hash, isGenericFont, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, kanban, layout, legend, lex, lineStyle, lint, loadFonts, markers, mindmap, onlyColor, optionKind, parse, parseInline, parseProps, perPass, portOn, processMarkdown, quadrant, ramp, recolor, registerTheme, registry, render, renderCanvas, renderHead, renderSegs, renderSvg, replaceBlockSource, run, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, shapes, splitTrailingProps, svgToCanvas, tables, themeNames, themes, timeline, toSource, treeview, tspans, unuse, use, writeLayout, writePanelDrag, zoomHeight, zoomable };
@@ -0,0 +1,2 @@
1
+ /** swaps the images of `figure[data-render="canvas"]` for canvases, now and as figures are added */
2
+ export declare function installCanvas(): void;
package/dist/canvas.js ADDED
@@ -0,0 +1,40 @@
1
+ import { n as svgFromDataUri } from "./svg-uri-Dx8SGV-n.js";
2
+ import { t as watchFigures } from "./watch-2VeW5DUN.js";
3
+ // src/integrations/canvas.ts
4
+ /**
5
+ * Canvas output for diagrams rendered with `output: 'canvas'`. Import it once
6
+ * in the site's client code; it does nothing during server rendering.
7
+ *
8
+ * import 'yuhwa/canvas';
9
+ *
10
+ * The page holds each diagram as an SVG `<img>`, so it shows without
11
+ * JavaScript. This script draws every one into a `<canvas>`, with the page's
12
+ * web fonts embedded, and swaps it in once it comes near the viewport. When
13
+ * drawing fails, the image stays.
14
+ */
15
+ /** swaps the images of `figure[data-render="canvas"]` for canvases, now and as figures are added */
16
+ function installCanvas() {
17
+ const swap = async (img) => {
18
+ const svg = svgFromDataUri(img.getAttribute("src") ?? "");
19
+ if (svg === void 0) return;
20
+ const { swapForRaster } = await import("./raster-iqi6XRPU.js").then((n) => n.i);
21
+ const canvas = await swapForRaster(img, svg, "canvas", img.alt);
22
+ if (canvas) canvas.className = img.className;
23
+ };
24
+ const near = new IntersectionObserver((entries) => {
25
+ for (const e of entries) {
26
+ if (!e.isIntersecting) continue;
27
+ near.unobserve(e.target);
28
+ swap(e.target).catch(() => {});
29
+ }
30
+ }, { rootMargin: "200px" });
31
+ watchFigures("__yuhwaCanvas", () => {
32
+ document.querySelectorAll("figure[data-render=\"canvas\"] img.yuhwa-svg").forEach((img) => {
33
+ if (img.dataset.yuhwaCanvas !== void 0) return;
34
+ img.dataset.yuhwaCanvas = "";
35
+ near.observe(img);
36
+ });
37
+ });
38
+ }
39
+ if (typeof document !== "undefined") installCanvas();
40
+ export { installCanvas };