@opendikw/web-ui 0.1.0-rc.1
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/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/auth/index.d.ts +23 -0
- package/dist/auth/index.js +118 -0
- package/dist/controls/Button.d.ts +14 -0
- package/dist/controls/Button.js +16 -0
- package/dist/controls/EmptyState.d.ts +8 -0
- package/dist/controls/EmptyState.js +5 -0
- package/dist/controls/Field.d.ts +23 -0
- package/dist/controls/Field.js +11 -0
- package/dist/controls/FrontmatterChip.d.ts +16 -0
- package/dist/controls/FrontmatterChip.js +16 -0
- package/dist/controls/IconButton.d.ts +15 -0
- package/dist/controls/IconButton.js +11 -0
- package/dist/controls/MetricCard.d.ts +16 -0
- package/dist/controls/MetricCard.js +11 -0
- package/dist/controls/Notice.d.ts +8 -0
- package/dist/controls/Notice.js +13 -0
- package/dist/controls/SegmentedControl.d.ts +27 -0
- package/dist/controls/SegmentedControl.js +16 -0
- package/dist/controls/SoftLabel.d.ts +15 -0
- package/dist/controls/SoftLabel.js +14 -0
- package/dist/controls/StatusPill.d.ts +6 -0
- package/dist/controls/StatusPill.js +8 -0
- package/dist/controls/cx.d.ts +6 -0
- package/dist/controls/cx.js +8 -0
- package/dist/controls/index.d.ts +11 -0
- package/dist/controls/index.js +11 -0
- package/dist/hooks/index.d.ts +4 -0
- package/dist/hooks/index.js +3 -0
- package/dist/hooks/useAsyncResource.d.ts +7 -0
- package/dist/hooks/useAsyncResource.js +36 -0
- package/dist/hooks/useBilingualReader.d.ts +40 -0
- package/dist/hooks/useBilingualReader.js +154 -0
- package/dist/hooks/usePreviewTranslation.d.ts +24 -0
- package/dist/hooks/usePreviewTranslation.js +43 -0
- package/dist/reader/BilingualView.d.ts +32 -0
- package/dist/reader/BilingualView.js +75 -0
- package/dist/reader/MarkdownView.d.ts +12 -0
- package/dist/reader/MarkdownView.js +94 -0
- package/dist/reader/chart-spec.d.ts +17 -0
- package/dist/reader/chart-spec.js +174 -0
- package/dist/reader/index.d.ts +5 -0
- package/dist/reader/index.js +4 -0
- package/dist/reader/markdown-runtime.d.ts +37 -0
- package/dist/reader/markdown-runtime.js +701 -0
- package/dist/styles/controls.css +546 -0
- package/dist/styles/reader.css +701 -0
- package/dist/styles/tokens.css +200 -0
- package/dist/styles.d.ts +1 -0
- package/dist/theme/index.d.ts +12 -0
- package/dist/theme/index.js +40 -0
- package/package.json +71 -0
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
// Shared markdown rendering runtime for the Base reader. Extracted from
|
|
2
|
+
// MarkdownView so both the single-column reader and the bilingual dual-column
|
|
3
|
+
// view render through the exact same markdown-it instance, sanitizer, and
|
|
4
|
+
// post-render hydration (mermaid / ECharts / authenticated images).
|
|
5
|
+
//
|
|
6
|
+
// `renderMarkdown` renders a whole document; `renderMarkdownBlockHtml` renders
|
|
7
|
+
// one block at a time while sharing a heading-slug env across blocks, so a
|
|
8
|
+
// bilingual column produces the same `id` slugs a whole-document render would.
|
|
9
|
+
// `runMarkdownEffects` / `useMarkdownEffects` hydrate the rendered HTML.
|
|
10
|
+
import katex from "katex";
|
|
11
|
+
import "katex/dist/katex.min.css";
|
|
12
|
+
import MarkdownIt from "markdown-it";
|
|
13
|
+
import { useEffect } from "react";
|
|
14
|
+
import { parseDetailsOpenAttribute, rawDetailsPattern, uniqueHeadingSlug, } from "@opendikw/web-client/document";
|
|
15
|
+
import { buildChartOption, isChartSpec, isChartType, parseChartFromDetails, } from "./chart-spec.js";
|
|
16
|
+
import { buildRequestUrl } from "@opendikw/web-client/core";
|
|
17
|
+
import { basename } from "@opendikw/web-client/document";
|
|
18
|
+
import { isRemoteRef } from "@opendikw/web-client/import";
|
|
19
|
+
const markdown = new MarkdownIt({
|
|
20
|
+
html: false,
|
|
21
|
+
linkify: true,
|
|
22
|
+
typographer: true,
|
|
23
|
+
});
|
|
24
|
+
installWikiLinks(markdown);
|
|
25
|
+
installMath(markdown);
|
|
26
|
+
installObsidianImages(markdown);
|
|
27
|
+
installStandardImages(markdown);
|
|
28
|
+
installRendererRules(markdown);
|
|
29
|
+
/** Render a whole markdown document to sanitized HTML. */
|
|
30
|
+
export function renderMarkdown(body, ctx) {
|
|
31
|
+
return renderWithEnv(body, ctx, { dikwContext: ctx });
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Render a single markdown block, threading a shared `env` across calls so
|
|
35
|
+
* heading-slug deduplication (and thus the `id` attributes anchor links target)
|
|
36
|
+
* stays consistent with a whole-document render. Callers create one `env`
|
|
37
|
+
* object and pass it for every block in document order.
|
|
38
|
+
*/
|
|
39
|
+
export function renderMarkdownBlockHtml(body, ctx, env) {
|
|
40
|
+
env.dikwContext = ctx;
|
|
41
|
+
return renderWithEnv(body, ctx, env);
|
|
42
|
+
}
|
|
43
|
+
function renderWithEnv(body, ctx, env) {
|
|
44
|
+
const { markdownBody: bodyWithoutDetails, details } = extractSafeDetails(body, ctx);
|
|
45
|
+
const { markdownBody, tables } = extractSafeRawTables(bodyWithoutDetails);
|
|
46
|
+
const html = markdown.render(markdownBody, env);
|
|
47
|
+
return restoreSafeBlocks(restoreSafeRawTables(html, tables), details);
|
|
48
|
+
}
|
|
49
|
+
// markdown-it 15 widened `Token.attrGet` to `string | number | null`; every attr read
|
|
50
|
+
// here is a string markdown-it or our own rules set.
|
|
51
|
+
function attrText(token, name) {
|
|
52
|
+
const value = token.attrGet(name);
|
|
53
|
+
return value == null ? null : String(value);
|
|
54
|
+
}
|
|
55
|
+
function installWikiLinks(md) {
|
|
56
|
+
md.inline.ruler.before("emphasis", "wikilink", (state, silent) => {
|
|
57
|
+
const start = state.pos;
|
|
58
|
+
if (state.src.charCodeAt(start) !== 0x5b || state.src.charCodeAt(start + 1) !== 0x5b) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
const end = state.src.indexOf("]]", start + 2);
|
|
62
|
+
if (end < 0) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
if (!silent) {
|
|
66
|
+
const raw = state.src.slice(start + 2, end).trim();
|
|
67
|
+
const [targetPart, labelPart] = raw.split("|", 2);
|
|
68
|
+
const target = targetPart.trim();
|
|
69
|
+
const label = (labelPart ?? targetPart).trim();
|
|
70
|
+
const token = state.push("wikilink", "", 0);
|
|
71
|
+
token.attrSet("data-target", target);
|
|
72
|
+
token.content = label || target;
|
|
73
|
+
}
|
|
74
|
+
state.pos = end + 2;
|
|
75
|
+
return true;
|
|
76
|
+
});
|
|
77
|
+
md.renderer.rules.wikilink = (tokens, index) => {
|
|
78
|
+
const token = tokens[index];
|
|
79
|
+
const target = attrText(token, "data-target") ?? token.content;
|
|
80
|
+
return `<button type="button" class="inline-wikilink" data-wiki-link="${escapeAttribute(target)}">${escapeHtml(token.content)}</button>`;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function installObsidianImages(md) {
|
|
84
|
+
md.inline.ruler.before("emphasis", "obsidian_image", (state, silent) => {
|
|
85
|
+
const src = state.src;
|
|
86
|
+
const start = state.pos;
|
|
87
|
+
if (src.charCodeAt(start) !== 0x21) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (src.charCodeAt(start + 1) !== 0x5b || src.charCodeAt(start + 2) !== 0x5b) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
const close = src.indexOf("]]", start + 3);
|
|
94
|
+
if (close < 0) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
if (!silent) {
|
|
98
|
+
const raw = src.slice(start + 3, close).trim();
|
|
99
|
+
const [pathPart, altPart] = raw.split("|", 2);
|
|
100
|
+
const path = pathPart.trim();
|
|
101
|
+
const alt = (altPart ?? "").trim();
|
|
102
|
+
const token = state.push("obsidian_image", "", 0);
|
|
103
|
+
token.attrSet("data-path", path);
|
|
104
|
+
if (alt) {
|
|
105
|
+
token.attrSet("data-alt", alt);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
state.pos = close + 2;
|
|
109
|
+
return true;
|
|
110
|
+
});
|
|
111
|
+
md.renderer.rules.obsidian_image = (tokens, index, _options, env) => {
|
|
112
|
+
const token = tokens[index];
|
|
113
|
+
const path = attrText(token, "data-path") ?? "";
|
|
114
|
+
const alt = attrText(token, "data-alt") ?? "";
|
|
115
|
+
const ctx = env?.dikwContext;
|
|
116
|
+
const resolved = resolveAssetUrl(path, ctx);
|
|
117
|
+
if (!resolved) {
|
|
118
|
+
return `<span class="md-broken-image" title="asset not found">⚠ ${escapeHtml(path)}</span>`;
|
|
119
|
+
}
|
|
120
|
+
const altText = alt || basename(path);
|
|
121
|
+
if (ctx?.assetToken) {
|
|
122
|
+
return `<img class="markdown-image" data-asset-src="${escapeAttribute(resolved)}" alt="${escapeAttribute(altText)}" loading="lazy" />`;
|
|
123
|
+
}
|
|
124
|
+
return `<img class="markdown-image" src="${escapeAttribute(resolved)}" alt="${escapeAttribute(altText)}" loading="lazy" />`;
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
// Standard CommonMark image syntax (```` / ````).
|
|
128
|
+
// Mirrors installObsidianImages but works on markdown-it's default ``image`` token
|
|
129
|
+
// so local refs land on /v1/assets/<id> instead of leaking to the SPA host.
|
|
130
|
+
//
|
|
131
|
+
// Accepts ``self: Renderer`` as the 5th argument so we can reuse
|
|
132
|
+
// ``renderInlineAsText`` for alt — markdown-it's default behavior is to strip
|
|
133
|
+
// inline markup from alt (CommonMark spec); a hand-rolled ``token.content``
|
|
134
|
+
// would leak literal ``**`` / ``_`` into screen readers.
|
|
135
|
+
function installStandardImages(md) {
|
|
136
|
+
md.renderer.rules.image = (tokens, index, options, env, self) => {
|
|
137
|
+
const token = tokens[index];
|
|
138
|
+
const src = attrText(token, "src") ?? "";
|
|
139
|
+
const title = attrText(token, "title") ?? "";
|
|
140
|
+
const ctx = env?.dikwContext;
|
|
141
|
+
const alt = self.renderInlineAsText(token.children ?? [], options, env);
|
|
142
|
+
const titleAttr = title ? ` title="${escapeAttribute(title)}"` : "";
|
|
143
|
+
// Empty src (``![]()``) and whitespace-only refs are common in drafts and
|
|
144
|
+
// tool-generated markdown — render nothing rather than a noisy ⚠ marker.
|
|
145
|
+
if (!src.trim()) {
|
|
146
|
+
return "";
|
|
147
|
+
}
|
|
148
|
+
if (isRemoteRef(src)) {
|
|
149
|
+
// ``http(s)://``, ``data:``, etc. pass through verbatim — these aren't
|
|
150
|
+
// tracked in PageAsset.original_paths. ``markdown-image`` class IS kept
|
|
151
|
+
// so the CSS in src/styles.css applies uniformly; the auth-hydration
|
|
152
|
+
// selector requires ``data-asset-src`` (absent here), so it stays inert.
|
|
153
|
+
return `<img class="markdown-image" src="${escapeAttribute(src)}" alt="${escapeAttribute(alt)}"${titleAttr} loading="lazy" />`;
|
|
154
|
+
}
|
|
155
|
+
// Two-stage lookup: literal src first, then percent-decoded fallback.
|
|
156
|
+
// markdown-it normalizeLink percent-encodes non-ASCII characters in
|
|
157
|
+
// standard ```` syntax (e.g. ``./封面.png`` → ``./%E5…``) but
|
|
158
|
+
// PageAsset.original_paths stores the raw author input by core's
|
|
159
|
+
// md_inspect. The decode retry is intentionally scoped to this site, NOT
|
|
160
|
+
// pushed into resolveAssetUrl, so Obsidian ``![[...]]`` resolution stays
|
|
161
|
+
// verbatim (its parser doesn't percent-encode and shouldn't get the
|
|
162
|
+
// cross-syntax leniency).
|
|
163
|
+
const decoded = decodePathForDisplay(src);
|
|
164
|
+
const resolved = resolveAssetUrl(src, ctx) ?? (decoded !== src ? resolveAssetUrl(decoded, ctx) : null);
|
|
165
|
+
if (!resolved) {
|
|
166
|
+
// Echo the decoded form so the user sees what they wrote, not
|
|
167
|
+
// ``%E5%B0%81…``.
|
|
168
|
+
return `<span class="md-broken-image" title="asset not found">⚠ ${escapeHtml(decoded)}</span>`;
|
|
169
|
+
}
|
|
170
|
+
if (ctx?.assetToken) {
|
|
171
|
+
return `<img class="markdown-image" data-asset-src="${escapeAttribute(resolved)}" alt="${escapeAttribute(alt)}"${titleAttr} loading="lazy" />`;
|
|
172
|
+
}
|
|
173
|
+
return `<img class="markdown-image" src="${escapeAttribute(resolved)}" alt="${escapeAttribute(alt)}"${titleAttr} loading="lazy" />`;
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/** Decode percent-escapes safely for display; if the string is malformed
|
|
177
|
+
* (rare — markdown-it produces well-formed encoding) return the raw input. */
|
|
178
|
+
function decodePathForDisplay(src) {
|
|
179
|
+
try {
|
|
180
|
+
return decodeURIComponent(src);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return src;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const SHA256_IN_PATH = /(?:^|\/)([0-9a-f]{64})\.[a-z0-9]+$/i;
|
|
187
|
+
function resolveAssetUrl(path, ctx) {
|
|
188
|
+
if (!ctx || !ctx.assets.length) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
const direct = ctx.assets.find((asset) => asset.original_paths.includes(path));
|
|
192
|
+
if (direct) {
|
|
193
|
+
return buildRequestUrl(ctx.assetBaseUrl, direct.url);
|
|
194
|
+
}
|
|
195
|
+
const hashMatch = path.match(SHA256_IN_PATH);
|
|
196
|
+
if (hashMatch) {
|
|
197
|
+
const byId = ctx.assets.find((asset) => asset.asset_id === hashMatch[1]);
|
|
198
|
+
if (byId) {
|
|
199
|
+
return buildRequestUrl(ctx.assetBaseUrl, byId.url);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
function installMath(md) {
|
|
205
|
+
md.inline.ruler.before("escape", "math_inline", (state, silent) => {
|
|
206
|
+
const start = state.pos;
|
|
207
|
+
if (state.src.charCodeAt(start) !== 0x24 || state.src.charCodeAt(start + 1) === 0x24) {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
if (start > 0 && state.src.charCodeAt(start - 1) === 0x5c) {
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
let end = start + 1;
|
|
214
|
+
while ((end = state.src.indexOf("$", end)) >= 0) {
|
|
215
|
+
if (state.src.charCodeAt(end - 1) === 0x5c) {
|
|
216
|
+
end += 1;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const content = state.src.slice(start + 1, end);
|
|
220
|
+
if (!content || content.includes("\n")) {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
if (!silent) {
|
|
224
|
+
const token = state.push("math_inline", "math", 0);
|
|
225
|
+
token.content = content.trim();
|
|
226
|
+
}
|
|
227
|
+
state.pos = end + 1;
|
|
228
|
+
return true;
|
|
229
|
+
}
|
|
230
|
+
return false;
|
|
231
|
+
});
|
|
232
|
+
md.block.ruler.before("fence", "math_block", (state, startLine, endLine, silent) => {
|
|
233
|
+
const start = state.bMarks[startLine] + state.tShift[startLine];
|
|
234
|
+
const max = state.eMarks[startLine];
|
|
235
|
+
if (state.src.slice(start, start + 2) !== "$$") {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
const firstLine = state.src.slice(start + 2, max);
|
|
239
|
+
let content;
|
|
240
|
+
let nextLine = startLine;
|
|
241
|
+
const sameLineClose = firstLine.lastIndexOf("$$");
|
|
242
|
+
if (sameLineClose >= 0 && firstLine.slice(0, sameLineClose).trim().length > 0) {
|
|
243
|
+
content = firstLine.slice(0, sameLineClose);
|
|
244
|
+
nextLine = startLine + 1;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
content = `${firstLine}\n`;
|
|
248
|
+
let found = false;
|
|
249
|
+
while (++nextLine < endLine) {
|
|
250
|
+
const lineStart = state.bMarks[nextLine] + state.tShift[nextLine];
|
|
251
|
+
const lineMax = state.eMarks[nextLine];
|
|
252
|
+
const line = state.src.slice(lineStart, lineMax);
|
|
253
|
+
const close = line.indexOf("$$");
|
|
254
|
+
if (close >= 0) {
|
|
255
|
+
content += line.slice(0, close);
|
|
256
|
+
found = true;
|
|
257
|
+
nextLine += 1;
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
content += `${line}\n`;
|
|
261
|
+
}
|
|
262
|
+
if (!found) {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (!silent) {
|
|
267
|
+
const token = state.push("math_block", "math", 0);
|
|
268
|
+
token.block = true;
|
|
269
|
+
token.content = content.trim();
|
|
270
|
+
token.map = [startLine, nextLine];
|
|
271
|
+
}
|
|
272
|
+
state.line = nextLine;
|
|
273
|
+
return true;
|
|
274
|
+
}, { alt: ["paragraph", "reference", "blockquote", "list"] });
|
|
275
|
+
md.renderer.rules.math_inline = (tokens, index) => renderMath(tokens[index].content, false);
|
|
276
|
+
md.renderer.rules.math_block = (tokens, index) => `${renderMath(tokens[index].content, true)}\n`;
|
|
277
|
+
}
|
|
278
|
+
function installRendererRules(md) {
|
|
279
|
+
const defaultRender = md.renderer.rules.link_open ??
|
|
280
|
+
((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options));
|
|
281
|
+
const headingRender = md.renderer.rules.heading_open ??
|
|
282
|
+
((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options));
|
|
283
|
+
md.renderer.rules.link_open = (tokens, index, options, env, self) => {
|
|
284
|
+
const href = attrText(tokens[index], "href") ?? "";
|
|
285
|
+
if (/^https?:\/\//i.test(href)) {
|
|
286
|
+
tokens[index].attrSet("target", "_blank");
|
|
287
|
+
tokens[index].attrSet("rel", "noreferrer");
|
|
288
|
+
}
|
|
289
|
+
return defaultRender(tokens, index, options, env, self);
|
|
290
|
+
};
|
|
291
|
+
md.renderer.rules.heading_open = (tokens, index, options, env, self) => {
|
|
292
|
+
const inline = tokens[index + 1];
|
|
293
|
+
const slug = inline?.type === "inline" && env ? uniqueHeadingSlug(env, inline.content) : "";
|
|
294
|
+
if (slug) {
|
|
295
|
+
tokens[index].attrSet("id", slug);
|
|
296
|
+
}
|
|
297
|
+
return headingRender(tokens, index, options, env, self);
|
|
298
|
+
};
|
|
299
|
+
md.renderer.rules.table_open = () => '<div class="markdown-table-wrap"><table>';
|
|
300
|
+
md.renderer.rules.table_close = () => "</table></div>";
|
|
301
|
+
const fenceRender = (tokens, index) => {
|
|
302
|
+
const token = tokens[index];
|
|
303
|
+
const lang = token.info.trim().split(/\s+/)[0];
|
|
304
|
+
if (lang.toLowerCase() === "mermaid") {
|
|
305
|
+
return renderMermaidShell(token.content);
|
|
306
|
+
}
|
|
307
|
+
const label = lang ? `<div class="code-label">${escapeHtml(lang)}</div>` : "";
|
|
308
|
+
return `<div class="code-block">${label}<pre><code>${escapeHtml(token.content)}</code></pre></div>`;
|
|
309
|
+
};
|
|
310
|
+
md.renderer.rules.fence = fenceRender;
|
|
311
|
+
md.renderer.rules.code_block = fenceRender;
|
|
312
|
+
}
|
|
313
|
+
const rawTablePattern = /<table\b[\s\S]*?<\/table>/gi;
|
|
314
|
+
const allowedTableTags = new Set([
|
|
315
|
+
"table",
|
|
316
|
+
"thead",
|
|
317
|
+
"tbody",
|
|
318
|
+
"tfoot",
|
|
319
|
+
"tr",
|
|
320
|
+
"th",
|
|
321
|
+
"td",
|
|
322
|
+
"caption",
|
|
323
|
+
"colgroup",
|
|
324
|
+
"col",
|
|
325
|
+
"br",
|
|
326
|
+
]);
|
|
327
|
+
const allowedTableAttributes = new Set(["align", "colspan", "rowspan", "scope"]);
|
|
328
|
+
function extractSafeDetails(body, ctx) {
|
|
329
|
+
const details = [];
|
|
330
|
+
const markdownBody = body.replace(rawDetailsPattern, (raw, attributes, summary, content) => {
|
|
331
|
+
const open = parseDetailsOpenAttribute(attributes);
|
|
332
|
+
if (open === null) {
|
|
333
|
+
return raw;
|
|
334
|
+
}
|
|
335
|
+
const summaryText = summary.trim();
|
|
336
|
+
const summaryLower = summaryText.toLowerCase();
|
|
337
|
+
const trimmedContent = content.trim();
|
|
338
|
+
const placeholder = `DIKW_RAW_DETAILS_${details.length}`;
|
|
339
|
+
if (isChartType(summaryLower)) {
|
|
340
|
+
const chartHtml = tryRenderChartPlaceholder(summaryLower, trimmedContent);
|
|
341
|
+
if (chartHtml) {
|
|
342
|
+
details.push({ placeholder, html: chartHtml });
|
|
343
|
+
return `\n\n${placeholder}\n\n`;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const renderedContent = renderMarkdown(trimmedContent, ctx);
|
|
347
|
+
details.push({
|
|
348
|
+
placeholder,
|
|
349
|
+
html: `<details class="markdown-details"${open ? " open" : ""}><summary>${escapeHtml(summaryText)}</summary><div class="markdown-details__body">${renderedContent}</div></details>`,
|
|
350
|
+
});
|
|
351
|
+
return `\n\n${placeholder}\n\n`;
|
|
352
|
+
});
|
|
353
|
+
return { markdownBody, details };
|
|
354
|
+
}
|
|
355
|
+
function tryRenderChartPlaceholder(type, content) {
|
|
356
|
+
const spec = parseChartFromDetails(content, type);
|
|
357
|
+
if (!spec) {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
const encoded = encodeChartSpec(spec);
|
|
361
|
+
const caption = spec.freeText.length
|
|
362
|
+
? `<div class="markdown-chart__caption">${spec.freeText.map(escapeHtml).join("<br/>")}</div>`
|
|
363
|
+
: "";
|
|
364
|
+
return `<div class="markdown-chart" data-chart-type="${escapeAttribute(type)}" data-chart-spec="${escapeAttribute(encoded)}" role="img" aria-label="${escapeAttribute(type)} chart"><div class="markdown-chart__canvas"></div>${caption}</div>`;
|
|
365
|
+
}
|
|
366
|
+
function encodeChartSpec(spec) {
|
|
367
|
+
const json = JSON.stringify(spec);
|
|
368
|
+
const bytes = new TextEncoder().encode(json);
|
|
369
|
+
let binary = "";
|
|
370
|
+
for (const byte of bytes) {
|
|
371
|
+
binary += String.fromCharCode(byte);
|
|
372
|
+
}
|
|
373
|
+
return btoa(binary);
|
|
374
|
+
}
|
|
375
|
+
function decodeChartSpec(encoded) {
|
|
376
|
+
const binary = atob(encoded);
|
|
377
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
378
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
379
|
+
}
|
|
380
|
+
function extractSafeRawTables(body) {
|
|
381
|
+
const tables = [];
|
|
382
|
+
const markdownBody = body.replace(rawTablePattern, (raw) => {
|
|
383
|
+
const html = sanitizeRawTable(raw);
|
|
384
|
+
if (!html) {
|
|
385
|
+
return raw;
|
|
386
|
+
}
|
|
387
|
+
const placeholder = `DIKW_RAW_TABLE_${tables.length}`;
|
|
388
|
+
tables.push({ placeholder, html });
|
|
389
|
+
return `\n\n${placeholder}\n\n`;
|
|
390
|
+
});
|
|
391
|
+
return { markdownBody, tables };
|
|
392
|
+
}
|
|
393
|
+
function restoreSafeBlocks(html, blocks) {
|
|
394
|
+
return blocks.reduce((current, block) => {
|
|
395
|
+
const paragraphPattern = new RegExp(`<p>\\s*${escapeRegExp(block.placeholder)}\\s*</p>`, "g");
|
|
396
|
+
return current.replace(paragraphPattern, block.html).replaceAll(block.placeholder, block.html);
|
|
397
|
+
}, html);
|
|
398
|
+
}
|
|
399
|
+
function restoreSafeRawTables(html, tables) {
|
|
400
|
+
return tables.reduce((current, table) => {
|
|
401
|
+
const paragraphPattern = new RegExp(`<p>\\s*${escapeRegExp(table.placeholder)}\\s*</p>`, "g");
|
|
402
|
+
return current.replace(paragraphPattern, table.html).replaceAll(table.placeholder, table.html);
|
|
403
|
+
}, html);
|
|
404
|
+
}
|
|
405
|
+
function sanitizeRawTable(raw) {
|
|
406
|
+
if (typeof DOMParser === "undefined") {
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
const parser = new DOMParser();
|
|
410
|
+
const doc = parser.parseFromString(raw, "text/html");
|
|
411
|
+
const table = doc.body.firstElementChild;
|
|
412
|
+
if (!(table instanceof HTMLTableElement)) {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
sanitizeTableElement(table);
|
|
416
|
+
return `<div class="markdown-table-wrap">${table.outerHTML}</div>`;
|
|
417
|
+
}
|
|
418
|
+
function sanitizeTableElement(element) {
|
|
419
|
+
for (const child of Array.from(element.children)) {
|
|
420
|
+
const tagName = child.tagName.toLowerCase();
|
|
421
|
+
if (!allowedTableTags.has(tagName)) {
|
|
422
|
+
child.remove();
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
sanitizeTableElement(child);
|
|
426
|
+
}
|
|
427
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
428
|
+
const name = attribute.name.toLowerCase();
|
|
429
|
+
if (name.startsWith("on") || !allowedTableAttributes.has(name)) {
|
|
430
|
+
element.removeAttribute(attribute.name);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function renderMath(content, displayMode) {
|
|
435
|
+
try {
|
|
436
|
+
return katex.renderToString(content, {
|
|
437
|
+
displayMode,
|
|
438
|
+
output: "htmlAndMathml",
|
|
439
|
+
strict: false,
|
|
440
|
+
throwOnError: false,
|
|
441
|
+
trust: false,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
const delimiter = displayMode ? "$$" : "$";
|
|
446
|
+
return escapeHtml(`${delimiter}${content}${delimiter}`);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function renderMermaidShell(source) {
|
|
450
|
+
return `<div class="mermaid-diagram" data-state="pending" data-mermaid-source="${escapeAttribute(encodeURIComponent(source))}"><div class="mermaid-diagram__loading">Rendering diagram...</div><pre class="mermaid-fallback" hidden><code>${escapeHtml(source)}</code></pre></div>`;
|
|
451
|
+
}
|
|
452
|
+
let mermaidRenderSequence = 0;
|
|
453
|
+
async function renderMermaidDiagrams(root, isCancelled) {
|
|
454
|
+
const diagrams = Array.from(root.querySelectorAll(".mermaid-diagram[data-state='pending']"));
|
|
455
|
+
if (!diagrams.length) {
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
let mermaid;
|
|
459
|
+
try {
|
|
460
|
+
mermaid = (await import("mermaid")).default;
|
|
461
|
+
mermaid.initialize({
|
|
462
|
+
startOnLoad: false,
|
|
463
|
+
securityLevel: "strict",
|
|
464
|
+
suppressErrorRendering: true,
|
|
465
|
+
theme: root.ownerDocument.documentElement.dataset.theme === "dark" ? "dark" : "default",
|
|
466
|
+
flowchart: { htmlLabels: false },
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
diagrams.forEach((diagram) => renderMermaidFallback(diagram));
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
for (const diagram of diagrams) {
|
|
474
|
+
const source = readMermaidSource(diagram);
|
|
475
|
+
try {
|
|
476
|
+
const id = `dikw-mermaid-${Date.now()}-${mermaidRenderSequence++}`;
|
|
477
|
+
const result = await mermaid.render(id, source);
|
|
478
|
+
if (isCancelled()) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
diagram.dataset.state = "rendered";
|
|
482
|
+
diagram.innerHTML = result.svg;
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
if (!isCancelled()) {
|
|
486
|
+
renderMermaidFallback(diagram, source);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
function renderMarkdownCharts(root) {
|
|
492
|
+
const placeholders = Array.from(root.querySelectorAll(".markdown-chart[data-chart-spec]"));
|
|
493
|
+
if (!placeholders.length) {
|
|
494
|
+
return () => { };
|
|
495
|
+
}
|
|
496
|
+
const instances = [];
|
|
497
|
+
let cancelled = false;
|
|
498
|
+
void (async () => {
|
|
499
|
+
let echarts;
|
|
500
|
+
try {
|
|
501
|
+
const [core, charts, components, renderers] = await Promise.all([
|
|
502
|
+
import("echarts/core"),
|
|
503
|
+
import("echarts/charts"),
|
|
504
|
+
import("echarts/components"),
|
|
505
|
+
import("echarts/renderers"),
|
|
506
|
+
]);
|
|
507
|
+
echarts = core;
|
|
508
|
+
echarts.use([
|
|
509
|
+
charts.BarChart,
|
|
510
|
+
charts.LineChart,
|
|
511
|
+
charts.ScatterChart,
|
|
512
|
+
charts.HeatmapChart,
|
|
513
|
+
components.GridComponent,
|
|
514
|
+
components.TooltipComponent,
|
|
515
|
+
components.TitleComponent,
|
|
516
|
+
components.VisualMapComponent,
|
|
517
|
+
renderers.CanvasRenderer,
|
|
518
|
+
]);
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
for (const el of placeholders) {
|
|
522
|
+
renderChartFallback(el);
|
|
523
|
+
}
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
if (cancelled) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const theme = root.ownerDocument.documentElement.dataset.theme === "dark" ? "dark" : undefined;
|
|
530
|
+
for (const el of placeholders) {
|
|
531
|
+
if (cancelled) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const encoded = el.dataset.chartSpec ?? "";
|
|
535
|
+
const type = el.dataset.chartType ?? "";
|
|
536
|
+
if (!encoded || !isChartType(type)) {
|
|
537
|
+
renderChartFallback(el);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const canvas = el.querySelector(".markdown-chart__canvas") ?? el;
|
|
541
|
+
try {
|
|
542
|
+
const decoded = decodeChartSpec(encoded);
|
|
543
|
+
if (!isChartSpec(decoded)) {
|
|
544
|
+
throw new Error("invalid chart spec");
|
|
545
|
+
}
|
|
546
|
+
const instance = echarts.init(canvas, theme);
|
|
547
|
+
instances.push(instance);
|
|
548
|
+
instance.setOption(buildChartOption(decoded));
|
|
549
|
+
el.dataset.state = "rendered";
|
|
550
|
+
}
|
|
551
|
+
catch {
|
|
552
|
+
renderChartFallback(el);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
})();
|
|
556
|
+
return () => {
|
|
557
|
+
cancelled = true;
|
|
558
|
+
for (const instance of instances) {
|
|
559
|
+
try {
|
|
560
|
+
instance.dispose();
|
|
561
|
+
}
|
|
562
|
+
catch {
|
|
563
|
+
//
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function renderChartFallback(el) {
|
|
569
|
+
el.dataset.state = "error";
|
|
570
|
+
const encoded = el.dataset.chartSpec ?? "";
|
|
571
|
+
const type = el.dataset.chartType ?? "chart";
|
|
572
|
+
if (!encoded) {
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
const decoded = decodeChartSpec(encoded);
|
|
577
|
+
if (!isChartSpec(decoded)) {
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
el.innerHTML = renderChartFallbackHtml(type, decoded);
|
|
581
|
+
}
|
|
582
|
+
catch {
|
|
583
|
+
/* leave shell as-is */
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function renderChartFallbackHtml(type, spec) {
|
|
587
|
+
const head = spec.headers.map((cell) => `<th>${escapeHtml(cell)}</th>`).join("");
|
|
588
|
+
const body = spec.rows
|
|
589
|
+
.map((row) => `<tr>${row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join("")}</tr>`)
|
|
590
|
+
.join("");
|
|
591
|
+
const table = `<div class="markdown-table-wrap"><table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>`;
|
|
592
|
+
return `<details class="markdown-details" open><summary>${escapeHtml(type)}</summary><div class="markdown-details__body">${table}</div></details>`;
|
|
593
|
+
}
|
|
594
|
+
function hydrateAuthenticatedImages(root, token) {
|
|
595
|
+
if (!token) {
|
|
596
|
+
return () => { };
|
|
597
|
+
}
|
|
598
|
+
const images = Array.from(root.querySelectorAll("img.markdown-image[data-asset-src]"));
|
|
599
|
+
if (!images.length) {
|
|
600
|
+
return () => { };
|
|
601
|
+
}
|
|
602
|
+
const blobUrls = [];
|
|
603
|
+
const controller = new AbortController();
|
|
604
|
+
void (async () => {
|
|
605
|
+
for (const img of images) {
|
|
606
|
+
if (controller.signal.aborted) {
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
const url = img.dataset.assetSrc;
|
|
610
|
+
if (!url) {
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
const response = await fetch(url, {
|
|
615
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
616
|
+
signal: controller.signal,
|
|
617
|
+
});
|
|
618
|
+
if (!response.ok) {
|
|
619
|
+
throw new Error(`asset ${response.status}`);
|
|
620
|
+
}
|
|
621
|
+
const blob = await response.blob();
|
|
622
|
+
if (controller.signal.aborted) {
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
626
|
+
blobUrls.push(objectUrl);
|
|
627
|
+
img.src = objectUrl;
|
|
628
|
+
}
|
|
629
|
+
catch {
|
|
630
|
+
img.dataset.assetState = "error";
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
})();
|
|
634
|
+
return () => {
|
|
635
|
+
controller.abort();
|
|
636
|
+
for (const url of blobUrls) {
|
|
637
|
+
URL.revokeObjectURL(url);
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
function renderMermaidFallback(diagram, source = readMermaidSource(diagram)) {
|
|
642
|
+
diagram.dataset.state = "error";
|
|
643
|
+
diagram.innerHTML = `<div class="mermaid-diagram__error">Mermaid diagram could not be rendered.</div><pre class="code-block mermaid-fallback"><code>${escapeHtml(source)}</code></pre>`;
|
|
644
|
+
}
|
|
645
|
+
function readMermaidSource(diagram) {
|
|
646
|
+
try {
|
|
647
|
+
return decodeURIComponent(diagram.dataset.mermaidSource ?? "");
|
|
648
|
+
}
|
|
649
|
+
catch {
|
|
650
|
+
return "";
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Hydrate rendered markdown HTML inside `root`: render mermaid diagrams, mount
|
|
655
|
+
* ECharts charts, and swap authenticated image placeholders for blob URLs.
|
|
656
|
+
* Returns a disposer that cancels in-flight work and frees chart instances /
|
|
657
|
+
* blob URLs. Pure DOM — no React — so it serves both the single-column reader
|
|
658
|
+
* and the bilingual dual-column view.
|
|
659
|
+
*/
|
|
660
|
+
export function runMarkdownEffects(root, { assetToken }) {
|
|
661
|
+
let cancelled = false;
|
|
662
|
+
void renderMermaidDiagrams(root, () => cancelled);
|
|
663
|
+
const disposeCharts = renderMarkdownCharts(root);
|
|
664
|
+
const disposeImages = hydrateAuthenticatedImages(root, assetToken);
|
|
665
|
+
return () => {
|
|
666
|
+
cancelled = true;
|
|
667
|
+
disposeCharts();
|
|
668
|
+
disposeImages();
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* React wrapper over {@link runMarkdownEffects}. Re-runs whenever `renderKey`
|
|
673
|
+
* (the rendered HTML, or any value that changes when the DOM content does) or
|
|
674
|
+
* `assetToken` changes, mirroring MarkdownView's original `[html, assetToken]`
|
|
675
|
+
* effect dependencies.
|
|
676
|
+
*/
|
|
677
|
+
export function useMarkdownEffects(ref, { renderKey, assetToken }) {
|
|
678
|
+
useEffect(() => {
|
|
679
|
+
const root = ref.current;
|
|
680
|
+
if (!root) {
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
return runMarkdownEffects(root, { assetToken });
|
|
684
|
+
// `renderKey` is an intentional re-run trigger: the DOM is replaced via
|
|
685
|
+
// dangerouslySetInnerHTML by the caller, so effects must re-hydrate the
|
|
686
|
+
// fresh nodes even though renderKey isn't read inside the callback.
|
|
687
|
+
}, [ref, renderKey, assetToken]);
|
|
688
|
+
}
|
|
689
|
+
function escapeHtml(value) {
|
|
690
|
+
return value
|
|
691
|
+
.replace(/&/g, "&")
|
|
692
|
+
.replace(/</g, "<")
|
|
693
|
+
.replace(/>/g, ">")
|
|
694
|
+
.replace(/"/g, """);
|
|
695
|
+
}
|
|
696
|
+
function escapeAttribute(value) {
|
|
697
|
+
return escapeHtml(value).replace(/'/g, "'");
|
|
698
|
+
}
|
|
699
|
+
function escapeRegExp(value) {
|
|
700
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
701
|
+
}
|