yuhwa 1.2.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 -3
  5. package/dist/browser.js +85 -21
  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-sZtzIA6-.js → lsp.worker-N6A9m364.js} +23 -17
  11. package/dist/editor/index.html +4 -1
  12. package/dist/{figure-CA2hy0xh.d.ts → figure-BLHfxz_e.d.ts} +28 -5
  13. package/dist/index-xVW43gqW.d.ts +261 -0
  14. package/dist/index.d.ts +3 -2
  15. package/dist/index.js +5 -1
  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 +47 -27
  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-Bzn2uKXZ.js → node-CkrQnPFb.js} +90 -12
  28. package/dist/parse--ljBMU60.js +3884 -0
  29. package/dist/plugin-CitzbblK.js +301 -0
  30. package/dist/{index-CnnoZYl0.d.ts → plugin-NMP_uf1a.d.ts} +93 -208
  31. package/dist/plugin.d.ts +12 -0
  32. package/dist/plugin.js +3 -0
  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-Dxo7OG8K.js → server-BTYtmr6B.js} +41 -63
  38. package/dist/{server--jHjJjOS.d.ts → server-DMAOtqqK.d.ts} +1 -1
  39. package/dist/{service-B1fpOg_L.js → service-C60VdeKS.js} +35 -3
  40. package/dist/{service-Brvpt7Do.d.ts → service-DimTFsE3.d.ts} +2 -0
  41. package/dist/{shared-Ddw88O9D.js → shared-h8tkFLY4.js} +719 -421
  42. package/dist/{src-DkQj7aIV.js → src-NCXCTK_4.js} +512 -4548
  43. package/dist/svg-uri-Dx8SGV-n.js +7 -0
  44. package/dist/vite.d.ts +1 -1
  45. package/dist/vite.js +3 -2
  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 +24 -2
  55. package/skills/yuhwa/SKILL.md +12 -0
  56. package/dist/editor/assets/index-BphHLTvA.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-CA2hy0xh.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,17 +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 LexedLine, $t as FrameKind, A as isMermaid, An as ThemeInput, At as LaidPanel, B as setPartTone, Bn as canvasMeasure, Bt as PartChange, C as GROUP_PROPS, Cn as LineStyle, Ct as EdgeOverride, D as lint, Dn as THEME_NAMES, Dt as LaidEdge, E as PANEL_PROPS, En as THEME_KEYS, Et as LabelRef, F as processMarkdown, Fn as isToneOrHex, Ft as PanelDecl, G as dashFor, Gt as ResolvedNodeStyle, H as setSetting, Ht as Point, I as replaceBlockSource, In as ramp, It as PanelHandle, J as DiagramJSON, Jt as SourceRef, K as lineStyle, Kt as ShapeName, L as editPart, Ln as registerTheme, Lt as PanelOverride, M as MdOptions, Mn as getTheme, Mt as LayoutOverrides, N as MdResult, Nn as isSafeCss, Nt as NodeDecl, O as ConvertResult, On as TONES, Ot as LaidGroup, P as findBlocks, Pn as isSafeLink, Pt as NodeOverride, Q as KNOWN_SETTINGS, Qt as Decoration, R as formatLayout, Rn as themeNames, Rt as PanelPart, S as ENUMS, Sn as tspans, St as EdgeDecl, T as NUMBERS, Tn as THEMES, Tt as HeadKind, U as writeLayout, Ut as Props, V as setProp, Vt as PartEdit, W as writePanelDrag, Wt as ResolvedEdgeStyle, X as fromJSON, Xt as groupPath, Y as JsonResult, Yt as GRID, Z as renderSvg, Zt as layout, _ as themes, _n as InkColors, _t as Component, an as RowPaint, at as blockBraces, b as COLORS, bn as renderSegs, bt as Diagram, c as git, cn as optionKind, ct as lex, d as sequence, dn as registry, dt as parseProps, en as PanelCtx, et as PANELS, f as legend, fn as unuse, ft as serializeProps, g as charts, gn as renderHead, gt as Box, h as tables, hn as ShapeKind, ht as splitTrailingProps, i as hash, in as RowKind, it as TokKind, j as MdBlock, jn as createTheme, jt as Layout, k as fromMermaid, kn as Theme, kt as LaidNode, l as chart, ln as perPass, lt as onlyColor, m as frames, mn as MarkerKind, mt as setTrailingProp, n as Options, nn as PanelOption, nt as SETTING_VALUES, o as toSource, on as StatementKind, ot as isYuhwaPath, p as footer, pn as use, pt as setLineProp, q as SHAPES, qt as Side, r as Result, rn as RowCtx, rt as Tok, s as builtins, sn as YuhwaPlugin, st as joinPath, t as InputFormat, tn as PanelKind, tt as ParseOptions, u as timeline, un as recolor, ut as parse, v as GUIDE, vn as Seg, vt as Curve, w as NODE_PROPS, wn as RAMPS, wt as GroupDecl, x as EDGE_PROPS, xn as segsW, xt as Direction, y as BOOLS, yn as parseInline, yt as Diagnostic, z as setLabel, zn as approxMeasure, zt as PartAction } from "./index-CnnoZYl0.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";
13
16
  import { i as zoomable, n as Zoomer, r as zoomHeight, t as ZoomOptions } from "./zoom-CCSUbX1X.js";
14
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
+ }>;
15
22
  /**
16
23
  * Fetches every file that `source` imports, and what those import, so
17
24
  * `render` can resolve them synchronously. Paths join against `file` (a URL
@@ -34,4 +41,4 @@ export declare class YuhwaDiagram extends Base {
34
41
  connectedCallback(): void;
35
42
  attributeChangedCallback(): void;
36
43
  }
37
- 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, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, optionKind, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, renderHead, renderSegs, renderSvg, replaceBlockSource, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, 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,18 +1,27 @@
1
- import { $ as setLineProp, A as approxMeasure, At as isSafeCss, B as unuse, C as builtins, Ct as RAMPS, D as sequence, Dt as TONES, E as timeline, Et as THEME_NAMES, F as themes, Ft as themeNames, G as blockBraces, H as KNOWN_SETTINGS, I as optionKind, J as lex, K as isYuhwaPath, L as perPass, M as frames, Mt as isToneOrHex, N as tables, Nt as ramp, O as legend, Ot as createTheme, P as charts, Pt as registerTheme, Q as serializeProps, R as recolor, S as layout, St as tspans, T as chart, Tt as THEME_KEYS, U as PANELS, V as use, W as SETTING_VALUES, X as parse, Y as onlyColor, Z as parseProps, _ as isMermaid, _t as parseInline, a as findBlocks, at as ENUMS, b as GRID, bt as segsW, c as editPart, ct as NUMBERS, d as setPartTone, dt as lint, et as setTrailingProp, f as setProp, ft as SHAPES, g as fromMermaid, h as writePanelDrag, ht as lineStyle, i as GUIDE, it as EDGE_PROPS, j as canvasMeasure, jt as isSafeLink, k as footer, kt as getTheme, l as formatLayout, lt as PANEL_PROPS, m as writeLayout, mt as dashFor, n as render$1, nt as BOOLS, o as processMarkdown, ot as GROUP_PROPS, p as setSetting, pt as renderHead, q as joinPath, r as toSource, rt as COLORS, s as replaceBlockSource, st as NODE_PROPS, t as hash, tt as splitTrailingProps, u as setLabel, v as fromJSON, w as git, wt as THEMES, x as groupPath, y as renderSvg, yt as renderSegs, z as registry } from "./src-DkQj7aIV.js";
2
- 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";
3
6
  // src/browser.ts
4
7
  /**
5
8
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
6
- * 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
7
11
  * `div.yuhwa` element on the page, and defines the <yuhwa-diagram>
8
12
  * custom element:
9
13
  *
10
14
  * <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
11
15
  * <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
12
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
13
18
  * el.source = 'a -> b' // re-renders
14
19
  */
15
- 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(", ");
16
25
  function prefersDark() {
17
26
  return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
18
27
  }
@@ -28,6 +37,15 @@ function render(source, opts = {}) {
28
37
  theme
29
38
  });
30
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
+ }
31
49
  const IMPORT_RE = /^\s*import\s+(?:\{[^}]*\}\s*from\s+)?"([^"]+)"/gm;
32
50
  /**
33
51
  * Fetches every file that `source` imports, and what those import, so
@@ -54,12 +72,49 @@ async function fetchImports(source, file, load = fetchText) {
54
72
  return files;
55
73
  }
56
74
  const fetchText = (url) => fetch(url).then((r) => r.ok ? r.text() : Promise.reject(/* @__PURE__ */ new Error(`${url}: HTTP ${r.status}`)));
57
- function fit(svg) {
58
- if (!svg) return;
59
- svg.removeAttribute("height");
60
- svg.style.maxWidth = "100%";
61
- svg.style.height = "auto";
62
- 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}`));
63
118
  }
64
119
  function run(root = document, opts = {}) {
65
120
  root.querySelectorAll(SELECTOR).forEach((el) => {
@@ -69,22 +124,27 @@ function run(root = document, opts = {}) {
69
124
  out.className = "yuhwa";
70
125
  out.dataset.rendered = "true";
71
126
  out.dataset.source = source;
72
- let ok = false;
73
- try {
127
+ let draws = 0;
128
+ const paint = () => {
74
129
  const r = render(source, {
75
130
  theme: host.dataset.theme,
76
131
  ...opts
77
132
  });
78
- out.innerHTML = r.svg;
79
- 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();
80
143
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
81
- ok = true;
82
144
  } catch (e) {
83
145
  out.textContent = `yuhwa error: ${e.message}`;
84
146
  out.style.color = "crimson";
85
147
  }
86
- host.replaceWith(out);
87
- if (ok && host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
88
148
  });
89
149
  }
90
150
  const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
@@ -98,13 +158,15 @@ var YuhwaDiagram = class extends Base {
98
158
  "theme",
99
159
  "src",
100
160
  "zoom",
101
- "wheel"
161
+ "wheel",
162
+ "render"
102
163
  ];
103
164
  #source = null;
104
165
  #fetched = null;
105
166
  #request = 0;
106
167
  #file;
107
168
  #files = {};
169
+ #draws = 0;
108
170
  get source() {
109
171
  return this.#source ?? "";
110
172
  }
@@ -150,8 +212,9 @@ var YuhwaDiagram = class extends Base {
150
212
  resolve: (p) => files[p]
151
213
  });
152
214
  this.yuhwaZoom?.destroy();
153
- this.innerHTML = r.svg;
154
- 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);
155
218
  const zoom = this.getAttribute("zoom");
156
219
  this.setAttribute("role", zoom === null ? "img" : "group");
157
220
  if (zoom !== null) zoomable(this, {
@@ -164,6 +227,7 @@ var YuhwaDiagram = class extends Base {
164
227
  else if (this.dataset.autoLabel) this.removeAttribute("aria-label"), delete this.dataset.autoLabel;
165
228
  }
166
229
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
230
+ redrawOnFonts(this, r.svg, () => this.#draw());
167
231
  this.dispatchEvent(new CustomEvent("yuhwa:render", { detail: {
168
232
  diagnostics: r.diagnostics,
169
233
  format: r.format
@@ -184,4 +248,4 @@ if (typeof document !== "undefined") {
184
248
  else run();
185
249
  }
186
250
  }
187
- 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, fetchImports, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, optionKind, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, render, renderHead, renderSegs, renderSvg, replaceBlockSource, run, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, 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 };