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/dist/plugin.d.ts CHANGED
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * Register a plugin with `use` from `yuhwa`.
10
10
  */
11
- import { $t as SANS, A as setLineProp, Bt as inkColor, Ct as RowKind, Dt as optionKind, E as onlyColor, Et as YuhwaPlugin, Ft as renderHead, Gt as segsW, Ht as parseInline, It as InkColors, Jt as tspans, Kt as sumW, Lt as Seg, M as splitTrailingProps, N as unquote, Nt as MarkerKind, O as parseProps, Ot as perPass, P as Box, Pt as ShapeKind, Qt as RAMPS, R as Diagram, Rt as esc, St as RowCtx, Tt as StatementKind, Ut as plain, Vt as nodeInk, Wt as renderSegs, Xt as LineStyle, Y as Layout, Yt as COLOR_TOKEN, Z as NodeDecl, Zt as MONO, _t as Decoration, a as effectiveProps, an as ThemeInput, at as PartEdit, bt as PanelKind, c as posNum, cn as cssHex, d as normalizeShape, dn as isSafeCss, dt as Side, et as PanelHandle, f as portOn, fn as isSafeLink, gn as resolveColor, i as edgeWidthOf, in as Theme, it as PartChange, j as setTrailingProp, k as serializeProps, kt as recolor, l as resolveNodeStyle, m as shapePath, mn as ramp, n as table, nt as PanelPart, o as lineStyle, on as bool, ot as Point, p as rectPath, qt as textEl, r as dashFor, s as num, sn as createTheme, st as Props, t as definePlugin, un as isColor, vn as Measure, vt as FrameKind, wt as RowPaint, xt as PanelOption, yn as approxMeasure, yt as PanelCtx, zt as f } from "./plugin-NSkNyoUj.js";
11
+ import { $t as SANS, A as setLineProp, Bt as inkColor, Ct as RowKind, Dt as optionKind, E as onlyColor, Et as YuhwaPlugin, Ft as renderHead, Gt as segsW, Ht as parseInline, It as InkColors, Jt as tspans, Kt as sumW, Lt as Seg, M as splitTrailingProps, N as unquote, Nt as MarkerKind, O as parseProps, Ot as perPass, P as Box, Pt as ShapeKind, Qt as RAMPS, R as Diagram, Rt as esc, Sn as approxMeasure, St as RowCtx, Tt as StatementKind, Ut as plain, Vt as nodeInk, Wt as renderSegs, Xt as LineStyle, Y as Layout, Yt as COLOR_TOKEN, Z as NodeDecl, Zt as MONO, _n as ramp, _t as Decoration, a as effectiveProps, an as ThemeInput, at as PartEdit, bt as PanelKind, c as posNum, cn as cssHex, d as normalizeShape, dt as Side, et as PanelHandle, f as portOn, fn as isColor, hn as isSafeLink, i as edgeWidthOf, in as Theme, it as PartChange, j as setTrailingProp, k as serializeProps, kt as recolor, l as resolveNodeStyle, m as shapePath, mn as isSafeCss, n as table, nt as PanelPart, o as lineStyle, on as bool, ot as Point, p as rectPath, qt as textEl, r as dashFor, s as num, sn as createTheme, st as Props, t as definePlugin, vt as FrameKind, wt as RowPaint, xn as Measure, xt as PanelOption, yn as resolveColor, yt as PanelCtx, zt as f } from "./plugin-NMP_uf1a.js";
12
12
  export { type Box, COLOR_TOKEN, type Decoration, type Diagram, type FrameKind, type InkColors, type Layout, type LineStyle, MONO, type MarkerKind, type Measure, type NodeDecl, type PanelCtx, type PanelHandle, type PanelKind, type PanelOption, type PanelPart, type PartChange, type PartEdit, type Point, type Props, RAMPS, type RowCtx, type RowKind, type RowPaint, SANS, type Seg, type ShapeKind, type Side, type StatementKind, type Theme, type ThemeInput, type YuhwaPlugin, approxMeasure, bool, createTheme, cssHex, dashFor, definePlugin, edgeWidthOf, effectiveProps, esc, f, inkColor, isColor, isSafeCss, isSafeLink, lineStyle, nodeInk, normalizeShape, num, onlyColor, optionKind, parseInline, parseProps, perPass, plain, portOn, posNum, ramp, recolor, rectPath, renderHead, renderSegs, resolveColor, resolveNodeStyle, segsW, serializeProps, setLineProp, setTrailingProp, shapePath, splitTrailingProps, sumW, table, textEl, tspans, unquote };
package/dist/plugin.js CHANGED
@@ -1 +1,3 @@
1
- export { jt as COLOR_TOKEN, Mt as MONO, Nt as RAMPS, Pt as SANS, n as approxMeasure, zt as bool, Bt as createTheme, Vt as cssHex, Z as dashFor, t as definePlugin, $ as edgeWidthOf, et as effectiveProps, ft as esc, pt as f, mt as inkColor, Wt as isColor, Gt as isSafeCss, Kt as isSafeLink, tt as lineStyle, gt as nodeInk, B as normalizeShape, nt as num, _ as onlyColor, i as optionKind, _t as parseInline, y as parseProps, a as perPass, yt as plain, V as portOn, it as posNum, Jt as ramp, o as recolor, H as rectPath, Y as renderHead, bt as renderSegs, Xt as resolveColor, ot as resolveNodeStyle, Ct as segsW, S as serializeProps, C as setLineProp, w as setTrailingProp, W as shapePath, T as splitTrailingProps, Dt as sumW, $t as table, Ot as textEl, At as tspans, E as unquote } from "./plugin-Bs4eiAuz.js";
1
+ import { At as SANS, Ct as sumW, Dt as COLOR_TOKEN, Et as tspans, F as portOn, Ft as bool, G as renderHead, I as rectPath, It as createTheme, Jt as resolveColor, Kt as ramp, Lt as cssHex, Ot as MONO, P as normalizeShape, Q as num, R as shapePath, Ut as isSafeCss, Vt as isColor, Wt as isSafeLink, X as effectiveProps, Y as edgeWidthOf, Z as lineStyle, _ as setTrailingProp, ct as esc, en as table, et as posNum, f as parseProps, ft as nodeInk, g as setLineProp, gt as renderSegs, h as serializeProps, ht as plain, kt as RAMPS, lt as f, nt as resolveNodeStyle, pt as parseInline, q as dashFor, u as onlyColor, ut as inkColor, v as splitTrailingProps, wt as textEl, y as unquote, yt as segsW } from "./parse--ljBMU60.js";
2
+ import { a as perPass, i as optionKind, n as approxMeasure, o as recolor, t as definePlugin } from "./plugin-CitzbblK.js";
3
+ export { COLOR_TOKEN, MONO, RAMPS, SANS, approxMeasure, bool, createTheme, cssHex, dashFor, definePlugin, edgeWidthOf, effectiveProps, esc, f, inkColor, isColor, isSafeCss, isSafeLink, lineStyle, nodeInk, normalizeShape, num, onlyColor, optionKind, parseInline, parseProps, perPass, plain, portOn, posNum, ramp, recolor, rectPath, renderHead, renderSegs, resolveColor, resolveNodeStyle, segsW, serializeProps, setLineProp, setTrailingProp, shapePath, splitTrailingProps, sumW, table, textEl, tspans, unquote };
@@ -0,0 +1,299 @@
1
+ import { r as __exportAll } from "./rolldown-runtime-CEjnN5Q1.js";
2
+ import { y as unquote } from "./parse--ljBMU60.js";
3
+ // src/raster.ts
4
+ /**
5
+ * Drawing a rendered SVG into a canvas. No side effects on import, so the
6
+ * editor and other apps can take it from `yuhwa` without the browser runtime.
7
+ *
8
+ * A browser loads an SVG image in isolation: it cannot use the page's web
9
+ * fonts. `svgToCanvas` therefore embeds the fonts the diagram names, as
10
+ * `data:` URLs in an `@font-face` rule inside the SVG, before drawing it.
11
+ */
12
+ var raster_exports = /* @__PURE__ */ __exportAll({ swapForRaster: () => swapForRaster });
13
+ /** natural size of a rendered SVG: its width and height, else its viewBox */
14
+ function svgSize(svg) {
15
+ const root = svg.match(/<svg\b[^>]*>/)?.[0] ?? "";
16
+ const attr = (name) => Number(root.match(new RegExp(`\\s${name}="([\\d.]+)"`))?.[1]);
17
+ const box = root.match(/\sviewBox="([^"]+)"/)?.[1].trim().split(/[\s,]+/).map(Number) ?? [];
18
+ const width = attr("width") || box[2] || 300;
19
+ return {
20
+ width,
21
+ height: attr("height") || (box[2] && box[3] ? width * box[3] / box[2] : 150)
22
+ };
23
+ }
24
+ const decode = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([\da-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&amp;/g, "&");
25
+ /** the values of a presentation attribute or CSS property across the SVG, decoded and trimmed */
26
+ function svgProp(svg, name) {
27
+ return [...svg.matchAll(new RegExp(`${name}(?:="([^"]*)"|\\s*:\\s*([^;"}]+))`, "g"))].map((m) => decode(m[1] ?? m[2]).trim());
28
+ }
29
+ /** lower-cased family names the SVG asks for, from font-family attributes and styles */
30
+ function svgFamilies(svg) {
31
+ const out = /* @__PURE__ */ new Set();
32
+ for (const v of svgProp(svg, "font-family")) for (const f of v.split(",")) out.add(unquote(f).toLowerCase());
33
+ return out;
34
+ }
35
+ const WEIGHT_WORDS = {
36
+ normal: 400,
37
+ bold: 700
38
+ };
39
+ function fontUsage(svg) {
40
+ const chars = /* @__PURE__ */ new Set();
41
+ const text = svg.replace(/<style\b[^>]*>[\s\S]*?<\/style>/g, "").match(/>[^<]+</g) ?? [];
42
+ for (const t of text) for (const ch of decode(t.slice(1, -1))) chars.add(ch.codePointAt(0));
43
+ const weights = /* @__PURE__ */ new Set([400]);
44
+ for (const v of svgProp(svg, "font-weight")) {
45
+ const w = WEIGHT_WORDS[v] ?? Number(v);
46
+ if (w > 0) weights.add(w);
47
+ }
48
+ const italic = svgProp(svg, "font-style").some((v) => /^(?:italic|oblique)/.test(v));
49
+ return {
50
+ families: svgFamilies(svg),
51
+ chars,
52
+ weights,
53
+ italic
54
+ };
55
+ }
56
+ /** a face's weight range: `400`, `100 900` (variable font) or `bold` */
57
+ function weightRange(weight) {
58
+ const [lo, hi = lo] = (weight ?? "normal").trim().split(/\s+/).map((v) => WEIGHT_WORDS[v] ?? (Number(v) || 400));
59
+ return [lo, hi];
60
+ }
61
+ /** how badly a face's weight range serves weight `w`, in the order CSS font matching tries faces; 0 is exact */
62
+ function weightMiss(w, [lo, hi]) {
63
+ if (w >= lo && w <= hi) return 0;
64
+ const v = w < lo ? lo : hi;
65
+ const d = Math.abs(v - w);
66
+ if (w >= 400 && w <= 500) return (v > w && v <= 500 ? 1e3 : v < w ? 2e3 : 3e3) + d;
67
+ return ((w < 400 ? v < w : v > w) ? 1e3 : 2e3) + d;
68
+ }
69
+ /**
70
+ * The faces a browser would pick for the SVG's weights and styles, per family
71
+ * and unicode-range. A family offered in nine weights embeds only the ones used.
72
+ */
73
+ function pickFaces(faces, { weights, italic }) {
74
+ const groups = /* @__PURE__ */ new Map();
75
+ for (const f of faces) {
76
+ const key = `${f.family.toLowerCase()}|${f.unicodeRange ?? ""}`;
77
+ groups.set(key, [...groups.get(key) ?? [], f]);
78
+ }
79
+ const out = /* @__PURE__ */ new Set();
80
+ const isItalic = (f) => /italic|oblique/i.test(f.style ?? "");
81
+ for (const group of groups.values()) for (const wantItalic of italic ? [false, true] : [false]) {
82
+ const styled = group.filter((f) => isItalic(f) === wantItalic);
83
+ const pool = styled.length ? styled : group;
84
+ for (const w of weights) {
85
+ let best = pool[0];
86
+ for (const f of pool) if (weightMiss(w, weightRange(f.weight)) < weightMiss(w, weightRange(best.weight))) best = f;
87
+ out.add(best);
88
+ }
89
+ }
90
+ return faces.filter((f) => out.has(f));
91
+ }
92
+ /** does a CSS unicode-range (`U+0000-00FF, U+0131, U+02??`) cover any of `chars`? */
93
+ function inUnicodeRange(range, chars) {
94
+ if (!range?.trim()) return true;
95
+ const spans = range.split(",").map((part) => {
96
+ const [a, b] = part.trim().replace(/^u\+/i, "").split("-");
97
+ if (b !== void 0) return [parseInt(a, 16), parseInt(b.replace(/^u\+/i, ""), 16)];
98
+ return [parseInt(a.replace(/\?/g, "0"), 16), parseInt(a.replace(/\?/g, "f"), 16)];
99
+ });
100
+ for (const c of chars) if (spans.some(([lo, hi]) => c >= lo && c <= hi)) return true;
101
+ return false;
102
+ }
103
+ /** first downloadable `url(...)` in an @font-face src, resolved against `base` */
104
+ function srcUrl(src, base) {
105
+ const m = src.match(/url\(\s*(['"]?)(.*?)\1\s*\)/);
106
+ if (!m) return void 0;
107
+ try {
108
+ return new URL(m[2], base).href;
109
+ } catch {
110
+ return;
111
+ }
112
+ }
113
+ function faceFrom(get, base) {
114
+ const url = srcUrl(get("src"), base);
115
+ const family = unquote(get("font-family"));
116
+ if (!url || !family) return void 0;
117
+ return {
118
+ family,
119
+ url,
120
+ weight: get("font-weight").trim() || void 0,
121
+ style: get("font-style").trim() || void 0,
122
+ unicodeRange: get("unicode-range").trim() || void 0
123
+ };
124
+ }
125
+ /** @font-face rules in CSS text, for stylesheets the page may not read (cross-origin) */
126
+ function parseFontFaces(css, base) {
127
+ const out = [];
128
+ for (const m of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
129
+ const body = m[1];
130
+ const get = (prop) => body.match(new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`, "i"))?.[1] ?? "";
131
+ const face = faceFrom(get, base);
132
+ if (face) out.push(face);
133
+ }
134
+ return out;
135
+ }
136
+ /** cache entries kept per map; the oldest goes first, so base64 fonts do not pile up */
137
+ const CACHE_SIZE = 32;
138
+ /** one promise per key, so a stylesheet or font file is fetched once per page */
139
+ function cached(map, key, load) {
140
+ let p = map.get(key);
141
+ if (p) return p;
142
+ map.set(key, p = load());
143
+ if (map.size > CACHE_SIZE) map.delete(map.keys().next().value);
144
+ return p;
145
+ }
146
+ const cssCache = /* @__PURE__ */ new Map();
147
+ let walking;
148
+ /** every @font-face the page declares; diagrams drawn together share one walk of the stylesheets */
149
+ function pageFonts() {
150
+ return walking ??= walkSheets().finally(() => walking = void 0);
151
+ }
152
+ /** readable sheets directly, cross-origin ones fetched */
153
+ async function walkSheets() {
154
+ if (typeof document === "undefined") return [];
155
+ const out = [];
156
+ const pending = [];
157
+ const walk = (rules, base) => {
158
+ for (const rule of Array.from(rules)) if (rule instanceof CSSFontFaceRule) {
159
+ const face = faceFrom((p) => rule.style.getPropertyValue(p), base);
160
+ if (face) out.push(face);
161
+ } else if (rule instanceof CSSImportRule) {
162
+ if (rule.styleSheet) sheet(rule.styleSheet);
163
+ } else if ("cssRules" in rule) walk(rule.cssRules, base);
164
+ };
165
+ const sheet = (s) => {
166
+ const base = s.href ?? location.href;
167
+ try {
168
+ walk(s.cssRules, base);
169
+ } catch {
170
+ const href = s.href;
171
+ if (!href) return;
172
+ pending.push(cached(cssCache, href, () => fetch(href).then((r) => r.ok ? r.text() : "").then((css) => parseFontFaces(css, href)).catch(() => [])));
173
+ }
174
+ };
175
+ for (const s of Array.from(document.styleSheets)) sheet(s);
176
+ for (const faces of await Promise.all(pending)) out.push(...faces);
177
+ return out;
178
+ }
179
+ function base64(bytes) {
180
+ const native = bytes.toBase64;
181
+ if (native) return native.call(bytes);
182
+ let bin = "";
183
+ for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
184
+ return btoa(bin);
185
+ }
186
+ const fileCache = /* @__PURE__ */ new Map();
187
+ /** a font file as a data: URL, typed by its extension; undefined when it cannot be fetched (CORS, 404) */
188
+ function fontData(url) {
189
+ if (url.startsWith("data:")) return Promise.resolve(url);
190
+ return cached(fileCache, url, () => fetch(url).then((r) => r.ok ? r.arrayBuffer() : Promise.reject(new Error(String(r.status)))).then((buf) => {
191
+ return `data:font/${url.match(/\.(woff2?|ttf|otf)(?:[?#]|$)/i)?.[1].toLowerCase() ?? "woff2"};base64,${base64(new Uint8Array(buf))}`;
192
+ }).catch(() => void 0));
193
+ }
194
+ const cssString = (s) => `"${s.replace(/["\\<>]/g, "")}"`;
195
+ const cssValue = (s) => s.replace(/[;{}<>"\\]/g, "");
196
+ /**
197
+ * Embeds the fonts the SVG names as an `@font-face` `<style>` inside it.
198
+ * Fonts it cannot fetch are skipped: the image then falls back to system fonts.
199
+ */
200
+ async function embedFonts(svg, fonts = "page") {
201
+ const usage = fontUsage(svg);
202
+ const wanted = pickFaces((fonts === "page" ? await pageFonts() : fonts).filter((f) => usage.families.has(f.family.toLowerCase()) && inUnicodeRange(f.unicodeRange, usage.chars)), usage);
203
+ const byUrl = /* @__PURE__ */ new Map();
204
+ for (const f of wanted) {
205
+ const prev = byUrl.get(f.url);
206
+ if (!prev) byUrl.set(f.url, f);
207
+ else {
208
+ const [a, b] = [weightRange(prev.weight), weightRange(f.weight)];
209
+ byUrl.set(f.url, {
210
+ ...prev,
211
+ weight: `${Math.min(a[0], b[0])} ${Math.max(a[1], b[1])}`
212
+ });
213
+ }
214
+ }
215
+ const css = (await Promise.all([...byUrl.values()].map(async (f) => {
216
+ const data = await fontData(f.url);
217
+ if (!data) return "";
218
+ return `@font-face{font-family:${cssString(f.family)};src:url(${data});` + (f.weight ? `font-weight:${cssValue(f.weight)};` : "") + (f.style ? `font-style:${cssValue(f.style)};` : "") + (f.unicodeRange ? `unicode-range:${cssValue(f.unicodeRange)};` : "") + "}";
219
+ }))).join("");
220
+ if (!css) return svg;
221
+ return svg.replace(/<svg\b[^>]*>/, (open) => `${open}<style>${css}</style>`);
222
+ }
223
+ /**
224
+ * Loads the page's web fonts that the SVG names, in the weights and styles
225
+ * it uses. Text is measured when the diagram renders, and a font that has
226
+ * not loaded yet is measured with its fallback. Resolves true when a font
227
+ * finished loading that was not ready before: render again for exact boxes.
228
+ */
229
+ async function loadFonts(svg) {
230
+ const fonts = typeof document === "undefined" ? void 0 : document.fonts;
231
+ if (!fonts) return false;
232
+ const { families, chars, weights, italic } = fontUsage(svg);
233
+ const text = String.fromCodePoint(...chars) || "a";
234
+ const specs = [];
235
+ for (const family of families) for (const w of weights) for (const style of italic ? ["normal", "italic"] : ["normal"]) specs.push(`${style} ${w} 16px ${cssString(family)}`);
236
+ const missing = specs.filter((s) => {
237
+ try {
238
+ return !fonts.check(s, text);
239
+ } catch {
240
+ return false;
241
+ }
242
+ });
243
+ if (!missing.length) return false;
244
+ return (await Promise.all(missing.map((s) => fonts.load(s, text).catch(() => [])))).some((faces) => faces.length > 0);
245
+ }
246
+ /**
247
+ * Draws an SVG string, such as `render(...).svg`, into a canvas. The page's
248
+ * web fonts that the diagram names are embedded first (see `fonts`).
249
+ */
250
+ async function svgToCanvas(svg, opts = {}) {
251
+ const { width, height } = svgSize(svg);
252
+ const scale = opts.scale ?? (typeof devicePixelRatio === "number" && devicePixelRatio > 0 ? devicePixelRatio : 1);
253
+ const fonts = opts.fonts ?? "page";
254
+ const source = fonts === false ? svg : await embedFonts(svg, fonts);
255
+ const url = URL.createObjectURL(new Blob([source], { type: "image/svg+xml" }));
256
+ const img = new Image();
257
+ img.src = url;
258
+ try {
259
+ await img.decode();
260
+ } finally {
261
+ URL.revokeObjectURL(url);
262
+ }
263
+ const canvas = opts.canvas ?? document.createElement("canvas");
264
+ canvas.width = Math.max(1, Math.round(width * scale));
265
+ canvas.height = Math.max(1, Math.round(height * scale));
266
+ const ctx = canvas.getContext("2d");
267
+ if (!ctx) throw new Error("yuhwa: no 2d canvas context");
268
+ if (opts.background) {
269
+ ctx.fillStyle = opts.background;
270
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
271
+ }
272
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
273
+ return canvas;
274
+ }
275
+ /**
276
+ * Draws `svg` and swaps the drawing in for `node`: a `<canvas>`, or for
277
+ * `png` an `<img>` of its PNG (a `blob:` URL; revoke it when the image goes),
278
+ * sized to the diagram. Nothing is swapped when `node` left the page or
279
+ * `current()` says a newer draw came.
280
+ */
281
+ async function swapForRaster(node, svg, mode, label, current = () => true) {
282
+ const canvas = await svgToCanvas(svg);
283
+ const stale = () => !current() || !node.isConnected;
284
+ if (stale()) return;
285
+ let out = canvas;
286
+ if (mode === "png") {
287
+ const blob = await new Promise((done) => canvas.toBlob(done, "image/png"));
288
+ if (!blob) throw new Error("the canvas gave no PNG");
289
+ if (stale()) return;
290
+ const img = new Image();
291
+ img.src = URL.createObjectURL(blob);
292
+ img.alt = label;
293
+ out = img;
294
+ } else canvas.setAttribute("role", "img"), canvas.setAttribute("aria-label", label);
295
+ out.style.width = `${svgSize(svg).width}px`;
296
+ node.replaceWith(out);
297
+ return out;
298
+ }
299
+ export { svgFamilies as a, swapForRaster as c, raster_exports as i, embedFonts as n, svgSize as o, loadFonts as r, svgToCanvas as s, base64 as t };
package/dist/remark.d.ts CHANGED
@@ -10,6 +10,6 @@
10
10
  * A fence with `no-render` (```yuhwa no-render) stays a code block.
11
11
  * ```yuhwa file="diagrams/arch.yu" renders that file instead of the block.
12
12
  */
13
- import { t as YuhwaDocsOptions } from "./figure-QAwSU1Ry.js";
13
+ import { t as YuhwaDocsOptions } from "./figure-BLHfxz_e.js";
14
14
  export default function remarkYuhwa(opts?: YuhwaDocsOptions): (tree: any, file?: any) => void;
15
15
  export { type YuhwaDocsOptions, remarkYuhwa };
package/dist/remark.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as wantsRender, n as renderBlock, o as zoomTag } from "./node-CLu2Pp_2.js";
1
+ import { n as renderBlock, o as wantsRender, s as zoomTag } from "./node-CkrQnPFb.js";
2
2
  // src/integrations/remark.ts
3
3
  /**
4
4
  * remark plugin: replaces ```yuhwa code blocks with a rendered figure.
@@ -0,0 +1,37 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esmMin = (fn, res, err) => () => {
7
+ if (err) throw err[0];
8
+ try {
9
+ return fn && (res = fn(fn = 0)), res;
10
+ } catch (e) {
11
+ throw err = [e], e;
12
+ }
13
+ };
14
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
15
+ var __exportAll = (all, flags) => {
16
+ let target = Object.setPrototypeOf({}, null);
17
+ for (var name in all) __defProp(target, name, {
18
+ get: all[name],
19
+ enumerable: true
20
+ });
21
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
22
+ return flags & 2 ? target : Object.preventExtensions(target);
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
27
+ desc = __getOwnPropDesc(from, key);
28
+ __defProp(to, key, {
29
+ get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
30
+ enumerable: !desc || desc.enumerable
31
+ });
32
+ }
33
+ }
34
+ return to;
35
+ };
36
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ export { __toCommonJS as i, __esmMin as n, __exportAll as r, __commonJSMin as t };
@@ -1,40 +1,6 @@
1
- import { n as YuhwaService, r as applyChange, t as SEMANTIC_LEGEND } from "./service-D7DNWBAU.js";
2
- // \0rolldown/runtime.js
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esmMin = (fn, res, err) => () => {
8
- if (err) throw err[0];
9
- try {
10
- return fn && (res = fn(fn = 0)), res;
11
- } catch (e) {
12
- throw err = [e], e;
13
- }
14
- };
15
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
16
- var __exportAll = (all, flags) => {
17
- let target = Object.setPrototypeOf({}, null);
18
- for (var name in all) __defProp(target, name, {
19
- get: all[name],
20
- enumerable: true
21
- });
22
- if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
23
- return flags & 2 ? target : Object.preventExtensions(target);
24
- };
25
- var __copyProps = (to, from, except, desc) => {
26
- if (from && typeof from === "object" || typeof from === "function") {
27
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
28
- desc = __getOwnPropDesc(from, key);
29
- __defProp(to, key, {
30
- get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
31
- enumerable: !desc || desc.enumerable
32
- });
33
- }
34
- }
35
- return to;
36
- };
37
- var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ import { i as __toCommonJS, n as __esmMin, r as __exportAll, t as __commonJSMin } from "./rolldown-runtime-CEjnN5Q1.js";
2
+ import { n as YuhwaService, r as applyChange, t as SEMANTIC_LEGEND } from "./service-C60VdeKS.js";
3
+ import { s as isMarkdown } from "./src-NCXCTK_4.js";
38
4
  // ../../node_modules/.pnpm/vscode-jsonrpc@10.0.0/node_modules/vscode-jsonrpc/lib/common/is.js
39
5
  var require_is$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
40
6
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -9764,7 +9730,10 @@ function startServer(connection, opts = {}) {
9764
9730
  resolve: (p) => docs.get(p) ?? opts.readFile?.(p),
9765
9731
  files: () => [...docs.keys()]
9766
9732
  });
9733
+ const pages = /* @__PURE__ */ new Map();
9767
9734
  const text = (uri) => docs.get(toPath(uri)) ?? "";
9735
+ const isPage = (uri) => isMarkdown(toPath(uri));
9736
+ const pageText = (uri) => pages.get(toPath(uri));
9768
9737
  let pull = false;
9769
9738
  let refresh = false;
9770
9739
  let watch = false;
@@ -9786,6 +9755,7 @@ function startServer(connection, opts = {}) {
9786
9755
  };
9787
9756
  const changed = (uri, src) => {
9788
9757
  const path = toPath(uri);
9758
+ if (isMarkdown(path)) return void (src === void 0 ? pages.delete(path) : pages.set(path, src));
9789
9759
  if (src === void 0) {
9790
9760
  docs.delete(path);
9791
9761
  uris.delete(path);
@@ -9852,7 +9822,7 @@ function startServer(connection, opts = {}) {
9852
9822
  connection.onDidOpenTextDocument((p) => changed(p.textDocument.uri, p.textDocument.text));
9853
9823
  connection.onDidChangeTextDocument((p) => {
9854
9824
  if (!p.contentChanges.length) return;
9855
- changed(p.textDocument.uri, p.contentChanges.reduce((t, ch) => applyChange(t, ch), text(p.textDocument.uri)));
9825
+ changed(p.textDocument.uri, p.contentChanges.reduce((t, ch) => applyChange(t, ch), pageText(p.textDocument.uri) ?? text(p.textDocument.uri)));
9856
9826
  });
9857
9827
  connection.onDidCloseTextDocument((p) => changed(p.textDocument.uri, void 0));
9858
9828
  connection.onDidChangeWatchedFiles(() => {
@@ -9860,47 +9830,55 @@ function startServer(connection, opts = {}) {
9860
9830
  validate();
9861
9831
  });
9862
9832
  connection.onDidChangeConfiguration(() => {});
9863
- connection.languages.diagnostics.on((p) => ({
9833
+ const yu = (none, f) => (p) => {
9834
+ const uri = p.textDocument.uri;
9835
+ return isPage(uri) ? none : f(p, text(uri), toPath(uri));
9836
+ };
9837
+ connection.languages.diagnostics.on(yu({
9864
9838
  kind: "full",
9865
- items: service.diagnostics(text(p.textDocument.uri), toPath(p.textDocument.uri))
9866
- }));
9867
- connection.onDocumentFormatting((p) => service.format(text(p.textDocument.uri)));
9868
- connection.onDocumentOnTypeFormatting((p) => service.onType(text(p.textDocument.uri), p.position, p.ch));
9869
- connection.onCompletion((p) => service.completion(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri)));
9870
- connection.onHover((p) => service.hover(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri)));
9871
- connection.onDefinition((p) => {
9872
- const t = service.definition(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri));
9839
+ items: []
9840
+ }, (_, src, path) => ({
9841
+ kind: "full",
9842
+ items: service.diagnostics(src, path)
9843
+ })));
9844
+ connection.onDocumentFormatting((p) => isPage(p.textDocument.uri) ? service.formatPage(pageText(p.textDocument.uri) ?? "") : service.format(text(p.textDocument.uri)));
9845
+ connection.onRequest("yuhwa/formatMarkdown", (p) => service.formatPage(p.text));
9846
+ connection.onDocumentOnTypeFormatting(yu([], (p, src) => service.onType(src, p.position, p.ch)));
9847
+ connection.onCompletion(yu([], (p, src, path) => service.completion(src, p.position, path)));
9848
+ connection.onHover(yu(null, (p, src, path) => service.hover(src, p.position, path)));
9849
+ connection.onDefinition(yu(null, (p, src, path) => {
9850
+ const t = service.definition(src, p.position, path);
9873
9851
  return t && {
9874
9852
  uri: t.file ? uris.get(t.file) ?? toUri(t.file) : p.textDocument.uri,
9875
9853
  range: t.range
9876
9854
  };
9877
- });
9878
- connection.onReferences((p) => service.references(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri), p.context.includeDeclaration).map((range) => ({
9855
+ }));
9856
+ connection.onReferences(yu([], (p, src, path) => service.references(src, p.position, path, p.context.includeDeclaration).map((range) => ({
9879
9857
  uri: p.textDocument.uri,
9880
9858
  range
9881
- })));
9882
- connection.onDocumentHighlight((p) => service.highlights(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri)));
9883
- connection.onDocumentSymbol((p) => service.symbols(text(p.textDocument.uri), toPath(p.textDocument.uri)));
9884
- connection.languages.semanticTokens.on((p) => service.semanticTokens(text(p.textDocument.uri), toPath(p.textDocument.uri)));
9885
- connection.onFoldingRanges((p) => service.folding(text(p.textDocument.uri), toPath(p.textDocument.uri)));
9886
- connection.onPrepareRename((p) => {
9887
- const r = service.prepareRename(text(p.textDocument.uri), p.position, toPath(p.textDocument.uri));
9859
+ }))));
9860
+ connection.onDocumentHighlight(yu([], (p, src, path) => service.highlights(src, p.position, path)));
9861
+ connection.onDocumentSymbol(yu([], (_, src, path) => service.symbols(src, path)));
9862
+ connection.languages.semanticTokens.on(yu({ data: [] }, (_, src, path) => service.semanticTokens(src, path)));
9863
+ connection.onFoldingRanges(yu([], (_, src, path) => service.folding(src, path)));
9864
+ connection.onPrepareRename(yu(null, (p, src, path) => {
9865
+ const r = service.prepareRename(src, p.position, path);
9888
9866
  if ("error" in r) throw new import_api.ResponseError(REQUEST_FAILED, r.error);
9889
9867
  return r;
9890
- });
9891
- connection.onRenameRequest((p) => {
9892
- const r = service.rename(text(p.textDocument.uri), p.position, p.newName, toPath(p.textDocument.uri));
9868
+ }));
9869
+ connection.onRenameRequest(yu(null, (p, src, path) => {
9870
+ const r = service.rename(src, p.position, p.newName, path);
9893
9871
  if ("error" in r) throw new import_api.ResponseError(REQUEST_FAILED, r.error);
9894
9872
  return { changes: { [p.textDocument.uri]: r } };
9895
- });
9896
- connection.onCodeAction((p) => service.fixes(text(p.textDocument.uri), p.context.diagnostics).map((f) => ({
9873
+ }));
9874
+ connection.onCodeAction(yu([], (p, src) => service.fixes(src, p.context.diagnostics).map((f) => ({
9897
9875
  title: f.title,
9898
9876
  kind: "quickfix",
9899
9877
  diagnostics: [f.diagnostic],
9900
9878
  isPreferred: true,
9901
9879
  edit: { changes: { [p.textDocument.uri]: f.edits } }
9902
- })));
9880
+ }))));
9903
9881
  connection.listen();
9904
9882
  return service;
9905
9883
  }
9906
- export { __commonJSMin as a, require_api$2 as i, require_api as n, require_api$1 as r, startServer as t };
9884
+ export { require_api$2 as i, require_api as n, require_api$1 as r, startServer as t };
@@ -1,6 +1,6 @@
1
1
  /// <reference path="../../typings/thenable.d.ts" preserve="true" />
2
2
  import { $ as SymbolTag, A as Hover, B as Location, C as DocumentHighlight, D as FoldingRange, E as DocumentUri, F as InlineValue, G as SelectionRange, H as Position, I as InlineValueContext, J as SemanticTokensEdit, K as SemanticTokens, L as InsertTextMode, M as InlineCompletionContext, N as InlineCompletionItem, O as FoldingRangeKind, P as InlineCompletionList, Q as SymbolKind, R as LSPAny, S as DiagnosticTag, T as DocumentSymbol, U as Range, V as MarkupKind, W as ReferenceContext, X as SignatureHelp, Y as SemanticTokensLegend, Z as SymbolInformation, _ as Declaration, a as CodeActionContext, at as VersionedTextDocumentIdentifier, b as DefinitionLink, c as CodeLens, ct as WorkspaceFolder, d as ColorPresentation, dt as uinteger, et as TextDocumentIdentifier, f as Command, g as CompletionList, h as CompletionItemTag, i as CodeAction, it as URI, j as InlayHint, k as FormattingOptions, l as Color, lt as WorkspaceSymbol, m as CompletionItemKind, n as CallHierarchyItem, nt as TextEdit, o as CodeActionKind, ot as WorkspaceEdit, p as CompletionItem, q as SemanticTokensDelta, r as CallHierarchyOutgoingCall, rt as TypeHierarchyItem, s as CodeActionTag, st as WorkspaceEditMetadata, t as CallHierarchyIncomingCall, tt as TextDocumentItem, u as ColorInformation, ut as integer, v as DeclarationLink, w as DocumentLink, x as Diagnostic, y as Definition, z as LSPObject } from "./main-DYrwpkoa.js";
3
- import { a as YuhwaService } from "./service-Brvpt7Do.js";
3
+ import { a as YuhwaService } from "./service-DimTFsE3.js";
4
4
  interface ResponseErrorLiteral<D = void> {
5
5
  /**
6
6
  * A number indicating the error type that occurred.
@@ -1,5 +1,6 @@
1
- import { _ as isMermaid } from "./src-BjOhvTAB.js";
2
- import { $t as table, A as ENUMS, D as BOOLS, F as PLACEMENT_PROPS, It as THEME_KEYS, M as NODE_PROPS, N as NUMBERS, O as COLORS, P as PANEL_PROPS, Rt as TONES, S as serializeProps, Zt as themeNames, d as PANELS, dt as SPAN_KEYS, f as SETTING_VALUES, g as lex, h as joinPath, i as optionKind, j as GROUP_PROPS, k as EDGE_PROPS, p as blockBraces, u as KNOWN_SETTINGS, v as parse, vt as parseSpanStyle, wt as spanKey, z as SHAPES } from "./plugin-Bs4eiAuz.js";
1
+ import { b as isMermaid, c as pageBlocks } from "./src-NCXCTK_4.js";
2
+ import { i as optionKind } from "./plugin-CitzbblK.js";
3
+ import { C as ENUMS, D as PANEL_PROPS, E as NUMBERS, M as SHAPES, Mt as THEME_KEYS, O as PLACEMENT_PROPS, Pt as TONES, S as EDGE_PROPS, T as NODE_PROPS, Yt as themeNames, b as BOOLS, bt as spanKey, c as joinPath, d as parse, en as table, h as serializeProps, l as lex, mt as parseSpanStyle, n as PANELS, o as blockBraces, r as SETTING_VALUES, st as SPAN_KEYS, t as KNOWN_SETTINGS, w as GROUP_PROPS, x as COLORS } from "./parse--ljBMU60.js";
3
4
  // src/lsp/format.ts
4
5
  /**
5
6
  * Formatting and text edits, without a parser of their own beyond `lex`.
@@ -27,7 +28,7 @@ function verbatimBlocks(text, lines) {
27
28
  }
28
29
  /** Format yuhwa source. Returns the new text; whitespace is all that changes. */
29
30
  function format(text) {
30
- if (isMermaid(text)) return text;
31
+ if (isMermaid(text) || /^\s*\{/.test(text)) return text;
31
32
  const eol = text.includes("\r\n") ? "\r\n" : "\n";
32
33
  const lines = text.split(/\r?\n/);
33
34
  const verbatim = /* @__PURE__ */ new Map();
@@ -123,6 +124,32 @@ function format(text) {
123
124
  while (kept.length && kept[kept.length - 1] === "") kept.pop();
124
125
  return kept.length ? kept.join(eol) + eol : "";
125
126
  }
127
+ /**
128
+ * A Markdown page with its diagram blocks formatted like `.yu` files: fences
129
+ * in `languages` and `<!--yuhwa` comments. `only` limits it to some blocks.
130
+ * A fence indented by up to three spaces keeps that indent on every line.
131
+ */
132
+ function formatPage(md, languages) {
133
+ const lines = md.split("\n");
134
+ const changed = [];
135
+ for (const b of pageBlocks(md, languages).reverse()) {
136
+ const body = lines.slice(b.line, b.end - 1);
137
+ const cr = body.some((l) => l.endsWith("\r")) ? "\r" : "";
138
+ const indent = lines[b.line - 1].match(/^ */)[0];
139
+ const inner = body.map((l) => l.replace(/\r$/, ""));
140
+ const strip = indent && inner.every((l) => !l.trim() || l.startsWith(indent)) ? indent.length : 0;
141
+ const source = inner.map((l) => l.slice(strip)).join("\n");
142
+ const out = format(source).replace(/\n+$/, "");
143
+ if (out === source) continue;
144
+ changed.unshift(b);
145
+ const next = out ? out.split("\n").map((l) => (l && strip ? indent + l : l) + cr) : [];
146
+ lines.splice(b.line, body.length, ...next);
147
+ }
148
+ return {
149
+ text: lines.join("\n"),
150
+ changed
151
+ };
152
+ }
126
153
  /** One edit that turns `a` into `b`, covering only what differs. */
127
154
  function diffEdits(a, b) {
128
155
  if (a === b) return [];
@@ -1205,6 +1232,10 @@ var YuhwaService = class {
1205
1232
  format(text) {
1206
1233
  return diffEdits(text, format(text));
1207
1234
  }
1235
+ /** Edits that format the diagram blocks of a Markdown page. */
1236
+ formatPage(text) {
1237
+ return diffEdits(text, formatPage(text).text);
1238
+ }
1208
1239
  /** Re-indent after a newline or `}` was typed at `pos`. */
1209
1240
  onType(text, pos, ch) {
1210
1241
  return onTypeEdits(text, pos, ch);
@@ -66,6 +66,8 @@ declare class YuhwaService {
66
66
  symbols(text: string, file?: string): DocumentSymbol[];
67
67
  /** Edits that format the document: indentation, line ends, blank lines. */
68
68
  format(text: string): TextEdit[];
69
+ /** Edits that format the diagram blocks of a Markdown page. */
70
+ formatPage(text: string): TextEdit[];
69
71
  /** Re-indent after a newline or `}` was typed at `pos`. */
70
72
  onType(text: string, pos: Position, ch: string): TextEdit[];
71
73
  folding(text: string, file?: string): FoldingRange[];