@celestia-island/hikari 0.55.350 → 0.55.352

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.350",
3
+ "version": "0.55.352",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Hikari UI library, Vue 3 runtime — one design system for Vue 3 and Rust/WASM applications",
@@ -24,6 +24,10 @@
24
24
  "import": "./src/index.ts",
25
25
  "types": "./src/index.ts"
26
26
  },
27
+ "./mermaid": {
28
+ "import": "./src/mermaid/index.ts",
29
+ "types": "./src/mermaid/index.ts"
30
+ },
27
31
  "./runtime": {
28
32
  "import": "./src/runtime/index.ts",
29
33
  "types": "./src/runtime/index.ts"
@@ -39,6 +39,18 @@
39
39
  pointer-events: none;
40
40
  }
41
41
 
42
+ /* Edge caption (opt-in `label` on BoardEdgeInput): SVG text with a
43
+ surface-colored halo (paint-order) so it reads over its own path, the
44
+ grid, and neighboring edges without a measuring pass. */
45
+ .hk-board-edge-label {
46
+ font-size: 12px;
47
+ fill: rgb(var(--color-text) / 85%);
48
+ paint-order: stroke;
49
+ stroke: rgb(var(--color-surface));
50
+ stroke-width: 4px;
51
+ stroke-linejoin: round;
52
+ }
53
+
42
54
  // Edge ink (fill/stroke/linecap) is set as presentation attributes on every
43
55
  // emitted path (HkBoard.tsx) — no CSS declaration here, only per-edge attrs.
44
56
 
@@ -84,6 +84,14 @@ export interface BoardNodeInput {
84
84
  data?: Record<string, unknown>;
85
85
  }
86
86
 
87
+ /** Per-instance sequence for document-unique marker ids (url(#id)
88
+ * resolves document-wide — two boards must never mint the same id). */
89
+ let boardInstanceCounter = 0;
90
+ function boardInstanceSeq(): number {
91
+ boardInstanceCounter += 1;
92
+ return boardInstanceCounter;
93
+ }
94
+
87
95
  export interface BoardEdgeInput {
88
96
  id: string;
89
97
  from: string;
@@ -96,6 +104,13 @@ export interface BoardEdgeInput {
96
104
  ink?: string;
97
105
  dashed?: boolean;
98
106
  width?: number;
107
+ /** Arrowhead at the `to` end: solid triangle, open chevron, or none
108
+ * (the default — plain path, current behavior). */
109
+ arrow?: "none" | "solid" | "open";
110
+ /** Caption painted at the path midpoint (mermaid edge labels, sequence
111
+ * message text). Plain text — no markup, SVG <text> with a surface
112
+ * halo so it stays legible over the path it names. */
113
+ label?: string;
99
114
  }
100
115
 
101
116
  // Ink colors ride INLINE STYLES beside the stroke presentation attribute:
@@ -162,7 +177,16 @@ export default defineComponent({
162
177
 
163
178
  const edgePaths = computed(() => {
164
179
  const rects = rectOf.value;
165
- const out: { id: string; d: string; ink: string; dashed: boolean; width: number }[] = [];
180
+ const out: {
181
+ id: string;
182
+ d: string;
183
+ ink: string;
184
+ dashed: boolean;
185
+ width: number;
186
+ arrow: "none" | "solid" | "open";
187
+ label: string | null;
188
+ labelAt: { x: number; y: number };
189
+ }[] = [];
166
190
  for (const e of props.edges) {
167
191
  const from = rects.get(e.from);
168
192
  const to = rects.get(e.to);
@@ -176,17 +200,52 @@ export default defineComponent({
176
200
  .map((id) => rects.get(id))
177
201
  .filter((r): r is BoardRect => Boolean(r))
178
202
  .map((r) => ({ x: r.x + r.w / 2, y: r.y + r.h / 2 }));
203
+ // Label anchor: the chord midpoint, pulled onto the middle via
204
+ // leg when the route bends through junctions (the sequence
205
+ // self-loop reads best with the caption beside the jog).
206
+ const mid = viaCenters.length > 0
207
+ ? viaCenters[Math.floor((viaCenters.length - 1) / 2)]
208
+ : { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
179
209
  out.push({
180
210
  id: e.id,
181
211
  d: boardViaPath(a, viaCenters, b, e.style ?? "orthogonal"),
182
212
  ink: e.ink ?? DEFAULT_INK,
183
213
  dashed: Boolean(e.dashed),
184
214
  width: e.width ?? 1.5,
215
+ arrow: e.arrow ?? "none",
216
+ label: e.label && e.label !== "" ? e.label : null,
217
+ labelAt: mid,
185
218
  });
186
219
  }
187
220
  return out;
188
221
  });
189
222
 
223
+ /** One marker per (kind, ink) pair actually used — marker fill cannot
224
+ * follow the referencing stroke on every engine hikari supports, so
225
+ * the defs are minted from the edge list (deterministic, in edge
226
+ * order) instead of trusting `context-stroke`. Ids carry a per-BOARD
227
+ * sequence: `url(#id)` resolves document-wide, and two mounted boards
228
+ * minting `hk-board-ah-0` each would cross-wire their arrowheads. */
229
+ const boardSeq = boardInstanceSeq();
230
+ const edgeMarkers = computed(() => {
231
+ const index = new Map<string, number>();
232
+ for (const e of edgePaths.value) {
233
+ if (e.arrow === "none") continue;
234
+ const key = `${e.arrow}\u0000${e.ink}`;
235
+ if (!index.has(key)) index.set(key, index.size);
236
+ }
237
+ return [...index.entries()].map(([key, i]) => {
238
+ const [kind, ink] = key.split("\u0000");
239
+ return { id: `hk-board-ah-${boardSeq}-${i}`, kind: kind as "solid" | "open", ink };
240
+ });
241
+ });
242
+
243
+ const markerOf = (kind: "none" | "solid" | "open", ink: string): string | undefined => {
244
+ if (kind === "none") return undefined;
245
+ const idx = edgeMarkers.value.findIndex((m) => m.kind === kind && m.ink === ink);
246
+ return idx >= 0 ? `url(#hk-board-ah-${boardSeq}-${idx})` : undefined;
247
+ };
248
+
190
249
  const contentBounds = computed(() => content.value);
191
250
 
192
251
  const worldStyle = computed(() => ({
@@ -431,18 +490,50 @@ export default defineComponent({
431
490
  <div class="hk-board-grid" style={gridStyle.value} />
432
491
  <div class="hk-board-world" style={worldStyle.value}>
433
492
  <svg class="hk-board-edges" width={contentBounds.value.w} height={contentBounds.value.h}>
493
+ <defs>
494
+ {edgeMarkers.value.map((m) => (
495
+ <marker
496
+ key={m.id}
497
+ id={m.id}
498
+ viewBox="0 0 10 8"
499
+ refX={9}
500
+ refY={4}
501
+ markerWidth={10}
502
+ markerHeight={8}
503
+ markerUnits="userSpaceOnUse"
504
+ orient="auto"
505
+ >
506
+ {m.kind === "solid"
507
+ ? <path d="M0,0 L10,4 L0,8 Z" fill={m.ink} />
508
+ : <path d="M0,0 L10,4 L0,8" fill="none" stroke={m.ink} stroke-width={1.5} stroke-linecap="round" />}
509
+ </marker>
510
+ ))}
511
+ </defs>
434
512
  {edgePaths.value.map((e) => (
435
- <path
436
- key={e.id}
437
- class="hk-board-edge"
438
- d={e.d}
439
- stroke={e.ink}
440
- style={{ stroke: e.ink }}
441
- stroke-width={e.width}
442
- stroke-dasharray={e.dashed ? "6 5" : undefined}
443
- fill="none"
444
- stroke-linecap="round"
445
- />
513
+ <g key={e.id}>
514
+ <path
515
+ class="hk-board-edge"
516
+ d={e.d}
517
+ stroke={e.ink}
518
+ style={{ stroke: e.ink }}
519
+ stroke-width={e.width}
520
+ stroke-dasharray={e.dashed ? "6 5" : undefined}
521
+ fill="none"
522
+ stroke-linecap="round"
523
+ marker-end={markerOf(e.arrow, e.ink)}
524
+ />
525
+ {e.label !== null && (
526
+ <text
527
+ class="hk-board-edge-label"
528
+ x={e.labelAt.x}
529
+ y={e.labelAt.y}
530
+ text-anchor="middle"
531
+ dominant-baseline="middle"
532
+ >
533
+ {e.label}
534
+ </text>
535
+ )}
536
+ </g>
446
537
  ))}
447
538
  </svg>
448
539
  {props.nodes.filter((n) => !n.hidden).map((n) => (
@@ -0,0 +1,148 @@
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+ import { createApp, h, nextTick, ref } from "vue";
3
+
4
+ import HkMarkdownRenderer from "./HkMarkdownRenderer";
5
+ import { setMermaidEngineForTests } from "../mermaid/engine";
6
+ import { mermaidParser } from "../mermaid";
7
+
8
+ /**
9
+ * Mermaid fence integration in HkMarkdownRenderer:
10
+ * - no engine → an ordinary highlighted code block (byte-for-byte the
11
+ * pre-existing behavior);
12
+ * - engine → placeholder mounts an HkMermaidDiagram sub-app;
13
+ * - re-parse swaps content without leaking the old sub-app;
14
+ * - hostile source text stays text (escaped through the sanitize path,
15
+ * rendered as text nodes by the fallback/board painters).
16
+ */
17
+
18
+ const mounts: { app: ReturnType<typeof createApp>; container: HTMLElement }[] = [];
19
+
20
+ function mount(content: string): { container: HTMLElement; set: (v: string) => void } {
21
+ const holder = ref(content);
22
+ const container = document.createElement("div");
23
+ document.body.appendChild(container);
24
+ const app = createApp({
25
+ render: () => h(HkMarkdownRenderer, { content: holder.value }),
26
+ });
27
+ app.mount(container);
28
+ mounts.push({ app, container });
29
+ return { container, set: (v: string) => void (holder.value = v) };
30
+ }
31
+
32
+ async function settleFor(root: HTMLElement, selector: string, tries = 120): Promise<void> {
33
+ for (let i = 0; i < tries; i += 1) {
34
+ if (root.querySelector(selector)) return;
35
+ await new Promise((r) => setTimeout(r, 5));
36
+ await nextTick();
37
+ }
38
+ }
39
+
40
+ afterEach(() => {
41
+ for (const { app, container } of mounts.splice(0)) {
42
+ app.unmount();
43
+ container.remove();
44
+ }
45
+ setMermaidEngineForTests(null);
46
+ });
47
+
48
+ const DOC = [
49
+ "# Report",
50
+ "",
51
+ "```mermaid",
52
+ "graph TD",
53
+ "A[Alpha] --> B[Beta]",
54
+ "```",
55
+ "",
56
+ "tail prose",
57
+ ].join("\n");
58
+
59
+ describe("HkMarkdownRenderer mermaid fences", () => {
60
+ it("without an engine the fence renders as the ordinary code block", async () => {
61
+ setMermaidEngineForTests(null);
62
+ const { container } = mount(DOC);
63
+ await settleFor(container, ".hk-md-code-wrap");
64
+ const code = container.querySelector(".hk-md-code code");
65
+ expect(code?.getAttribute("class")).toContain("language-mermaid");
66
+ expect(code?.textContent).toContain("graph TD");
67
+ expect(container.querySelector(".hk-md-mermaid")).toBeNull();
68
+ expect(container.querySelector(".hk-mermaid")).toBeNull();
69
+ });
70
+
71
+ it("with an engine the fence mounts a diagram sub-app inside the markdown body", async () => {
72
+ setMermaidEngineForTests(mermaidParser);
73
+ const { container } = mount(DOC);
74
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
75
+ const host = container.querySelector(".hk-md-mermaid") as HTMLElement;
76
+ expect(host.querySelector(".hk-mermaid")).not.toBeNull();
77
+ expect(host.querySelector(".hk-board")).not.toBeNull();
78
+ // Prose around the fence is untouched. (No h1 assertion: the
79
+ // happy-dom DOMPurify build strips SOME leading tags — an
80
+ // environment artifact, not product behavior — so prose presence is
81
+ // asserted on text, not on tag shape.)
82
+ expect(container.textContent).toContain("Report");
83
+ expect(container.textContent).toContain("tail prose");
84
+ // The source carrier is swapped out for the host on mount.
85
+ expect(container.querySelector(".hk-md-mermaid-src")).toBeNull();
86
+ });
87
+
88
+ it("re-parsing new content replaces the old diagram (no stale sub-app)", async () => {
89
+ setMermaidEngineForTests(mermaidParser);
90
+ const { container, set } = mount(DOC);
91
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
92
+ const first = container.querySelector(".hk-mermaid") as HTMLElement;
93
+ expect(first.getAttribute("data-mermaid-kind")).toBe("graph");
94
+
95
+ // Leading prose on purpose: the happy-dom DOMPurify build unwraps
96
+ // the FIRST element of the sanitized string (environment artifact,
97
+ // browsers keep it), and this test targets the swap, not that quirk.
98
+ set(["Update:", "", "```mermaid", "sequenceDiagram", "X ->> Y: ping", "```"].join("\n"));
99
+ await settleFor(container, ".hk-mermaid[data-mermaid-kind='sequence']");
100
+ const mounted = container.querySelectorAll(".hk-md-mermaid[data-mermaid='mounted']");
101
+ expect(mounted).toHaveLength(1);
102
+ // The old board left the DOM with the old body.
103
+ expect(first.isConnected).toBe(false);
104
+ });
105
+
106
+ it("hostile source text stays text through the whole pipeline", async () => {
107
+ setMermaidEngineForTests(mermaidParser);
108
+ const hostile = ["```mermaid", "graph TD", 'A<img src=x onerror="alert(1)"> --> B', "```"].join("\n");
109
+ const { container } = mount(hostile);
110
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
111
+ expect(container.querySelector("img")).toBeNull();
112
+ // The hostile text may appear ESCAPED (the fallback shows the source
113
+ // verbatim as text); it must never appear as live markup.
114
+ expect(container.innerHTML).not.toContain("<img");
115
+ expect(container.innerHTML).not.toContain("<script");
116
+ });
117
+ });
118
+
119
+ // ── Lifecycle pins (R3 survivors: prune + teardown) ───────────────────
120
+
121
+ describe("mermaid sub-app lifecycle pins", () => {
122
+ it("re-parse unmounts the stale sub-app (no leaked __vue_app__)", async () => {
123
+ setMermaidEngineForTests(mermaidParser);
124
+ const { container, set } = mount(DOC);
125
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
126
+ const stale = container.querySelector(".hk-md-mermaid") as HTMLElement;
127
+ expect((stale as unknown as Record<string, unknown>).__vue_app__).toBeTruthy();
128
+
129
+ set(["Update:", "", "```mermaid", "sequenceDiagram", "X ->> Y: ping", "```"].join("\n"));
130
+ await settleFor(container, ".hk-mermaid[data-mermaid-kind='sequence']");
131
+ // The stale host left the document AND its app was unmounted.
132
+ expect(stale.isConnected).toBe(false);
133
+ expect((stale as unknown as Record<string, unknown>).__vue_app__).toBeUndefined();
134
+ });
135
+
136
+ it("renderer teardown unmounts every mermaid sub-app", async () => {
137
+ setMermaidEngineForTests(mermaidParser);
138
+ const { container } = mount(DOC);
139
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
140
+ const host = container.querySelector(".hk-md-mermaid") as HTMLElement;
141
+ expect((host as unknown as Record<string, unknown>).__vue_app__).toBeTruthy();
142
+
143
+ const entry = mounts[mounts.length - 1];
144
+ entry.app.unmount();
145
+ expect((host as unknown as Record<string, unknown>).__vue_app__).toBeUndefined();
146
+ expect(host.isConnected).toBe(false);
147
+ });
148
+ });
@@ -208,6 +208,24 @@
208
208
  z-index: 10;
209
209
  }
210
210
 
211
+ /* Mermaid fence placeholder — the mounted HkMermaidDiagram replaces the
212
+ subtree after the DOM settles. The inner pre is only a SOURCE CARRIER
213
+ (it survives the sanitize pass and hands the raw fence text to the
214
+ sub-app); it never paints. */
215
+ .hk-md-mermaid {
216
+ margin: 0.75em 0;
217
+ }
218
+
219
+ .hk-md-mermaid-src {
220
+ display: none;
221
+ }
222
+
223
+ .hk-markdown-body .hk-mermaid {
224
+ // The diagram owns its block: markdown prose margins stop at its
225
+ // border, the board's own surface takes over.
226
+ margin: 0;
227
+ }
228
+
211
229
  /* ── Inline chips (opt-in `inlineChips` prop) ────────────────────────
212
230
  Fill-template tokens (`{{ name }}`) and asset references (`@level/name`,
213
231
  bare `@name`) chipped inside rendered prose. The look is the family's
@@ -1,8 +1,10 @@
1
- import { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from "vue";
1
+ import { computed, createApp, defineComponent, nextTick, onBeforeUnmount, ref, watch, type App } from "vue";
2
2
  import type { Renderer, Tokens } from "marked";
3
3
  import HSpinner from "./HkSpinner";
4
+ import HkMermaidDiagram from "./HkMermaidDiagram";
4
5
  import { applyInlineChipsToBody } from "./inlineChips";
5
6
  import { attachOverlayScrollbars, type OverlayScrollbarHandle } from "../composables/useOverlayScrollbar";
7
+ import { getMermaidEngine } from "../mermaid/engine";
6
8
  import { asIndexable } from "../utils/typing";
7
9
  import "./HkMarkdownRenderer.scss";
8
10
 
@@ -42,6 +44,14 @@ async function ensureDOMPurify(): Promise<Purifier | null> {
42
44
  }
43
45
  }
44
46
 
47
+ function escapeHtml(text: string): string {
48
+ return text
49
+ .replace(/&/g, "&amp;")
50
+ .replace(/</g, "&lt;")
51
+ .replace(/>/g, "&gt;")
52
+ .replace(/"/g, "&quot;");
53
+ }
54
+
45
55
  function tryHighlight(code: string, lang?: string): string {
46
56
  try {
47
57
  // `hljs` is a host-installed global (the consumer may ship highlight.js
@@ -57,15 +67,11 @@ function tryHighlight(code: string, lang?: string): string {
57
67
  } catch {
58
68
  // fall through
59
69
  }
60
- return code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
70
+ return escapeHtml(code);
61
71
  }
62
72
 
63
73
  function renderPlain(content: string): string {
64
- const escaped = content
65
- .replace(/&/g, "&amp;")
66
- .replace(/</g, "&lt;")
67
- .replace(/>/g, "&gt;");
68
- return `<pre class="hk-md-plain">${escaped}</pre>`;
74
+ return `<pre class="hk-md-plain">${escapeHtml(content)}</pre>`;
69
75
  }
70
76
 
71
77
  async function renderMarkdown(content: string): Promise<string> {
@@ -83,6 +89,19 @@ async function renderMarkdown(content: string): Promise<string> {
83
89
  const renderer = new marked.Renderer();
84
90
 
85
91
  renderer.code = function ({ text, lang }: Tokens.Code): string {
92
+ // Mermaid fences become carrier blocks; the mounted
93
+ // HkMermaidDiagram sub-apps replace them after the DOM settles (see
94
+ // syncMermaidBlocks). The carrier is a PRE (never a wrapper DIV):
95
+ // a div leading the sanitized string is not universally kept by the
96
+ // sanitize pass, while pre/code survive every observed shape — the
97
+ // mount swaps the carrier for a fresh host div via replaceWith,
98
+ // which never passes through the sanitizer at all.
99
+ // Without a registered engine the fence renders as the ordinary
100
+ // code block below — the exact economy the hljs convention gives
101
+ // syntax highlighting.
102
+ if (lang === "mermaid" && getMermaidEngine()) {
103
+ return `<pre class="hk-md-mermaid-src" data-mermaid="pending"><code>${escapeHtml(text)}</code></pre>`;
104
+ }
86
105
  const highlighted = tryHighlight(text, lang);
87
106
  // Audit hikari-R1-5: whitelist the language tag before interpolation
88
107
  // (depth-in-defence — the final DOMPurify pass remains the primary
@@ -174,6 +193,40 @@ export default defineComponent({
174
193
  const bodyRef = ref<HTMLElement>();
175
194
  const overlayScrollbars: Array<{ el: HTMLElement; handle: OverlayScrollbarHandle }> = [];
176
195
 
196
+ // Mounted mermaid sub-apps. Each diagram placeholder gets its own
197
+ // createApp instance (the body is innerHTML, not vdom — a sub-app is
198
+ // the only way to mount a component inside it); they are tracked so
199
+ // a re-parse (body replaced wholesale) and the final unmount never
200
+ // leak an app on a detached node.
201
+ const mermaidApps: Array<{ el: HTMLElement; app: App }> = [];
202
+
203
+ function pruneMermaidApps(): void {
204
+ for (let i = mermaidApps.length - 1; i >= 0; i -= 1) {
205
+ if (!mermaidApps[i].el.isConnected) {
206
+ mermaidApps[i].app.unmount();
207
+ mermaidApps.splice(i, 1);
208
+ }
209
+ }
210
+ }
211
+
212
+ function syncMermaidBlocks(body: HTMLElement): void {
213
+ pruneMermaidApps();
214
+ if (!getMermaidEngine()) return;
215
+ for (const carrier of body.querySelectorAll<HTMLElement>('.hk-md-mermaid-src[data-mermaid="pending"]')) {
216
+ const source = carrier.querySelector("code")?.textContent ?? "";
217
+ const host = document.createElement("div");
218
+ host.className = "hk-md-mermaid";
219
+ host.dataset.mermaid = "mounted";
220
+ carrier.replaceWith(host);
221
+ // Report contexts are narrow reading panes: the minimap is noise
222
+ // for a diagram-sized board, canvas dragging stays on (wide
223
+ // diagrams are exactly what pan was built for).
224
+ const app = createApp(HkMermaidDiagram, { source, minimap: false, interactive: true });
225
+ app.mount(host);
226
+ mermaidApps.push({ el: host, app });
227
+ }
228
+ }
229
+
177
230
  function syncOverlayScrollbars() {
178
231
  for (let i = overlayScrollbars.length - 1; i >= 0; i--) {
179
232
  if (!overlayScrollbars[i].el.isConnected) {
@@ -200,12 +253,17 @@ export default defineComponent({
200
253
  // nodes, so the scan must reconcile against the final DOM.
201
254
  if (props.inlineChips) applyInlineChipsToBody(body);
202
255
  syncOverlayScrollbars();
256
+ // Mermaid mounts last: it replaces its carrier subtrees
257
+ // wholesale, which would orphan anything attached inside them.
258
+ syncMermaidBlocks(body);
203
259
  });
204
260
  });
205
261
 
206
262
  onBeforeUnmount(() => {
207
263
  for (const c of overlayScrollbars) c.handle.detach();
208
264
  overlayScrollbars.length = 0;
265
+ for (const m of mermaidApps) m.app.unmount();
266
+ mermaidApps.length = 0;
209
267
  });
210
268
 
211
269
  return () => (