@alexpeng/dsh-custom-plugin 0.1.1 → 0.1.3

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/lib/client.js CHANGED
@@ -130,6 +130,120 @@ window.__ModuleLoader__.load({
130
130
  }
131
131
  }
132
132
  //#endregion
133
+ //#region src/client/mermaid-code.ts
134
+ /**
135
+ * Pure Mermaid code-block detection helpers for the in-place renderer.
136
+ *
137
+ * The GUI renders a settled ```mermaid fence with its language in the code
138
+ * banner, but while the assistant is still streaming the banner is blank and
139
+ * the fence content grows chunk by chunk — detection then has to fall back to
140
+ * content heuristics (keyword prefix + completeness), the same approach the
141
+ * Gemini Voyager extension uses. Everything here is string-in/string-out so
142
+ * the heuristics stay unit-testable without a DOM.
143
+ * @module @alexpeng/dsh-custom-plugin/client/mermaid-code
144
+ */
145
+ /** Diagram-type keywords aligned with mermaid's own detectors (longest first
146
+ * so `flowchart-elk` is not eaten by `flowchart`). `mindmap` included. */
147
+ const MERMAID_KEYWORDS = [
148
+ "flowchart-elk",
149
+ "flowchart",
150
+ "graph",
151
+ "sequenceDiagram",
152
+ "classDiagram",
153
+ "stateDiagram",
154
+ "erDiagram",
155
+ "gantt",
156
+ "pie",
157
+ "gitGraph",
158
+ "journey",
159
+ "mindmap",
160
+ "timeline",
161
+ "zenuml",
162
+ "quadrantChart",
163
+ "requirementDiagram",
164
+ "requirement",
165
+ "sankey-beta",
166
+ "sankey",
167
+ "C4Context",
168
+ "C4Container",
169
+ "C4Component",
170
+ "C4Dynamic",
171
+ "C4Deployment",
172
+ "xychart-beta",
173
+ "xychart",
174
+ "block-beta",
175
+ "block",
176
+ "packet-beta",
177
+ "packet",
178
+ "architecture-beta",
179
+ "architecture",
180
+ "kanban",
181
+ "radar-beta",
182
+ "treemap"
183
+ ];
184
+ /** Banner labels that carry no language information (GUI locales + plain
185
+ * `mermaid` obviously excluded): content detection still applies to them. */
186
+ const GENERIC_INFOSTRINGS = /* @__PURE__ */ new Set([
187
+ "代码段",
188
+ "代码",
189
+ "代码块",
190
+ "示例",
191
+ "示例代码",
192
+ "程式碼片段",
193
+ "コード スニペット",
194
+ "code",
195
+ "code snippet",
196
+ "snippet",
197
+ "example",
198
+ "code example",
199
+ "sample",
200
+ "text",
201
+ "plain",
202
+ "plaintext",
203
+ "raw",
204
+ "output",
205
+ "result"
206
+ ]);
207
+ /** A banner label that names a real programming language must not be
208
+ * content-detected (a Python `%%` comment is not a mermaid directive). */
209
+ function isGenericInfostring(label) {
210
+ if (label === null || label === void 0 || label.trim() === "") return true;
211
+ return GENERIC_INFOSTRINGS.has(label.trim().toLowerCase());
212
+ }
213
+ /** Whitespace normalization: web/CJK paste artifacts break the parser. */
214
+ function normalizeMermaidText(code) {
215
+ return code.replace(/[\u00A0\u2002\u2003\u2009\u3000]/g, " ").replace(/[\u200B\u200C\u200D\uFEFF]/g, "");
216
+ }
217
+ /** Does this text look like complete mermaid source? Conservative: during
218
+ * streaming we would rather skip a beat than flash a syntax error. */
219
+ function isMermaidCode(code) {
220
+ const trimmed = code.trim();
221
+ if (trimmed.length < 50) return false;
222
+ const lower = trimmed.toLowerCase();
223
+ if (!(trimmed.startsWith("%%") || MERMAID_KEYWORDS.some((keyword) => {
224
+ if (!lower.startsWith(keyword.toLowerCase())) return false;
225
+ const next = lower.charAt(keyword.length);
226
+ return next === "" || next === " " || next === "\n" || next === " " || next === "\r";
227
+ }))) return false;
228
+ const lines = trimmed.split("\n").filter((line) => line.trim().length > 0);
229
+ if (lines.length < 3) return false;
230
+ const lastLine = lines[lines.length - 1].trim();
231
+ if ([
232
+ "-->",
233
+ "---",
234
+ "-.",
235
+ "==>",
236
+ ":::",
237
+ "[",
238
+ "(",
239
+ "{",
240
+ "|",
241
+ "&",
242
+ ","
243
+ ].some((ending) => lastLine.endsWith(ending))) return false;
244
+ return true;
245
+ }
246
+ //#endregion
133
247
  //#region src/client/mermaid-url.ts
134
248
  function bytesToBase64Url(bytes) {
135
249
  let bin = "";
@@ -990,6 +1104,61 @@ window.__ModuleLoader__.load({
990
1104
  flex-direction: column;
991
1105
  gap: 14px;
992
1106
  max-width: 720px;
1107
+ }
1108
+ .vx-mmd-wrap {
1109
+ position: relative;
1110
+ margin: 6px 0;
1111
+ border: 1px solid rgba(127, 164, 224, .35);
1112
+ border-radius: 12px;
1113
+ overflow: hidden;
1114
+ background: rgba(127, 164, 224, .05);
1115
+ }
1116
+ .vx-mmd-bar {
1117
+ display: flex;
1118
+ align-items: center;
1119
+ gap: 4px;
1120
+ padding: 4px 6px;
1121
+ border-bottom: 1px solid rgba(127, 164, 224, .25);
1122
+ background: rgba(127, 164, 224, .08);
1123
+ }
1124
+ .vx-mmd-btn {
1125
+ border: none;
1126
+ background: transparent;
1127
+ color: inherit;
1128
+ opacity: .65;
1129
+ font-size: 12px;
1130
+ padding: 3px 10px;
1131
+ border-radius: 8px;
1132
+ cursor: pointer;
1133
+ }
1134
+ .vx-mmd-btn:hover {
1135
+ opacity: 1;
1136
+ background: rgba(127, 164, 224, .18);
1137
+ }
1138
+ .vx-mmd-btn.active {
1139
+ opacity: 1;
1140
+ background: rgba(127, 164, 224, .28);
1141
+ font-weight: 600;
1142
+ }
1143
+ .vx-mmd-live {
1144
+ margin-left: auto;
1145
+ font-size: 11px;
1146
+ opacity: .6;
1147
+ color: inherit;
1148
+ text-decoration: none;
1149
+ padding: 3px 8px;
1150
+ }
1151
+ .vx-mmd-live:hover {
1152
+ opacity: 1;
1153
+ }
1154
+ .vx-mmd-stage {
1155
+ padding: 16px 12px;
1156
+ overflow-x: auto;
1157
+ text-align: center;
1158
+ }
1159
+ .vx-mmd-stage svg {
1160
+ max-width: 100%;
1161
+ height: auto;
993
1162
  }`;
994
1163
  //#endregion
995
1164
  //#region src/client/custom.tsx
@@ -2605,7 +2774,7 @@ window.__ModuleLoader__.load({
2605
2774
  return false;
2606
2775
  }
2607
2776
  }
2608
- async function renderMermaid(code) {
2777
+ async function renderMermaid(code, dark = false) {
2609
2778
  try {
2610
2779
  const mermaid = (typeof window !== "undefined" ? window : null).mermaid;
2611
2780
  if (mermaid === void 0) return {
@@ -2614,7 +2783,7 @@ window.__ModuleLoader__.load({
2614
2783
  };
2615
2784
  mermaid.initialize({
2616
2785
  startOnLoad: false,
2617
- theme: "default",
2786
+ theme: dark ? "dark" : "default",
2618
2787
  securityLevel: "strict"
2619
2788
  });
2620
2789
  const id = "vx-mmd-" + Date.now() + Math.floor(Math.random() * 9999);
@@ -2654,6 +2823,132 @@ window.__ModuleLoader__.load({
2654
2823
  index: 0
2655
2824
  } });
2656
2825
  }
2826
+ /** Blocks with a render already in flight (WeakSet: dead blocks drop out). */
2827
+ const mmdInflight = /* @__PURE__ */ new WeakSet();
2828
+ /** Previous scan theme; a flip invalidates rendered-SVG memoization. */
2829
+ let mmdLastDark = null;
2830
+ /** The banner's language label: `.md-code-block > bannerWrap > banner >
2831
+ * infostring` is the GUI CodeBlock's stable shape (its CSS classes are
2832
+ * hashed, the structure is not). */
2833
+ function blockInfostring(block) {
2834
+ const info = block.querySelector(":scope > div:first-child > div:first-child > div:first-child");
2835
+ return info !== null ? info.textContent ?? "" : null;
2836
+ }
2837
+ /** Raw fence text: the GUI keeps unknown languages (mermaid among them) on
2838
+ * the plain `<pre><code>` path, so `pre` always carries the source. */
2839
+ function blockCodeText(block) {
2840
+ const pre = block.querySelector("pre");
2841
+ return pre !== null ? pre.textContent ?? "" : null;
2842
+ }
2843
+ /** Insert/refresh the diagram wrapper before one code block. Never moves
2844
+ * GUI-owned nodes — React keeps reconciling its tree; the block is only
2845
+ * visually swapped with the diagram stage via display. */
2846
+ async function renderInPlace(block, code, dark) {
2847
+ if (block.dataset.vxMmd === code) return;
2848
+ if (!await ensureMermaid()) {
2849
+ block.dataset.vxMmdFail = code;
2850
+ return;
2851
+ }
2852
+ const r = await renderMermaid(code, dark);
2853
+ if (!r.ok) {
2854
+ block.dataset.vxMmdFail = code;
2855
+ return;
2856
+ }
2857
+ delete block.dataset.vxMmdFail;
2858
+ block.dataset.vxMmd = code;
2859
+ const d = typeof document !== "undefined" ? document : null;
2860
+ if (d === null) return;
2861
+ let wrap = block.previousElementSibling;
2862
+ if (wrap === null || !wrap.classList.contains("vx-mmd-wrap")) {
2863
+ wrap = d.createElement("div");
2864
+ wrap.className = "vx-mmd-wrap";
2865
+ block.parentElement?.insertBefore(wrap, block);
2866
+ const bar = d.createElement("div");
2867
+ bar.className = "vx-mmd-bar";
2868
+ const diagramBtn = d.createElement("button");
2869
+ diagramBtn.type = "button";
2870
+ diagramBtn.className = "vx-mmd-btn active";
2871
+ diagramBtn.textContent = "图表";
2872
+ const codeBtn = d.createElement("button");
2873
+ codeBtn.type = "button";
2874
+ codeBtn.className = "vx-mmd-btn";
2875
+ codeBtn.textContent = "代码";
2876
+ const live = d.createElement("a");
2877
+ live.className = "vx-mmd-live";
2878
+ live.target = "_blank";
2879
+ live.rel = "noopener noreferrer";
2880
+ live.textContent = "mermaid.live";
2881
+ mermaidLiveUrl(code).then((url) => {
2882
+ live.href = url;
2883
+ }).catch(() => {});
2884
+ bar.append(diagramBtn, codeBtn, live);
2885
+ const stage = d.createElement("div");
2886
+ stage.className = "vx-mmd-stage";
2887
+ wrap.append(bar, stage);
2888
+ const showDiagram = () => {
2889
+ stage.style.display = "";
2890
+ block.style.display = "none";
2891
+ diagramBtn.classList.add("active");
2892
+ codeBtn.classList.remove("active");
2893
+ };
2894
+ const showCode = () => {
2895
+ stage.style.display = "none";
2896
+ block.style.display = "";
2897
+ diagramBtn.classList.remove("active");
2898
+ codeBtn.classList.add("active");
2899
+ };
2900
+ diagramBtn.addEventListener("click", showDiagram);
2901
+ codeBtn.addEventListener("click", showCode);
2902
+ showDiagram();
2903
+ }
2904
+ const stage = wrap.querySelector(".vx-mmd-stage");
2905
+ if (stage !== null) stage.innerHTML = r.svg;
2906
+ }
2907
+ /** Scan every chat code block and render the mermaid ones in place. */
2908
+ async function scanMermaidBlocks(dark) {
2909
+ const d = typeof document !== "undefined" ? document : null;
2910
+ if (d === null) return;
2911
+ for (const wrap of Array.from(d.querySelectorAll(".vx-mmd-wrap"))) {
2912
+ const next = wrap.nextElementSibling;
2913
+ if (next === null || !next.classList.contains("md-code-block")) wrap.remove();
2914
+ }
2915
+ for (const block of Array.from(d.querySelectorAll(".md-code-block"))) {
2916
+ if (mmdInflight.has(block)) continue;
2917
+ const codeRaw = blockCodeText(block);
2918
+ if (codeRaw === null) continue;
2919
+ const code = normalizeMermaidText(codeRaw).trim();
2920
+ if (code === "") continue;
2921
+ const info = blockInfostring(block);
2922
+ if (info !== null && info.trim().toLowerCase() === "mermaid") {
2923
+ if (code.split("\n").filter((l) => l.trim() !== "").length < 2) continue;
2924
+ } else {
2925
+ if (!isGenericInfostring(info)) continue;
2926
+ if (!isMermaidCode(codeRaw)) continue;
2927
+ }
2928
+ if (block.dataset.vxMmd === code || block.dataset.vxMmdFail === code) continue;
2929
+ mmdInflight.add(block);
2930
+ try {
2931
+ await renderInPlace(block, code, dark);
2932
+ } finally {
2933
+ mmdInflight.delete(block);
2934
+ }
2935
+ }
2936
+ }
2937
+ /** Undo in-place rendering (feature toggled off): remove wrappers, unhide
2938
+ * code blocks. Diagram DOM is plugin-owned, so removal is safe. */
2939
+ function restoreMermaidBlocks() {
2940
+ const d = typeof document !== "undefined" ? document : null;
2941
+ if (d === null) return;
2942
+ for (const wrap of Array.from(d.querySelectorAll(".vx-mmd-wrap"))) {
2943
+ const next = wrap.nextElementSibling;
2944
+ if (next !== null && next.classList.contains("md-code-block")) next.style.display = "";
2945
+ wrap.remove();
2946
+ }
2947
+ for (const block of Array.from(d.querySelectorAll(".md-code-block"))) {
2948
+ delete block.dataset.vxMmd;
2949
+ delete block.dataset.vxMmdFail;
2950
+ }
2951
+ }
2657
2952
  /** Peak-hour CNY unit prices per 1M tokens (official peak/off-peak table
2658
2953
  * effective 2026-08-17); off-peak hours are exactly half. deepseek-chat and
2659
2954
  * deepseek-reasoner were deprecated 2026-07-24 and both map onto
@@ -3807,8 +4102,8 @@ window.__ModuleLoader__.load({
3807
4102
  setEngine(ok ? "ready" : "failed");
3808
4103
  toast(ok ? "Mermaid 引擎已就绪" : "加载失败:可改用 mermaid.live 按钮", ok ? "info" : "error");
3809
4104
  };
3810
- return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted vx-pad-sm" }, "消息中的 Mermaid 代码块可就地渲染为图表;渲染失败可一键跳转 mermaid.live 在线编辑。"), react.createElement(Toggle, {
3811
- label: "显示 Mermaid 渲染按钮",
4105
+ return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-muted vx-pad-sm" }, "助手回复与用户消息中的 Mermaid 代码块会自动就地渲染为图表(支持思维导图、流程图等),可随时切回代码视图;渲染引擎优先取本地依赖,失败时回退 CDN,也可一键跳转 mermaid.live 在线编辑。"), react.createElement(Toggle, {
4106
+ label: "自动渲染 Mermaid 图表",
3812
4107
  checked: S.cfg.mermaid === true,
3813
4108
  onChange: (v) => {
3814
4109
  setS({ cfg: {
@@ -3823,7 +4118,7 @@ window.__ModuleLoader__.load({
3823
4118
  }, react.createElement(Icon, {
3824
4119
  n: "gitBranch",
3825
4120
  size: 12
3826
- }), engine === "ready" ? " 引擎已就绪" : engine === "loading" ? " 加载中…" : " 预加载渲染引擎"), react.createElement("span", { className: "vx-muted" }, engine === "failed" ? "加载失败(可能需代理)" : "")));
4121
+ }), engine === "ready" ? " 引擎已就绪" : engine === "loading" ? " 加载中…" : " 预加载渲染引擎"), react.createElement("span", { className: "vx-muted" }, engine === "failed" ? "加载失败(本地依赖缺失且网络不可达)" : "")));
3827
4122
  }
3828
4123
  function ToolsTab() {
3829
4124
  const s = useS();
@@ -3937,6 +4232,47 @@ window.__ModuleLoader__.load({
3937
4232
  onClick: () => answer(false)
3938
4233
  }, "取消"))));
3939
4234
  }
4235
+ function MermaidInPlace() {
4236
+ const s = useS();
4237
+ const enabled = s.cfg.mermaid === true;
4238
+ const dark = s.dark;
4239
+ react.useEffect(() => {
4240
+ if (!enabled) {
4241
+ restoreMermaidBlocks();
4242
+ return;
4243
+ }
4244
+ const d = typeof document !== "undefined" ? document : null;
4245
+ const w = typeof window !== "undefined" ? window : null;
4246
+ if (d === null || d.body === null || w === null || w.MutationObserver === void 0) return;
4247
+ let timer = null;
4248
+ let stopped = false;
4249
+ const scan = () => {
4250
+ if (!stopped) scanMermaidBlocks(dark);
4251
+ };
4252
+ const schedule = () => {
4253
+ if (timer !== null) clearTimeout(timer);
4254
+ timer = setTimeout(scan, 400);
4255
+ };
4256
+ if (mmdLastDark !== null && mmdLastDark !== dark) for (const block of Array.from(d.querySelectorAll(".md-code-block"))) delete block.dataset.vxMmd;
4257
+ mmdLastDark = dark;
4258
+ scan();
4259
+ const observer = new MutationObserver(schedule);
4260
+ observer.observe(d.body, {
4261
+ childList: true,
4262
+ subtree: true,
4263
+ characterData: true
4264
+ });
4265
+ return () => {
4266
+ stopped = true;
4267
+ observer.disconnect();
4268
+ if (timer !== null) {
4269
+ clearTimeout(timer);
4270
+ timer = null;
4271
+ }
4272
+ };
4273
+ }, [enabled, dark]);
4274
+ return null;
4275
+ }
3940
4276
  function MermaidModal() {
3941
4277
  const mm = useS().mermaidModal;
3942
4278
  const [svg, setSvg] = react.useState(null);
@@ -3960,7 +4296,7 @@ window.__ModuleLoader__.load({
3960
4296
  setLoading(false);
3961
4297
  return;
3962
4298
  }
3963
- const r = await renderMermaid(mm.codes[mm.index]);
4299
+ const r = await renderMermaid(mm.codes[mm.index], S.dark);
3964
4300
  if (!alive) return;
3965
4301
  if (r.ok === true) setSvg(r.svg);
3966
4302
  else setErr(r.error);
@@ -4436,6 +4772,7 @@ window.__ModuleLoader__.load({
4436
4772
  };
4437
4773
  }, [s.scrollerEl]);
4438
4774
  const children = [react.createElement(FxCanvas, { key: "fx" })];
4775
+ children.push(react.createElement(MermaidInPlace, { key: "mmd" }));
4439
4776
  children.push(react.createElement(TimelineRail, {
4440
4777
  key: "rail",
4441
4778
  useSessions: props.useSessions,