yuhwa 1.0.2 → 1.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/README.md +13 -12
- package/client.d.ts +9 -1
- package/dist/astro.d.ts +2 -2
- package/dist/astro.js +8 -1
- package/dist/browser.d.ts +11 -5
- package/dist/browser.js +27 -7
- package/dist/cli.js +612 -49
- package/dist/editor/assets/index-BphHLTvA.js +689 -0
- package/dist/editor/assets/lsp.worker-sZtzIA6-.js +30 -0
- package/dist/editor/index.html +5 -4
- package/dist/figure-CA2hy0xh.d.ts +48 -0
- package/dist/{index-Dl845tUQ.d.ts → index-CnnoZYl0.d.ts} +76 -7
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/ironmark.d.ts +4 -2
- package/dist/ironmark.js +18 -7
- package/dist/llms.txt +26 -17
- package/dist/lsp-browser.d.ts +2 -2
- package/dist/lsp-browser.js +1 -1
- package/dist/lsp-node.js +208 -212
- package/dist/lsp-server.d.ts +1 -1
- package/dist/lsp-server.js +1 -1
- package/dist/lsp.d.ts +44 -2
- package/dist/lsp.js +1 -1
- package/dist/markdown-it.d.ts +2 -1
- package/dist/markdown-it.js +7 -6
- package/dist/node-Bzn2uKXZ.js +224 -0
- package/dist/remark.d.ts +2 -1
- package/dist/remark.js +16 -5
- package/dist/{server-DJC_fQMe.d.ts → server--jHjJjOS.d.ts} +2 -2
- package/dist/{server-DmQuHQrG.js → server-Dxo7OG8K.js} +19 -2
- package/dist/{service-BYS9Qfkq.js → service-B1fpOg_L.js} +348 -44
- package/dist/{service-ClZ8clSQ.d.ts → service-Brvpt7Do.d.ts} +3 -1
- package/dist/{shared-qo_r6RUN.js → shared-Ddw88O9D.js} +3069 -742
- package/dist/{src-wk7tBpWs.js → src-DkQj7aIV.js} +2842 -744
- package/dist/style.css +14 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +19 -12
- package/dist/vuepress.d.ts +3 -1
- package/dist/vuepress.js +7 -2
- package/dist/yuhwa.iife.js +91 -75
- package/dist/zoom-CCSUbX1X.d.ts +49 -0
- package/dist/zoom-QeqB6QlH.js +275 -0
- package/dist/zoom-script-CVdAzMhX.js +51 -0
- package/dist/zoom.d.ts +35 -0
- package/dist/zoom.js +19 -0
- package/package.json +10 -2
- package/dist/editor/assets/index-BQLsumas.js +0 -587
- package/dist/editor/assets/lsp.worker-RlPj9blG.js +0 -26
- package/dist/figure-BZHIKnxv.d.ts +0 -27
- package/dist/node-Bneu5eJV.js +0 -108
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { C as
|
|
3
|
+
import { C as COLORS, D as NODE_PROPS, E as GROUP_PROPS, I as THEME_KEYS, L as THEME_NAMES, N as esc, R as TONES, T as ENUMS, _ as isYuhwaPath, c as render$1, d as optionKind, f as registry, h as SETTING_VALUES, i as format, j as SHAPES, k as PANEL_PROPS, l as toSource, o as tidy, p as KNOWN_SETTINGS, s as diskResolve, t as VERSION, u as canvasMeasure, v as joinPath$1, w as EDGE_PROPS, z as isSafeCss } from "./shared-Ddw88O9D.js";
|
|
4
4
|
import { createServer } from "node:http";
|
|
5
5
|
import { basename, dirname, extname, join, resolve, sep } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { spawn } from "node:child_process";
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
8
9
|
import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
|
|
9
10
|
// src/markdown.ts
|
|
10
11
|
/**
|
|
@@ -23,10 +24,15 @@ import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
|
|
|
23
24
|
*/
|
|
24
25
|
const COMMENT_OPEN = /^<!--\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
|
|
25
26
|
const FENCE_OPEN = /^(```+|~~~+)\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
|
|
26
|
-
function imageRef(name, lightPath, darkPath) {
|
|
27
|
-
if (darkPath)
|
|
28
|
-
|
|
27
|
+
function imageRef(name, lightPath, darkPath, href) {
|
|
28
|
+
if (darkPath) {
|
|
29
|
+
const pic = `<picture><source media="(prefers-color-scheme: dark)" srcset="${darkPath}"><img alt="${name}" src="${lightPath}"></picture>`;
|
|
30
|
+
return href ? `<a href="${href.replace(/"/g, "%22")}">${pic}</a>` : pic;
|
|
31
|
+
}
|
|
32
|
+
return href ? `[](${href})` : ``;
|
|
29
33
|
}
|
|
34
|
+
/** an image reference without the link `view` wraps it in */
|
|
35
|
+
const unlinked = (ref) => ref.match(/^\[(!\[[^\]]*\]\([^)]*\))\]\([^)]*\)$/)?.[1] ?? ref.match(/^<a href="[^"]*">(<picture>.*<\/picture>)<\/a>$/)?.[1] ?? ref;
|
|
30
36
|
function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
|
|
31
37
|
const lines = md.split("\n");
|
|
32
38
|
const blocks = [];
|
|
@@ -64,7 +70,7 @@ function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
|
|
|
64
70
|
};
|
|
65
71
|
let k = j + 1;
|
|
66
72
|
while (k < lines.length && lines[k].trim() === "" && k <= j + 1) k++;
|
|
67
|
-
const candidate = lines[k]?.trim();
|
|
73
|
+
const candidate = unlinked(lines[k]?.trim() ?? "");
|
|
68
74
|
const path = joinPath(outDir, `${n}.svg`);
|
|
69
75
|
if (candidate === imageRef(n, path) || candidate === imageRef(n, path, joinPath(outDir, `${n}.dark.svg`))) b.image = [k, k];
|
|
70
76
|
blocks.push(b);
|
|
@@ -96,7 +102,8 @@ function processMarkdown(md, opts = {}) {
|
|
|
96
102
|
path: lightPath,
|
|
97
103
|
svg: light.svg + "\n"
|
|
98
104
|
});
|
|
99
|
-
|
|
105
|
+
const href = light.diagram.imports?.length ? void 0 : opts.view?.(b.source);
|
|
106
|
+
let ref = imageRef(b.name, lightPath, void 0, href);
|
|
100
107
|
if (opts.dark) {
|
|
101
108
|
const dark = render$1(b.source, {
|
|
102
109
|
...io,
|
|
@@ -107,7 +114,7 @@ function processMarkdown(md, opts = {}) {
|
|
|
107
114
|
path: darkPath,
|
|
108
115
|
svg: dark.svg + "\n"
|
|
109
116
|
});
|
|
110
|
-
ref = imageRef(b.name, lightPath, darkPath);
|
|
117
|
+
ref = imageRef(b.name, lightPath, darkPath, href);
|
|
111
118
|
}
|
|
112
119
|
const replacement = [];
|
|
113
120
|
if (b.kind === "fence" && !opts.keepFences) replacement.push(`<!--yuhwa ${b.name}`, ...b.source.split("\n"), "-->");
|
|
@@ -136,9 +143,18 @@ function replaceBlockSource(md, index, source) {
|
|
|
136
143
|
const list = (xs) => [...xs].join(", ");
|
|
137
144
|
const code = (xs) => list([...xs].map((x) => "`" + x + "`"));
|
|
138
145
|
const panels = [...registry.panels.values()];
|
|
146
|
+
const PLACEHOLDER = {
|
|
147
|
+
color: "<colour>",
|
|
148
|
+
number: "N",
|
|
149
|
+
text: "…"
|
|
150
|
+
};
|
|
139
151
|
const settings = list([...KNOWN_SETTINGS].map((k) => SETTING_VALUES[k] ? `${k} (${SETTING_VALUES[k].join("|")})` : k));
|
|
140
152
|
const panelLines = panels.map((p) => {
|
|
141
|
-
const header = Object.entries(p.options ?? {}).map(([k, v]) =>
|
|
153
|
+
const header = Object.entries(p.options ?? {}).map(([k, v]) => {
|
|
154
|
+
const o = optionKind(v);
|
|
155
|
+
if (o.kind === "select") return `${k}: ${o.values.join("|")}`;
|
|
156
|
+
return o.kind === "flag" ? k : `${k}: ${PLACEHOLDER[o.kind]}`;
|
|
157
|
+
});
|
|
142
158
|
const body = p.guide ?? (p.syntax ? "`" + p.syntax + "`" : "");
|
|
143
159
|
return `- \`${p.name}\`: ${body}${header.length ? ` Header: ${code(header)}.` : ""}`;
|
|
144
160
|
}).join("\n");
|
|
@@ -149,7 +165,7 @@ yuhwa is a text diagram language that renders to a self-contained SVG. One
|
|
|
149
165
|
statement per line. \`//\` at line start or after a space starts a comment, so
|
|
150
166
|
URLs in labels stay text. There is no \`#\` comment.
|
|
151
167
|
|
|
152
|
-
Workflow: write the source, run \`yuhwa check file.
|
|
168
|
+
Workflow: write the source, run \`yuhwa check file.yu --json\` (or read the
|
|
153
169
|
\`diagnostics\` of \`render\`), fix every error and warning, then render. Done
|
|
154
170
|
when it reports 0 diagnostics; they name the fix ("did you mean ...").
|
|
155
171
|
|
|
@@ -196,7 +212,7 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
|
|
|
196
212
|
\`$a\`. \`name(x, "Label, with comma", b: y)\` stamps it out. Use one per
|
|
197
213
|
repeated shape of nodes instead of copying lines.
|
|
198
214
|
- Group: \`group id "Label" .class [props] { ... }\`, may nest. \`group "Label" {\`
|
|
199
|
-
gets a slug id. Edges connect nodes
|
|
215
|
+
gets a slug id. Edges connect nodes and panel ids (\`plan -> sales\`), never groups.
|
|
200
216
|
- Props: \`[key: value, key: "a, b", flag]\`; a bare flag means true, a bare
|
|
201
217
|
value names its key: \`[cylinder, amber, dashed]\`.
|
|
202
218
|
- Props on their own lines: a \`key: value\` line indented under a node, edge,
|
|
@@ -209,13 +225,14 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
|
|
|
209
225
|
\`\`\`
|
|
210
226
|
- Card: a node line ending in \`{\` takes body lines until a line that is only
|
|
211
227
|
\`}\`. It draws a header (label, \`meta\` right, \`caps\` small caps), a divider
|
|
212
|
-
and a monospace body.
|
|
228
|
+
and a monospace body. \`font-size\`/\`font-weight\`/\`text\` style the header;
|
|
229
|
+
\`body-size\`, \`body-weight\`, \`body-color\` and \`line-height\` style the body.
|
|
213
230
|
|
|
214
231
|
## Values
|
|
215
232
|
|
|
216
233
|
- \`color\` sets fill, border and text in one: \`[blue]\` or \`[color: blue]\`.
|
|
217
|
-
Palette: ${list(TONES)}; shades like blue-600; any CSS colour.
|
|
218
|
-
|
|
234
|
+
Palette: ${list(TONES)}; shades like blue-600; any CSS colour. The colour
|
|
235
|
+
props (${list(COLORS)}) take the same values and colour one part.
|
|
219
236
|
- Shapes: ${list(SHAPES)}.
|
|
220
237
|
- Line styles: ${list(ENUMS.style)}. Heads: ${list(ENUMS.head)}. Sides (\`exit\`, \`enter\`): ${list(ENUMS.exit)}.
|
|
221
238
|
- Themes: ${list(THEME_NAMES)}. Define one with \`theme brand [base: midnight, accent: orange]\`
|
|
@@ -231,6 +248,9 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
|
|
|
231
248
|
\`sub\` is a second, smaller line; \`icon\` an emoji before the label; \`link\`
|
|
232
249
|
makes a node clickable; \`flow: true\` animates an edge; \`constraint: false\`
|
|
233
250
|
keeps an edge out of the layout; \`shape: text\` is an annotation without a box.
|
|
251
|
+
\`below: <id>\`, \`above\`, \`right-of\`, \`left-of\` and \`rank\` place a node next to another
|
|
252
|
+
node without drawing an edge; do not use invisible edges for that. The \`max-width: <px>\` setting
|
|
253
|
+
wraps the ranks of a right or left diagram into rows that fit that width.
|
|
234
254
|
\`frame: <kind> <text>\` draws window chrome: ${list(registry.frames.keys())}.
|
|
235
255
|
|
|
236
256
|
## Card bodies
|
|
@@ -250,8 +270,12 @@ checks "checks" [meta: 42s, caps: true] {
|
|
|
250
270
|
|
|
251
271
|
Lines: text, \`left || right\` (right-aligned part), \`---\` divider, empty gap.
|
|
252
272
|
Rows: ${code(registry.rows.map((r) => r.syntax ?? r.kind))}; a \`|---|\` row makes a table header.
|
|
253
|
-
Inline markup (
|
|
254
|
-
|
|
273
|
+
Inline markup (in every text: labels, \`sub\`, edge labels, group and panel titles,
|
|
274
|
+
\`title\`, \`subtitle\`, \`footer\`): \`**bold**\`, \`*muted*\`, \`~~strike~~\`, \`\`code\`\`,
|
|
275
|
+
\`[[chip]]\` / \`[[green: chip]]\`, \`{red: text}\`, and styled spans
|
|
276
|
+
\`{color: red, size: 18, weight: 700, italic | text}\` (short: \`{red, bold | text}\`).
|
|
277
|
+
Text props on every element (node, edge label, group and panel title): \`text\`,
|
|
278
|
+
\`font-size\`, \`font-weight\`, \`italic\`; a panel's \`font-size\` scales all its text.
|
|
255
279
|
|
|
256
280
|
\`legend: .svc Service | --> async | red Deprecated\` and \`footer: a | b\` draw
|
|
257
281
|
strips under the diagram; a legend item starts with a class, colour or arrow.
|
|
@@ -285,10 +309,10 @@ ${panelLines}
|
|
|
285
309
|
|
|
286
310
|
## Imports
|
|
287
311
|
|
|
288
|
-
\`import "./shared.
|
|
312
|
+
\`import "./shared.yu"\` at top level pulls in another file's classes,
|
|
289
313
|
nodes, groups, edges, panels, variables and components; paths resolve against
|
|
290
314
|
the importing file, and the importing file wins on conflicts.
|
|
291
|
-
\`import { api, .svc as .service, $brand } from "./x.
|
|
315
|
+
\`import { api, .svc as .service, $brand } from "./x.yu"\` takes only those.
|
|
292
316
|
A file with \`export api, .svc\` (or \`export\` before a declaration:
|
|
293
317
|
\`export def ...\`, \`export $x: 1\`, \`export theme brand {\`) offers only those.
|
|
294
318
|
Custom themes come along with every import. Settings stay in their file unless
|
|
@@ -348,6 +372,363 @@ panel. \`yuhwa convert file.mmd\` prints the yuhwa source.
|
|
|
348
372
|
Keep labels short and put detail in \`sub\`. One colour per kind of thing,
|
|
349
373
|
defined once as a class. 5 to 20 nodes read best; split larger systems.
|
|
350
374
|
`;
|
|
375
|
+
// src/zoom.ts
|
|
376
|
+
/** Make the diagram inside `host` pannable and zoomable. Calling it again replaces the earlier viewer. */
|
|
377
|
+
function zoomable(host, opts = {}) {
|
|
378
|
+
host.yuhwaZoom?.destroy();
|
|
379
|
+
const doc = host.ownerDocument;
|
|
380
|
+
const win = doc.defaultView ?? window;
|
|
381
|
+
if (!doc.getElementById("yuhwa-zoom-css")) {
|
|
382
|
+
const css = doc.createElement("style");
|
|
383
|
+
css.id = "yuhwa-zoom-css";
|
|
384
|
+
css.textContent = `
|
|
385
|
+
.yuhwa-zoom{position:relative;display:block;overflow:hidden;touch-action:pan-x pan-y;-webkit-user-select:none;user-select:none;outline:none}
|
|
386
|
+
.yuhwa-zoom:focus-visible{box-shadow:0 0 0 2px Highlight}
|
|
387
|
+
.yuhwa-zoom[data-zoomed]{cursor:grab;touch-action:none}
|
|
388
|
+
.yuhwa-zoom[data-dragging]{cursor:grabbing}
|
|
389
|
+
.yuhwa-zoom-stage{transform-origin:0 0}
|
|
390
|
+
.yuhwa-zoom-stage.yuhwa-zoom-anim{transition:transform .18s ease-out}
|
|
391
|
+
.yuhwa-zoom-fixed .yuhwa-zoom-stage,.yuhwa-zoom:fullscreen .yuhwa-zoom-stage{height:100%;display:flex;align-items:center;justify-content:center}
|
|
392
|
+
.yuhwa-zoom-fixed .yuhwa-zoom-stage :is(svg,img),.yuhwa-zoom:fullscreen .yuhwa-zoom-stage :is(svg,img){max-width:100%;max-height:100%;width:auto;height:auto}
|
|
393
|
+
.yuhwa-zoom:fullscreen{background:var(--yuhwa-zoom-bg,Canvas)}
|
|
394
|
+
.yuhwa-zoom-stage img{-webkit-user-drag:none}
|
|
395
|
+
.yuhwa-zoom-bar{position:absolute;top:8px;right:8px;display:flex;align-items:center;gap:2px;padding:3px;border-radius:8px;background:color-mix(in srgb,Canvas 86%,transparent);box-shadow:0 1px 4px rgba(0,0,0,.18);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);opacity:0;transition:opacity .15s;font:500 12px/1 system-ui,sans-serif;color:CanvasText;cursor:default}
|
|
396
|
+
.yuhwa-zoom:hover .yuhwa-zoom-bar,.yuhwa-zoom:focus-within .yuhwa-zoom-bar,.yuhwa-zoom[data-zoomed] .yuhwa-zoom-bar{opacity:1}
|
|
397
|
+
@media (hover:none){.yuhwa-zoom-bar{opacity:1}}
|
|
398
|
+
.yuhwa-zoom-bar button{all:unset;box-sizing:border-box;min-width:28px;height:28px;padding:0 6px;display:grid;place-items:center;border-radius:6px;cursor:pointer;font-variant-numeric:tabular-nums}
|
|
399
|
+
.yuhwa-zoom-bar button:hover{background:color-mix(in srgb,CanvasText 10%,transparent)}
|
|
400
|
+
.yuhwa-zoom-bar button:focus-visible{outline:2px solid Highlight}
|
|
401
|
+
.yuhwa-zoom-bar button:disabled{opacity:.35;cursor:default;background:none}
|
|
402
|
+
.yuhwa-zoom-hint{position:absolute;left:50%;bottom:10px;transform:translateX(-50%);padding:5px 10px;border-radius:6px;background:rgba(20,20,20,.78);color:#fff;font:12px/1.3 system-ui,sans-serif;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .2s}
|
|
403
|
+
.yuhwa-zoom-hint[data-show]{opacity:1}
|
|
404
|
+
@media (prefers-reduced-motion:reduce){.yuhwa-zoom-stage.yuhwa-zoom-anim,.yuhwa-zoom-hint,.yuhwa-zoom-bar{transition:none}}`;
|
|
405
|
+
doc.head.append(css);
|
|
406
|
+
}
|
|
407
|
+
const min = opts.min ?? 1;
|
|
408
|
+
const max = Math.max(opts.max ?? 8, min);
|
|
409
|
+
let s = 1;
|
|
410
|
+
let x = 0;
|
|
411
|
+
let y = 0;
|
|
412
|
+
const addedTabIndex = !host.hasAttribute("tabindex");
|
|
413
|
+
const oldHeight = host.style.height;
|
|
414
|
+
host.classList.add("yuhwa-zoom");
|
|
415
|
+
if (opts.height) {
|
|
416
|
+
host.classList.add("yuhwa-zoom-fixed");
|
|
417
|
+
host.style.height = opts.height;
|
|
418
|
+
}
|
|
419
|
+
if (addedTabIndex) host.tabIndex = 0;
|
|
420
|
+
const stage = doc.createElement("div");
|
|
421
|
+
stage.className = "yuhwa-zoom-stage";
|
|
422
|
+
stage.append(...host.childNodes);
|
|
423
|
+
host.append(stage);
|
|
424
|
+
const icon = (d) => `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="${d}" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
|
|
425
|
+
const button = (label, html, onClick) => {
|
|
426
|
+
const b = doc.createElement("button");
|
|
427
|
+
b.type = "button";
|
|
428
|
+
b.title = label;
|
|
429
|
+
b.setAttribute("aria-label", label);
|
|
430
|
+
b.innerHTML = html;
|
|
431
|
+
b.addEventListener("click", (e) => {
|
|
432
|
+
e.stopPropagation();
|
|
433
|
+
onClick();
|
|
434
|
+
});
|
|
435
|
+
return b;
|
|
436
|
+
};
|
|
437
|
+
const bar = doc.createElement("div");
|
|
438
|
+
bar.className = "yuhwa-zoom-bar";
|
|
439
|
+
const minus = button("Zoom out (−)", icon("M3.5 8h9"), () => zoom(1 / 1.5, void 0, true));
|
|
440
|
+
const pct = button("Reset zoom (0)", "100%", () => reset());
|
|
441
|
+
const plus = button("Zoom in (+)", icon("M3.5 8h9M8 3.5v9"), () => zoom(1.5, void 0, true));
|
|
442
|
+
bar.append(minus, pct, plus);
|
|
443
|
+
if (!!(doc.fullscreenEnabled && host.requestFullscreen)) bar.append(button("Full screen", icon("M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"), () => doc.fullscreenElement === host ? doc.exitFullscreen() : host.requestFullscreen().catch(() => {})));
|
|
444
|
+
if (opts.controls !== false) host.append(bar);
|
|
445
|
+
const hint = doc.createElement("div");
|
|
446
|
+
hint.className = "yuhwa-zoom-hint";
|
|
447
|
+
hint.setAttribute("aria-hidden", "true");
|
|
448
|
+
hint.textContent = /Mac|iP/.test(win.navigator.platform) ? "Pinch or ⌘ + scroll to zoom" : "Ctrl + scroll to zoom";
|
|
449
|
+
host.append(hint);
|
|
450
|
+
let hintTimer = 0;
|
|
451
|
+
const showHint = () => {
|
|
452
|
+
hint.setAttribute("data-show", "");
|
|
453
|
+
win.clearTimeout(hintTimer);
|
|
454
|
+
hintTimer = win.setTimeout(() => hint.removeAttribute("data-show"), 1400);
|
|
455
|
+
};
|
|
456
|
+
const apply = (animate = false) => {
|
|
457
|
+
const w = host.clientWidth;
|
|
458
|
+
const h = host.clientHeight;
|
|
459
|
+
const ex = w - w * s;
|
|
460
|
+
const ey = h - h * s;
|
|
461
|
+
x = Math.min(Math.max(x, Math.min(0, ex)), Math.max(0, ex));
|
|
462
|
+
y = Math.min(Math.max(y, Math.min(0, ey)), Math.max(0, ey));
|
|
463
|
+
stage.classList.toggle("yuhwa-zoom-anim", animate);
|
|
464
|
+
stage.style.transform = s === 1 && !x && !y ? "" : `translate(${x}px, ${y}px) scale(${s})`;
|
|
465
|
+
host.toggleAttribute("data-zoomed", s > 1.001);
|
|
466
|
+
const label = `${Math.round(s * 100)}%`;
|
|
467
|
+
if (pct.textContent !== label) pct.textContent = label;
|
|
468
|
+
minus.disabled = s <= min + .001;
|
|
469
|
+
plus.disabled = s >= max - .001;
|
|
470
|
+
};
|
|
471
|
+
const zoom = (factor, at, animate = false) => {
|
|
472
|
+
const p = at ?? {
|
|
473
|
+
x: host.clientWidth / 2,
|
|
474
|
+
y: host.clientHeight / 2
|
|
475
|
+
};
|
|
476
|
+
const next = Math.min(max, Math.max(min, s * factor));
|
|
477
|
+
x = p.x - (p.x - x) * next / s;
|
|
478
|
+
y = p.y - (p.y - y) * next / s;
|
|
479
|
+
s = next;
|
|
480
|
+
apply(animate);
|
|
481
|
+
};
|
|
482
|
+
const reset = (animate = true) => {
|
|
483
|
+
s = 1;
|
|
484
|
+
x = y = 0;
|
|
485
|
+
apply(animate);
|
|
486
|
+
};
|
|
487
|
+
const local = (e) => {
|
|
488
|
+
const r = host.getBoundingClientRect();
|
|
489
|
+
return {
|
|
490
|
+
x: e.clientX - r.left,
|
|
491
|
+
y: e.clientY - r.top
|
|
492
|
+
};
|
|
493
|
+
};
|
|
494
|
+
const onWheel = (e) => {
|
|
495
|
+
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? host.clientHeight : 1;
|
|
496
|
+
const dx = e.deltaX * unit;
|
|
497
|
+
const dy = e.deltaY * unit;
|
|
498
|
+
if (e.ctrlKey || e.metaKey || opts.wheel || doc.fullscreenElement === host) {
|
|
499
|
+
e.preventDefault();
|
|
500
|
+
zoom(Math.exp(-dy * (Math.abs(dy) < 50 ? .01 : .002)), local(e));
|
|
501
|
+
} else if (s > 1.001) {
|
|
502
|
+
const ox = x;
|
|
503
|
+
const oy = y;
|
|
504
|
+
x -= dx;
|
|
505
|
+
y -= dy;
|
|
506
|
+
apply();
|
|
507
|
+
if (x !== ox || y !== oy) e.preventDefault();
|
|
508
|
+
} else if (Math.abs(dy) > Math.abs(dx)) showHint();
|
|
509
|
+
};
|
|
510
|
+
const points = /* @__PURE__ */ new Map();
|
|
511
|
+
let pinch = null;
|
|
512
|
+
let moved = 0;
|
|
513
|
+
const pinchState = () => {
|
|
514
|
+
const [a, b] = [...points.values()];
|
|
515
|
+
return {
|
|
516
|
+
d: Math.hypot(a.x - b.x, a.y - b.y) || 1,
|
|
517
|
+
x: (a.x + b.x) / 2,
|
|
518
|
+
y: (a.y + b.y) / 2
|
|
519
|
+
};
|
|
520
|
+
};
|
|
521
|
+
const onDown = (e) => {
|
|
522
|
+
if (e.pointerType === "mouse" && e.button !== 0 || bar.contains(e.target)) return;
|
|
523
|
+
if (points.size === 0) moved = 0;
|
|
524
|
+
points.set(e.pointerId, local(e));
|
|
525
|
+
if (points.size === 2) {
|
|
526
|
+
pinch = pinchState();
|
|
527
|
+
for (const id of points.keys()) host.setPointerCapture?.(id);
|
|
528
|
+
} else if (points.size === 1 && s > 1.001) {
|
|
529
|
+
host.setPointerCapture?.(e.pointerId);
|
|
530
|
+
host.setAttribute("data-dragging", "");
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
const onMove = (e) => {
|
|
534
|
+
const last = points.get(e.pointerId);
|
|
535
|
+
if (!last) return;
|
|
536
|
+
const p = local(e);
|
|
537
|
+
points.set(e.pointerId, p);
|
|
538
|
+
if (points.size >= 2 && pinch) {
|
|
539
|
+
const now = pinchState();
|
|
540
|
+
x += now.x - pinch.x;
|
|
541
|
+
y += now.y - pinch.y;
|
|
542
|
+
zoom(now.d / pinch.d, now);
|
|
543
|
+
moved += Math.abs(now.d - pinch.d) + Math.abs(now.x - pinch.x) + Math.abs(now.y - pinch.y);
|
|
544
|
+
pinch = now;
|
|
545
|
+
} else if (host.hasAttribute("data-dragging")) {
|
|
546
|
+
x += p.x - last.x;
|
|
547
|
+
y += p.y - last.y;
|
|
548
|
+
moved += Math.abs(p.x - last.x) + Math.abs(p.y - last.y);
|
|
549
|
+
apply();
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
const onUp = (e) => {
|
|
553
|
+
points.delete(e.pointerId);
|
|
554
|
+
pinch = points.size >= 2 ? pinchState() : null;
|
|
555
|
+
if (points.size === 0) host.removeAttribute("data-dragging");
|
|
556
|
+
};
|
|
557
|
+
const onClick = (e) => {
|
|
558
|
+
if (moved > 4 && !bar.contains(e.target)) {
|
|
559
|
+
e.preventDefault();
|
|
560
|
+
e.stopPropagation();
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
const onDblClick = (e) => {
|
|
564
|
+
if (bar.contains(e.target)) return;
|
|
565
|
+
e.preventDefault();
|
|
566
|
+
if (s >= max - .001) reset();
|
|
567
|
+
else zoom(2, local(e), true);
|
|
568
|
+
};
|
|
569
|
+
const onKey = (e) => {
|
|
570
|
+
if (e.target !== host || e.altKey || e.ctrlKey || e.metaKey) return;
|
|
571
|
+
const step = 60;
|
|
572
|
+
const moves = {
|
|
573
|
+
ArrowLeft: [step, 0],
|
|
574
|
+
ArrowRight: [-60, 0],
|
|
575
|
+
ArrowUp: [0, step],
|
|
576
|
+
ArrowDown: [0, -60]
|
|
577
|
+
};
|
|
578
|
+
if (e.key === "+" || e.key === "=") zoom(1.5, void 0, true);
|
|
579
|
+
else if (e.key === "-" || e.key === "_") zoom(1 / 1.5, void 0, true);
|
|
580
|
+
else if (e.key === "0") reset();
|
|
581
|
+
else if (moves[e.key] && s > 1.001) {
|
|
582
|
+
const ox = x;
|
|
583
|
+
const oy = y;
|
|
584
|
+
x += moves[e.key][0];
|
|
585
|
+
y += moves[e.key][1];
|
|
586
|
+
apply(true);
|
|
587
|
+
if (x === ox && y === oy) return;
|
|
588
|
+
} else return;
|
|
589
|
+
e.preventDefault();
|
|
590
|
+
};
|
|
591
|
+
const onDragStart = (e) => e.preventDefault();
|
|
592
|
+
const off = new AbortController();
|
|
593
|
+
const signal = off.signal;
|
|
594
|
+
host.addEventListener("wheel", onWheel, {
|
|
595
|
+
passive: false,
|
|
596
|
+
signal
|
|
597
|
+
});
|
|
598
|
+
host.addEventListener("pointerdown", onDown, { signal });
|
|
599
|
+
host.addEventListener("pointermove", onMove, { signal });
|
|
600
|
+
host.addEventListener("pointerup", onUp, { signal });
|
|
601
|
+
host.addEventListener("pointercancel", onUp, { signal });
|
|
602
|
+
host.addEventListener("click", onClick, {
|
|
603
|
+
capture: true,
|
|
604
|
+
signal
|
|
605
|
+
});
|
|
606
|
+
host.addEventListener("dblclick", onDblClick, { signal });
|
|
607
|
+
host.addEventListener("keydown", onKey, { signal });
|
|
608
|
+
host.addEventListener("dragstart", onDragStart, { signal });
|
|
609
|
+
doc.addEventListener("fullscreenchange", () => reset(false), { signal });
|
|
610
|
+
const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => apply());
|
|
611
|
+
resize?.observe(host);
|
|
612
|
+
apply();
|
|
613
|
+
const api = {
|
|
614
|
+
get scale() {
|
|
615
|
+
return s;
|
|
616
|
+
},
|
|
617
|
+
zoom: (factor, at) => zoom(factor, at, true),
|
|
618
|
+
reset: () => reset(),
|
|
619
|
+
destroy() {
|
|
620
|
+
off.abort();
|
|
621
|
+
resize?.disconnect();
|
|
622
|
+
win.clearTimeout(hintTimer);
|
|
623
|
+
bar.remove();
|
|
624
|
+
hint.remove();
|
|
625
|
+
if (stage.parentNode === host) {
|
|
626
|
+
host.append(...stage.childNodes);
|
|
627
|
+
stage.remove();
|
|
628
|
+
}
|
|
629
|
+
host.classList.remove("yuhwa-zoom", "yuhwa-zoom-fixed");
|
|
630
|
+
host.removeAttribute("data-zoomed");
|
|
631
|
+
host.removeAttribute("data-dragging");
|
|
632
|
+
host.style.height = oldHeight;
|
|
633
|
+
if (addedTabIndex) host.removeAttribute("tabindex");
|
|
634
|
+
delete host.yuhwaZoom;
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
host.yuhwaZoom = api;
|
|
638
|
+
return api;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* The `height` of a `zoom` flag or attribute: empty means the diagram's own
|
|
642
|
+
* height, a bare number means pixels, anything else is a CSS length.
|
|
643
|
+
*/
|
|
644
|
+
function zoomHeight(value) {
|
|
645
|
+
const v = value?.trim();
|
|
646
|
+
if (!v || v === "true") return void 0;
|
|
647
|
+
return /^\d+(\.\d+)?$/.test(v) ? `${v}px` : v;
|
|
648
|
+
}
|
|
649
|
+
// src/cli/blocks.ts
|
|
650
|
+
/**
|
|
651
|
+
* Finds the diagrams in a Markdown page for `yuhwa check` and `yuhwa render`:
|
|
652
|
+
* fenced blocks in one of `languages` and the `<!--yuhwa name … -->` comments
|
|
653
|
+
* that `yuhwa md` writes. Fences in other languages are skipped whole, so a
|
|
654
|
+
* ```markdown fence that shows a yuhwa block is not checked.
|
|
655
|
+
*/
|
|
656
|
+
/** fence languages read by default; `--lang` overrides them */
|
|
657
|
+
const MD_LANGUAGES = ["yuhwa", "yu"];
|
|
658
|
+
const isMarkdown = (file) => /\.(md|mdx|markdown)$/i.test(file);
|
|
659
|
+
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)(.*)$/;
|
|
660
|
+
function pageBlocks(md, languages = MD_LANGUAGES) {
|
|
661
|
+
const lines = md.split("\n");
|
|
662
|
+
const blocks = [];
|
|
663
|
+
for (let i = 0; i < lines.length; i++) {
|
|
664
|
+
const line = lines[i].replace(/\r$/, "");
|
|
665
|
+
let close;
|
|
666
|
+
let lang;
|
|
667
|
+
let meta = "";
|
|
668
|
+
let m = line.match(FENCE);
|
|
669
|
+
if (m) {
|
|
670
|
+
const fence = m[1];
|
|
671
|
+
const closer = new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\s*$`);
|
|
672
|
+
close = (l) => closer.test(l);
|
|
673
|
+
lang = m[2];
|
|
674
|
+
meta = m[3].trim();
|
|
675
|
+
} else if (m = line.match(COMMENT_OPEN)) {
|
|
676
|
+
close = (l) => l.trim() === "-->";
|
|
677
|
+
lang = "comment";
|
|
678
|
+
meta = m[1] ?? "";
|
|
679
|
+
} else continue;
|
|
680
|
+
let j = i + 1;
|
|
681
|
+
while (j < lines.length && !close(lines[j].replace(/\r$/, ""))) j++;
|
|
682
|
+
if (j >= lines.length) break;
|
|
683
|
+
if (lang === "comment" || languages.includes(lang) && !/(^|\s)no-render(\s|$)/.test(meta)) {
|
|
684
|
+
const name = meta.split(/\s+/).find((w) => w && w !== "no-code");
|
|
685
|
+
blocks.push({
|
|
686
|
+
index: blocks.length,
|
|
687
|
+
lang,
|
|
688
|
+
...name ? { name } : {},
|
|
689
|
+
line: i + 1,
|
|
690
|
+
source: lines.slice(i + 1, j).join("\n")
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
i = j;
|
|
694
|
+
}
|
|
695
|
+
return blocks;
|
|
696
|
+
}
|
|
697
|
+
/** parses `--lang yuhwa,yu` */
|
|
698
|
+
function parseLanguages(v) {
|
|
699
|
+
if (typeof v !== "string") return MD_LANGUAGES;
|
|
700
|
+
const langs = v.split(",").map((s) => s.trim()).filter(Boolean);
|
|
701
|
+
if (!langs.length) throw new Error("--lang: give at least one fence language, e.g. --lang yuhwa,yu");
|
|
702
|
+
return langs;
|
|
703
|
+
}
|
|
704
|
+
// src/cli/view.ts
|
|
705
|
+
/**
|
|
706
|
+
* A standalone HTML page that shows one diagram in a full-window pan and zoom
|
|
707
|
+
* viewer: the SVG and the viewer script inline, nothing to load. Written by
|
|
708
|
+
* `yuhwa render -o x.html` and served by `yuhwa serve` under `/view`.
|
|
709
|
+
*/
|
|
710
|
+
/** the viewer script, stringified once */
|
|
711
|
+
const SCRIPT = `(${zoomable})(document.getElementById('diagram'), { height: '100%', wheel: true });`;
|
|
712
|
+
function viewerPage(svg, opts = {}) {
|
|
713
|
+
const title = esc(opts.title ?? "diagram");
|
|
714
|
+
const bg = opts.background && isSafeCss(opts.background) ? opts.background : "#ffffff";
|
|
715
|
+
return `<!doctype html>
|
|
716
|
+
<html lang="en">
|
|
717
|
+
<head>
|
|
718
|
+
<meta charset="utf-8">
|
|
719
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
720
|
+
<title>${title}</title>
|
|
721
|
+
<style>html,body{margin:0;height:100%;background:${bg}}#diagram{height:100%;--yuhwa-zoom-bg:${bg}}</style>
|
|
722
|
+
</head>
|
|
723
|
+
<body>
|
|
724
|
+
<div id="diagram" role="group" aria-label="${title}">
|
|
725
|
+
${svg}
|
|
726
|
+
</div>
|
|
727
|
+
<script${opts.nonce ? ` nonce="${esc(opts.nonce)}"` : ""}>${SCRIPT}<\/script>
|
|
728
|
+
</body>
|
|
729
|
+
</html>
|
|
730
|
+
`;
|
|
731
|
+
}
|
|
351
732
|
// src/cli/server.ts
|
|
352
733
|
/**
|
|
353
734
|
* HTTP render service. Any tool that can show an image URL can show a diagram:
|
|
@@ -355,6 +736,8 @@ defined once as a class. 5 to 20 nodes read best; split larger systems.
|
|
|
355
736
|
* GET /svg?src=<urlencoded source>[&theme=midnight]
|
|
356
737
|
* GET /svg/<base64url source>[.svg]
|
|
357
738
|
* GET /yuhwa/svg/<deflate + base64url source> (Kroki-compatible)
|
|
739
|
+
* GET /view?src=…, /view/<base64url>, /yuhwa/view/<deflate + base64url>
|
|
740
|
+
* the same as a page with pan and zoom
|
|
358
741
|
* POST /svg body: source (yuhwa, Mermaid or JSON)
|
|
359
742
|
* POST /check body: source → { ok, format, diagnostics }
|
|
360
743
|
* GET /llms.txt language reference for AI tools
|
|
@@ -365,6 +748,13 @@ const MAX_BODY = 1 << 20;
|
|
|
365
748
|
function encodeSource(source) {
|
|
366
749
|
return deflateSync(Buffer.from(source, "utf8"), { level: 9 }).toString("base64url");
|
|
367
750
|
}
|
|
751
|
+
/** the hosted viewer: a static page that decodes the hash, so it needs no server */
|
|
752
|
+
const VIEWER = "https://ph1p.github.io/yuhwa/view/";
|
|
753
|
+
/** a link to a page that pans and zooms `source`: your `yuhwa serve` at `base`, else the hosted viewer */
|
|
754
|
+
function viewUrl(source, base) {
|
|
755
|
+
const enc = encodeSource(source);
|
|
756
|
+
return base ? `${base.replace(/\/$/, "")}/yuhwa/view/${enc}` : `${VIEWER}#z=${enc}`;
|
|
757
|
+
}
|
|
368
758
|
function decodeSource(encoded, compressed) {
|
|
369
759
|
const buf = Buffer.from(encoded.replace(/\.svg$/, ""), "base64url");
|
|
370
760
|
if (!compressed) return buf.toString("utf8");
|
|
@@ -405,7 +795,8 @@ const HOME = (origin) => `<!doctype html><meta charset="utf-8"><title>yuhwa rend
|
|
|
405
795
|
<ul>
|
|
406
796
|
<li><code>GET /svg?src=…&theme=…</code> URL-encoded source</li>
|
|
407
797
|
<li><code>GET /svg/<base64url></code> base64url source</li>
|
|
408
|
-
<li><code>GET /yuhwa/svg/<deflate+base64url></code> Kroki-compatible; <code>yuhwa url file.
|
|
798
|
+
<li><code>GET /yuhwa/svg/<deflate+base64url></code> Kroki-compatible; <code>yuhwa url file.yu</code> prints one</li>
|
|
799
|
+
<li><code>GET /view?src=…</code>, <code>/view/<base64url></code>, <code>/yuhwa/view/<deflate+base64url></code> the same diagram as a page you can pan and zoom; <code>yuhwa url --view --base …</code> prints one</li>
|
|
409
800
|
<li><code>POST /svg</code> source as body</li>
|
|
410
801
|
<li><code>POST /check</code> JSON diagnostics</li>
|
|
411
802
|
<li><code>GET /llms.txt</code> language reference for AI tools</li>
|
|
@@ -430,6 +821,19 @@ function handler(req, res) {
|
|
|
430
821
|
if (cache && !errors.length) res.setHeader("cache-control", "public, max-age=31536000, immutable");
|
|
431
822
|
res.end(r.svg);
|
|
432
823
|
};
|
|
824
|
+
const sendView = (source) => {
|
|
825
|
+
const r = render$1(source, { theme });
|
|
826
|
+
const nonce = randomBytes(16).toString("base64");
|
|
827
|
+
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
828
|
+
res.setHeader("content-security-policy", `default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'nonce-${nonce}'`);
|
|
829
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
830
|
+
res.setHeader("x-yuhwa-format", r.format);
|
|
831
|
+
res.end(viewerPage(r.svg, {
|
|
832
|
+
title: r.diagram.settings.title ?? "yuhwa diagram",
|
|
833
|
+
nonce,
|
|
834
|
+
background: r.layout.theme.background
|
|
835
|
+
}));
|
|
836
|
+
};
|
|
433
837
|
const sendJson = (status, body) => {
|
|
434
838
|
res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body, null, 2));
|
|
435
839
|
};
|
|
@@ -447,6 +851,14 @@ function handler(req, res) {
|
|
|
447
851
|
if (m) return sendSvg(decodeSource(m[1], false), true);
|
|
448
852
|
m = path.match(/^\/yuhwa\/svg\/([\w-]+)$/);
|
|
449
853
|
if (m) return sendSvg(decodeSource(m[1], true), true);
|
|
854
|
+
if (path === "/view") {
|
|
855
|
+
const src = url.searchParams.get("src");
|
|
856
|
+
return src === null ? fail(400, "missing ?src=") : sendView(src);
|
|
857
|
+
}
|
|
858
|
+
m = path.match(/^\/view\/([\w-]+)$/);
|
|
859
|
+
if (m) return sendView(decodeSource(m[1], false));
|
|
860
|
+
m = path.match(/^\/yuhwa\/view\/([\w-]+)$/);
|
|
861
|
+
if (m) return sendView(decodeSource(m[1], true));
|
|
450
862
|
}
|
|
451
863
|
if (req.method === "POST" && [
|
|
452
864
|
"/svg",
|
|
@@ -463,7 +875,10 @@ function handler(req, res) {
|
|
|
463
875
|
format: r.format,
|
|
464
876
|
diagnostics: r.diagnostics
|
|
465
877
|
});
|
|
466
|
-
}
|
|
878
|
+
}).catch((e) => {
|
|
879
|
+
if (!res.headersSent) fail(e.status ?? 400, e.message);
|
|
880
|
+
else res.end();
|
|
881
|
+
});
|
|
467
882
|
return;
|
|
468
883
|
}
|
|
469
884
|
fail(404, `not found: ${req.method} ${path} (see GET /)`);
|
|
@@ -532,7 +947,8 @@ function saveEditorFiles(file, mainName, block, loaded, update) {
|
|
|
532
947
|
* custom element:
|
|
533
948
|
*
|
|
534
949
|
* <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
|
|
535
|
-
* <yuhwa-diagram src="docs/arch.
|
|
950
|
+
* <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
|
|
951
|
+
* <yuhwa-diagram src="big.yu" zoom="480px"></yuhwa-diagram> // pan and zoom
|
|
536
952
|
* el.source = 'a -> b' // re-renders
|
|
537
953
|
*/
|
|
538
954
|
const SELECTOR = "pre > code.language-yuhwa, pre > code.lang-yuhwa, pre.yuhwa, div.yuhwa:not([data-rendered])";
|
|
@@ -555,7 +971,7 @@ const IMPORT_RE = /^\s*import\s+(?:\{[^}]*\}\s*from\s+)?"([^"]+)"/gm;
|
|
|
555
971
|
/**
|
|
556
972
|
* Fetches every file that `source` imports, and what those import, so
|
|
557
973
|
* `render` can resolve them synchronously. Paths join against `file` (a URL
|
|
558
|
-
* path such as `/docs/arch.
|
|
974
|
+
* path such as `/docs/arch.yu`); a file that fails to load is left out and
|
|
559
975
|
* shows up as a diagnostic on its import line.
|
|
560
976
|
*/
|
|
561
977
|
async function fetchImports(source, file, load = fetchText) {
|
|
@@ -592,6 +1008,7 @@ function run(root = document, opts = {}) {
|
|
|
592
1008
|
out.className = "yuhwa";
|
|
593
1009
|
out.dataset.rendered = "true";
|
|
594
1010
|
out.dataset.source = source;
|
|
1011
|
+
let ok = false;
|
|
595
1012
|
try {
|
|
596
1013
|
const r = render(source, {
|
|
597
1014
|
theme: host.dataset.theme,
|
|
@@ -600,17 +1017,28 @@ function run(root = document, opts = {}) {
|
|
|
600
1017
|
out.innerHTML = r.svg;
|
|
601
1018
|
fit(out.querySelector("svg"));
|
|
602
1019
|
for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
|
|
1020
|
+
ok = true;
|
|
603
1021
|
} catch (e) {
|
|
604
1022
|
out.textContent = `yuhwa error: ${e.message}`;
|
|
605
1023
|
out.style.color = "crimson";
|
|
606
1024
|
}
|
|
607
1025
|
host.replaceWith(out);
|
|
1026
|
+
if (ok && host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
|
|
608
1027
|
});
|
|
609
1028
|
}
|
|
610
1029
|
const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
|
|
611
|
-
/**
|
|
1030
|
+
/**
|
|
1031
|
+
* <yuhwa-diagram [theme] [src] [zoom[=height]] [wheel]>source</yuhwa-diagram>;
|
|
1032
|
+
* fires `yuhwa:render` with the diagnostics. `zoom` makes it a pan and zoom
|
|
1033
|
+
* viewer, `wheel` lets the plain mouse wheel zoom it.
|
|
1034
|
+
*/
|
|
612
1035
|
var YuhwaDiagram = class extends Base {
|
|
613
|
-
static observedAttributes = [
|
|
1036
|
+
static observedAttributes = [
|
|
1037
|
+
"theme",
|
|
1038
|
+
"src",
|
|
1039
|
+
"zoom",
|
|
1040
|
+
"wheel"
|
|
1041
|
+
];
|
|
614
1042
|
#source = null;
|
|
615
1043
|
#fetched = null;
|
|
616
1044
|
#request = 0;
|
|
@@ -660,9 +1088,15 @@ var YuhwaDiagram = class extends Base {
|
|
|
660
1088
|
file: this.#file,
|
|
661
1089
|
resolve: (p) => files[p]
|
|
662
1090
|
});
|
|
1091
|
+
this.yuhwaZoom?.destroy();
|
|
663
1092
|
this.innerHTML = r.svg;
|
|
664
1093
|
fit(this.querySelector("svg"));
|
|
665
|
-
this.
|
|
1094
|
+
const zoom = this.getAttribute("zoom");
|
|
1095
|
+
this.setAttribute("role", zoom === null ? "img" : "group");
|
|
1096
|
+
if (zoom !== null) zoomable(this, {
|
|
1097
|
+
height: zoomHeight(zoom),
|
|
1098
|
+
wheel: this.hasAttribute("wheel")
|
|
1099
|
+
});
|
|
666
1100
|
if (!this.hasAttribute("aria-label") || this.dataset.autoLabel) {
|
|
667
1101
|
const t = r.diagram.settings.title;
|
|
668
1102
|
if (t) this.setAttribute("aria-label", t), this.dataset.autoLabel = "1";
|
|
@@ -693,13 +1127,14 @@ if (typeof document !== "undefined") {
|
|
|
693
1127
|
const HELP = `yuhwa — diagrams that look good and stay where you put them
|
|
694
1128
|
|
|
695
1129
|
Usage
|
|
696
|
-
yuhwa render <file|-> [-o out.svg] [--theme name]
|
|
697
|
-
yuhwa check <file|-...> [--json]
|
|
698
|
-
yuhwa
|
|
699
|
-
yuhwa
|
|
700
|
-
yuhwa
|
|
1130
|
+
yuhwa render <file|-> [-o out.svg|out.html] [--html] [--theme name] [--block n]
|
|
1131
|
+
yuhwa check <file|-...> [--json] [--lang yuhwa,yu]
|
|
1132
|
+
yuhwa lint <file...> [--fix] [--json] [--lang yuhwa,yu]
|
|
1133
|
+
yuhwa convert <file.mmd|file.json|-> [-o out.yu]
|
|
1134
|
+
yuhwa md <file.md...> [--out-dir diagrams] [--dark] [--keep-fences] [--view[=base]]
|
|
1135
|
+
yuhwa edit <file.yu|file.md> [--block n] [--port 4747] [--no-open]
|
|
701
1136
|
yuhwa serve [--port 4749] [--host 127.0.0.1]
|
|
702
|
-
yuhwa url <file|-> [--base http://localhost:4749]
|
|
1137
|
+
yuhwa url <file|-> [--base http://localhost:4749] [--view]
|
|
703
1138
|
yuhwa <file> same as yuhwa render <file>
|
|
704
1139
|
yuhwa guide language reference for AI tools (alias: llms)
|
|
705
1140
|
yuhwa themes
|
|
@@ -708,15 +1143,27 @@ Usage
|
|
|
708
1143
|
|
|
709
1144
|
Input can be yuhwa, a Mermaid flowchart or JSON; the format is detected.
|
|
710
1145
|
|
|
711
|
-
render Render one diagram to SVG (stdout unless -o is given).
|
|
1146
|
+
render Render one diagram to SVG (stdout unless -o is given). From a
|
|
1147
|
+
Markdown file it renders block --block n (from 0, default 0).
|
|
1148
|
+
-o x.html or --html writes a page that pans and zooms instead.
|
|
712
1149
|
check Validate without rendering. --json prints machine-readable diagnostics.
|
|
1150
|
+
A .md/.mdx/.markdown file is checked block by block: every
|
|
1151
|
+
\`\`\`yuhwa and \`\`\`yu fence (--lang picks others) and every
|
|
1152
|
+
<!--yuhwa --> comment, with line numbers in the Markdown file.
|
|
1153
|
+
lint Everything check reports, plus unused classes, variables and
|
|
1154
|
+
components, edges drawn twice and unformatted files. Fails on any
|
|
1155
|
+
finding, warnings included. --fix formats .yu files in place.
|
|
713
1156
|
convert Turn a Mermaid flowchart or JSON diagram into yuhwa source.
|
|
714
1157
|
md Render every yuhwa block in Markdown files, write the SVGs and
|
|
715
|
-
insert or update the image reference below each block.
|
|
1158
|
+
insert or update the image reference below each block. --view
|
|
1159
|
+
links each image to a page that pans and zooms it (the hosted
|
|
1160
|
+
viewer, or --view=<base> for your own \`serve\`).
|
|
716
1161
|
edit Open the visual editor in your browser. Drag boxes, bend edges,
|
|
717
1162
|
move labels; saving writes the layout back into your file.
|
|
718
1163
|
serve HTTP render service: <img src="http://host/svg?src=..."> anywhere.
|
|
719
1164
|
url Print an embeddable image URL for a diagram (for \`serve\`).
|
|
1165
|
+
--view prints a link to a page that pans and zooms it instead:
|
|
1166
|
+
the hosted viewer, or your \`serve\` with --base.
|
|
720
1167
|
guide Print the language reference (same as llms.txt). AI agents: read
|
|
721
1168
|
this first, then write source and run \`check --json\` until it is clean.
|
|
722
1169
|
`;
|
|
@@ -737,7 +1184,8 @@ function parseArgs(argv) {
|
|
|
737
1184
|
"block",
|
|
738
1185
|
"port",
|
|
739
1186
|
"host",
|
|
740
|
-
"base"
|
|
1187
|
+
"base",
|
|
1188
|
+
"lang"
|
|
741
1189
|
].includes(k)) a[k] = argv[++i];
|
|
742
1190
|
else a[k] = true;
|
|
743
1191
|
} else a._.push(s);
|
|
@@ -751,12 +1199,22 @@ function printDiagnostics(file, ds, prefix = "") {
|
|
|
751
1199
|
function cmdRender(a) {
|
|
752
1200
|
const file = a._[1];
|
|
753
1201
|
if (!file) throw new Error("render: missing input file");
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
1202
|
+
let source = readInput(file);
|
|
1203
|
+
let at = 0;
|
|
1204
|
+
if (isMarkdown(file)) {
|
|
1205
|
+
const blocks = blocksOf(a, file, source);
|
|
1206
|
+
const n = Number(str(a.block) ?? 0);
|
|
1207
|
+
const b = blocks[n];
|
|
1208
|
+
if (!b) throw new Error(blocks.length ? `${file} has no yuhwa block #${n} (it has ${blocks.length})` : `${file} has no yuhwa blocks`);
|
|
1209
|
+
({source, line: at} = b);
|
|
1210
|
+
}
|
|
1211
|
+
const r = renderAs(a, file, source);
|
|
1212
|
+
printDiagnostics(file, shiftLines(r.diagnostics, at));
|
|
1213
|
+
const out = str(a.out);
|
|
1214
|
+
writeOut(out, !!a.html || /\.html?$/i.test(out ?? "") ? viewerPage(r.svg, {
|
|
1215
|
+
title: r.diagram.settings.title ?? basename(file),
|
|
1216
|
+
background: r.layout.theme.background
|
|
1217
|
+
}) : r.svg + "\n");
|
|
760
1218
|
if (r.diagnostics.some((d) => d.severity === "error")) process.exitCode = 1;
|
|
761
1219
|
}
|
|
762
1220
|
const fileOpts = (file) => ({
|
|
@@ -770,14 +1228,74 @@ function writeOut(out, text) {
|
|
|
770
1228
|
writeFileSync(out, text);
|
|
771
1229
|
process.stderr.write(`wrote ${out}\n`);
|
|
772
1230
|
}
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
1231
|
+
/** block diagnostics carry block lines; `at` is the opening fence's page line */
|
|
1232
|
+
const shiftLines = (ds, at) => at ? ds.map((d) => ({
|
|
1233
|
+
...d,
|
|
1234
|
+
line: at + Math.max(d.line, 1)
|
|
1235
|
+
})) : ds;
|
|
1236
|
+
/** render with the command's `--theme` and the file's import resolver */
|
|
1237
|
+
const renderAs = (a, file, source) => render$1(source, {
|
|
1238
|
+
theme: str(a.theme),
|
|
1239
|
+
...fileOpts(file)
|
|
1240
|
+
});
|
|
1241
|
+
/** the yuhwa blocks of a Markdown page, honouring `--lang` */
|
|
1242
|
+
const blocksOf = (a, file, source = readInput(file)) => pageBlocks(source, parseLanguages(a.lang));
|
|
1243
|
+
/** `check` on a Markdown page: one report for the page, one entry per block */
|
|
1244
|
+
function checkPage(file, a) {
|
|
1245
|
+
const blocks = blocksOf(a, file);
|
|
1246
|
+
const diagnostics = [];
|
|
1247
|
+
const counts = {
|
|
1248
|
+
nodes: 0,
|
|
1249
|
+
edges: 0,
|
|
1250
|
+
groups: 0
|
|
1251
|
+
};
|
|
1252
|
+
const entries = blocks.map((b) => {
|
|
1253
|
+
const r = renderAs(a, file, b.source);
|
|
1254
|
+
for (const d of shiftLines(r.diagnostics, b.line)) diagnostics.push({
|
|
1255
|
+
...d,
|
|
1256
|
+
block: b.index
|
|
780
1257
|
});
|
|
1258
|
+
const { nodes, edges, groups } = r.diagram;
|
|
1259
|
+
counts.nodes += nodes.size;
|
|
1260
|
+
counts.edges += edges.length;
|
|
1261
|
+
counts.groups += groups.size;
|
|
1262
|
+
const { source: _, ...where } = b;
|
|
1263
|
+
return {
|
|
1264
|
+
...where,
|
|
1265
|
+
ok: !r.diagnostics.some((d) => d.severity === "error"),
|
|
1266
|
+
format: r.format,
|
|
1267
|
+
nodes: nodes.size,
|
|
1268
|
+
edges: edges.length,
|
|
1269
|
+
groups: groups.size
|
|
1270
|
+
};
|
|
1271
|
+
});
|
|
1272
|
+
const ok = entries.every((e) => e.ok);
|
|
1273
|
+
if (!ok) process.exitCode = 1;
|
|
1274
|
+
if (!a.json) {
|
|
1275
|
+
printDiagnostics(file, diagnostics);
|
|
1276
|
+
process.stderr.write(blocks.length ? `${file}: ${ok ? "ok" : "errors"} (markdown, ${blocks.length} block(s), ${diagnostics.length} diagnostic(s))\n` : `${file}: ok (markdown, no yuhwa blocks found)\n`);
|
|
1277
|
+
}
|
|
1278
|
+
return {
|
|
1279
|
+
file,
|
|
1280
|
+
ok,
|
|
1281
|
+
format: "markdown",
|
|
1282
|
+
...counts,
|
|
1283
|
+
diagnostics,
|
|
1284
|
+
blocks: entries,
|
|
1285
|
+
...blocks.length ? {} : { note: "no yuhwa blocks found" }
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
/** run `one` per input file; `--json` prints one report, or an array for several files */
|
|
1289
|
+
function perFile(a, cmd, one) {
|
|
1290
|
+
const files = a._.slice(1);
|
|
1291
|
+
if (!files.length) throw new Error(`${cmd}: missing input file`);
|
|
1292
|
+
const reports = files.map(one);
|
|
1293
|
+
if (a.json) process.stdout.write(JSON.stringify(reports.length === 1 ? reports[0] : reports, null, 2) + "\n");
|
|
1294
|
+
}
|
|
1295
|
+
function cmdCheck(a) {
|
|
1296
|
+
perFile(a, "check", (file) => {
|
|
1297
|
+
if (isMarkdown(file)) return checkPage(file, a);
|
|
1298
|
+
const r = renderAs(a, file, readInput(file));
|
|
781
1299
|
const ok = !r.diagnostics.some((d) => d.severity === "error");
|
|
782
1300
|
if (!ok) process.exitCode = 1;
|
|
783
1301
|
const { nodes, edges, groups } = r.diagram;
|
|
@@ -795,7 +1313,48 @@ function cmdCheck(a) {
|
|
|
795
1313
|
diagnostics: r.diagnostics
|
|
796
1314
|
};
|
|
797
1315
|
});
|
|
798
|
-
|
|
1316
|
+
}
|
|
1317
|
+
/** `check` plus hygiene and formatting; exit code 1 on any finding */
|
|
1318
|
+
function cmdLint(a) {
|
|
1319
|
+
const lintOne = (source, file, at = 0) => {
|
|
1320
|
+
const r = renderAs(a, file, source);
|
|
1321
|
+
return shiftLines([...r.diagnostics, ...r.format === "yuhwa" ? tidy(source, r.diagram) : []], at);
|
|
1322
|
+
};
|
|
1323
|
+
perFile(a, "lint", (file) => {
|
|
1324
|
+
let diagnostics;
|
|
1325
|
+
let fixed = false;
|
|
1326
|
+
if (isMarkdown(file)) diagnostics = blocksOf(a, file).flatMap((b) => lintOne(b.source, file, b.line).map((d) => ({
|
|
1327
|
+
...d,
|
|
1328
|
+
block: b.index
|
|
1329
|
+
})));
|
|
1330
|
+
else {
|
|
1331
|
+
const source = readInput(file);
|
|
1332
|
+
diagnostics = lintOne(source, file);
|
|
1333
|
+
const formatted = format(source);
|
|
1334
|
+
if (formatted !== source) {
|
|
1335
|
+
if (a.fix && file !== "-") {
|
|
1336
|
+
writeFileSync(file, formatted);
|
|
1337
|
+
fixed = true;
|
|
1338
|
+
} else diagnostics.push({
|
|
1339
|
+
line: 1,
|
|
1340
|
+
message: "Not formatted: run yuhwa lint --fix",
|
|
1341
|
+
severity: "warning"
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
diagnostics.sort((x, y) => x.line - y.line);
|
|
1346
|
+
if (diagnostics.length) process.exitCode = 1;
|
|
1347
|
+
if (!a.json) {
|
|
1348
|
+
printDiagnostics(file, diagnostics);
|
|
1349
|
+
process.stderr.write(`${file}: ${diagnostics.length ? `${diagnostics.length} finding(s)` : "clean"}${fixed ? ", formatted" : ""}\n`);
|
|
1350
|
+
}
|
|
1351
|
+
return {
|
|
1352
|
+
file,
|
|
1353
|
+
ok: !diagnostics.length,
|
|
1354
|
+
...fixed ? { fixed } : {},
|
|
1355
|
+
diagnostics
|
|
1356
|
+
};
|
|
1357
|
+
});
|
|
799
1358
|
}
|
|
800
1359
|
function cmdConvert(a) {
|
|
801
1360
|
const file = a._[1];
|
|
@@ -808,8 +1367,10 @@ function cmdConvert(a) {
|
|
|
808
1367
|
function cmdUrl(a) {
|
|
809
1368
|
const file = a._[1];
|
|
810
1369
|
if (!file) throw new Error("url: missing input file");
|
|
1370
|
+
const source = readInput(file);
|
|
1371
|
+
if (a.view) return void process.stdout.write(`${viewUrl(source, str(a.base))}\n`);
|
|
811
1372
|
const base = (str(a.base) ?? "http://localhost:4749").replace(/\/$/, "");
|
|
812
|
-
process.stdout.write(`${base}/yuhwa/svg/${encodeSource(
|
|
1373
|
+
process.stdout.write(`${base}/yuhwa/svg/${encodeSource(source)}\n`);
|
|
813
1374
|
}
|
|
814
1375
|
function cmdMd(a) {
|
|
815
1376
|
const files = a._.slice(1);
|
|
@@ -821,6 +1382,7 @@ function cmdMd(a) {
|
|
|
821
1382
|
baseName: basename(file, extname(file)).toLowerCase(),
|
|
822
1383
|
dark: !!a.dark,
|
|
823
1384
|
keepFences: !!a["keep-fences"],
|
|
1385
|
+
view: a.view ? (src) => viewUrl(src, str(a.view)) : void 0,
|
|
824
1386
|
...fileOpts(file)
|
|
825
1387
|
});
|
|
826
1388
|
for (const d of res.diagnostics) process.stderr.write(`${file} [${d.block}]:${d.line}: ${d.severity}: ${d.message}\n`);
|
|
@@ -856,7 +1418,7 @@ function openBrowser(url) {
|
|
|
856
1418
|
function cmdEdit(a) {
|
|
857
1419
|
const file = a._[1];
|
|
858
1420
|
if (!file) throw new Error("edit: missing file");
|
|
859
|
-
const isMd =
|
|
1421
|
+
const isMd = isMarkdown(file);
|
|
860
1422
|
if (!existsSync(file)) {
|
|
861
1423
|
if (isMd) throw new Error(`${file} does not exist`);
|
|
862
1424
|
writeFileSync(file, "direction: right\n\nhello \"Hello\" -> world \"World\"\n");
|
|
@@ -942,6 +1504,7 @@ function main() {
|
|
|
942
1504
|
else if (cmd === "md") cmdMd(a);
|
|
943
1505
|
else if (cmd === "edit") cmdEdit(a);
|
|
944
1506
|
else if (cmd === "check") cmdCheck(a);
|
|
1507
|
+
else if (cmd === "lint") cmdLint(a);
|
|
945
1508
|
else if (cmd === "convert") cmdConvert(a);
|
|
946
1509
|
else if (cmd === "url") cmdUrl(a);
|
|
947
1510
|
else if (cmd === "serve") serve(Number(str(a.port) ?? 4749), str(a.host) ?? "127.0.0.1");
|