@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,40 @@
|
|
|
1
|
+
import type { BilingualBlock } from "../reader/BilingualView.js";
|
|
2
|
+
import { TranslateError, translateBlocks, type TranslateCache } from "@opendikw/web-client/translate";
|
|
3
|
+
interface UseBilingualReaderOptions {
|
|
4
|
+
/** Frontmatter-stripped markdown to read (same content the mono view renders). */
|
|
5
|
+
body: string;
|
|
6
|
+
/** Whether the sidecar translator is configured; gates whether translation runs. */
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
targetLang?: string;
|
|
9
|
+
/** IndexedDB-backed cache (or a test shim); null/undefined → no caching. */
|
|
10
|
+
cache?: TranslateCache | null;
|
|
11
|
+
/** Override for tests. */
|
|
12
|
+
translate?: typeof translateBlocks;
|
|
13
|
+
}
|
|
14
|
+
export interface BilingualReader {
|
|
15
|
+
/** Toggle is ON (the dual-column view should render). */
|
|
16
|
+
active: boolean;
|
|
17
|
+
/** A chunked translation is in flight; batches stream in and fill `blocks`
|
|
18
|
+
* progressively until the final result lands. */
|
|
19
|
+
translating: boolean;
|
|
20
|
+
/** The translation came back from cache (drives the "cached" chip). */
|
|
21
|
+
cached: boolean;
|
|
22
|
+
error: TranslateError | null;
|
|
23
|
+
/** Ordered blocks with translations filled in (undefined until they arrive). */
|
|
24
|
+
blocks: BilingualBlock[];
|
|
25
|
+
toggle: () => void;
|
|
26
|
+
retranslate: () => void;
|
|
27
|
+
/** Re-translate, bypassing the cache (force fresh). */
|
|
28
|
+
forceRetranslate: () => void;
|
|
29
|
+
cancel: () => void;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Drives the Base reader's bilingual mode for one page: splits the body into
|
|
33
|
+
* blocks, sends the text blocks to /web/translate, and maps the result back
|
|
34
|
+
* 1:1. The translation is chunked server-side, so partial batches arrive via
|
|
35
|
+
* `onProgress` and fill the columns progressively; the final result then
|
|
36
|
+
* overwrites them. Resets when the body changes; aborts in-flight work on
|
|
37
|
+
* cancel / page switch.
|
|
38
|
+
*/
|
|
39
|
+
export declare function useBilingualReader({ body, enabled, targetLang, cache, translate, }: UseBilingualReaderOptions): BilingualReader;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { splitMarkdownBlocks } from "@opendikw/web-client/document";
|
|
3
|
+
import { TranslateError, translateBlocks, } from "@opendikw/web-client/translate";
|
|
4
|
+
/**
|
|
5
|
+
* Drives the Base reader's bilingual mode for one page: splits the body into
|
|
6
|
+
* blocks, sends the text blocks to /web/translate, and maps the result back
|
|
7
|
+
* 1:1. The translation is chunked server-side, so partial batches arrive via
|
|
8
|
+
* `onProgress` and fill the columns progressively; the final result then
|
|
9
|
+
* overwrites them. Resets when the body changes; aborts in-flight work on
|
|
10
|
+
* cancel / page switch.
|
|
11
|
+
*/
|
|
12
|
+
export function useBilingualReader({ body, enabled, targetLang, cache, translate = translateBlocks, }) {
|
|
13
|
+
const [active, setActive] = useState(false);
|
|
14
|
+
const [translating, setTranslating] = useState(false);
|
|
15
|
+
const [cached, setCached] = useState(false);
|
|
16
|
+
const [error, setError] = useState(null);
|
|
17
|
+
const [translations, setTranslations] = useState(null);
|
|
18
|
+
// Progressive reveal buffer: filled as batches arrive (sparse — `undefined`
|
|
19
|
+
// slots still show a skeleton). The complete `translations` takes precedence
|
|
20
|
+
// once the job finishes; this is cleared on reset/cancel.
|
|
21
|
+
const [partial, setPartial] = useState(null);
|
|
22
|
+
const abortRef = useRef(null);
|
|
23
|
+
const runIdRef = useRef(0);
|
|
24
|
+
const blocks = useMemo(() => splitMarkdownBlocks(body), [body]);
|
|
25
|
+
const textBlocks = useMemo(() => blocks.filter((b) => b.kind === "text").map((b) => b.md), [blocks]);
|
|
26
|
+
const run = useCallback((refresh = false) => {
|
|
27
|
+
abortRef.current?.abort();
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
abortRef.current = controller;
|
|
30
|
+
const runId = ++runIdRef.current;
|
|
31
|
+
setTranslating(true);
|
|
32
|
+
setError(null);
|
|
33
|
+
setCached(false);
|
|
34
|
+
setPartial(null);
|
|
35
|
+
void translate(textBlocks, {
|
|
36
|
+
targetLang,
|
|
37
|
+
signal: controller.signal,
|
|
38
|
+
cache,
|
|
39
|
+
refresh,
|
|
40
|
+
onProgress: (e) => {
|
|
41
|
+
if (runIdRef.current !== runId)
|
|
42
|
+
return;
|
|
43
|
+
if (e.phase === "cache_hit") {
|
|
44
|
+
setCached(true);
|
|
45
|
+
}
|
|
46
|
+
else if (e.phase === "partial") {
|
|
47
|
+
setPartial((prev) => {
|
|
48
|
+
const next = prev
|
|
49
|
+
? prev.slice()
|
|
50
|
+
: new Array(textBlocks.length).fill(undefined);
|
|
51
|
+
for (const { i, tr } of e.blocks) {
|
|
52
|
+
if (i >= 0 && i < next.length)
|
|
53
|
+
next[i] = tr;
|
|
54
|
+
}
|
|
55
|
+
return next;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
.then((result) => {
|
|
61
|
+
if (runIdRef.current !== runId)
|
|
62
|
+
return;
|
|
63
|
+
setTranslations(result);
|
|
64
|
+
setTranslating(false);
|
|
65
|
+
})
|
|
66
|
+
.catch((err) => {
|
|
67
|
+
if (runIdRef.current !== runId)
|
|
68
|
+
return;
|
|
69
|
+
// Abort is intentional (cancel / page switch) — leave state to the caller.
|
|
70
|
+
if (err instanceof TranslateError && err.code === "aborted")
|
|
71
|
+
return;
|
|
72
|
+
setError(err instanceof TranslateError
|
|
73
|
+
? err
|
|
74
|
+
: new TranslateError("translator_api", err instanceof Error ? err.message : String(err)));
|
|
75
|
+
setTranslating(false);
|
|
76
|
+
});
|
|
77
|
+
}, [textBlocks, targetLang, cache, translate]);
|
|
78
|
+
// Reset everything when the page body changes — a new document starts in the
|
|
79
|
+
// single-column (mono) view, and any in-flight translation is abandoned.
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
runIdRef.current += 1;
|
|
82
|
+
abortRef.current?.abort();
|
|
83
|
+
abortRef.current = null;
|
|
84
|
+
setActive(false);
|
|
85
|
+
setTranslating(false);
|
|
86
|
+
setCached(false);
|
|
87
|
+
setError(null);
|
|
88
|
+
setTranslations(null);
|
|
89
|
+
setPartial(null);
|
|
90
|
+
}, [body]);
|
|
91
|
+
// Stop any in-flight request if the component unmounts.
|
|
92
|
+
useEffect(() => () => abortRef.current?.abort(), []);
|
|
93
|
+
const toggle = useCallback(() => {
|
|
94
|
+
if (!enabled)
|
|
95
|
+
return;
|
|
96
|
+
if (active) {
|
|
97
|
+
// Only hide the dual column — do NOT abort an in-flight translation.
|
|
98
|
+
// Letting it run to completion fills `translations` and writes the cache,
|
|
99
|
+
// so toggling back shows the finished (or still-streaming) result instead
|
|
100
|
+
// of discarding the work and re-translating from scratch on every click.
|
|
101
|
+
setActive(false);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
setActive(true);
|
|
105
|
+
// Start a translation only when one isn't already done or in flight for this
|
|
106
|
+
// page (so toggling back mid-translation doesn't kick off a second run).
|
|
107
|
+
if (!translations && !translating)
|
|
108
|
+
run();
|
|
109
|
+
}, [enabled, active, translations, translating, run]);
|
|
110
|
+
const retranslate = useCallback(() => {
|
|
111
|
+
if (!enabled)
|
|
112
|
+
return;
|
|
113
|
+
run();
|
|
114
|
+
}, [enabled, run]);
|
|
115
|
+
// Like retranslate, but bypasses the cache read so it always re-translates
|
|
116
|
+
// (the reader's "再翻译一次" action). The fresh result overwrites the cache.
|
|
117
|
+
const forceRetranslate = useCallback(() => {
|
|
118
|
+
if (!enabled)
|
|
119
|
+
return;
|
|
120
|
+
run(true);
|
|
121
|
+
}, [enabled, run]);
|
|
122
|
+
const cancel = useCallback(() => {
|
|
123
|
+
abortRef.current?.abort();
|
|
124
|
+
runIdRef.current += 1;
|
|
125
|
+
setActive(false);
|
|
126
|
+
setTranslating(false);
|
|
127
|
+
setPartial(null);
|
|
128
|
+
}, []);
|
|
129
|
+
const biBlocks = useMemo(() => {
|
|
130
|
+
// The complete result wins; until it lands, fall back to the progressive
|
|
131
|
+
// partial buffer so already-translated paragraphs show while the rest load.
|
|
132
|
+
const source = translations ?? partial;
|
|
133
|
+
let textIndex = 0;
|
|
134
|
+
return blocks.map((block) => {
|
|
135
|
+
if (block.kind === "special") {
|
|
136
|
+
return { kind: "special", source: block.md };
|
|
137
|
+
}
|
|
138
|
+
const translation = source ? source[textIndex] : undefined;
|
|
139
|
+
textIndex += 1;
|
|
140
|
+
return { kind: "text", source: block.md, translation };
|
|
141
|
+
});
|
|
142
|
+
}, [blocks, translations, partial]);
|
|
143
|
+
return {
|
|
144
|
+
active,
|
|
145
|
+
translating,
|
|
146
|
+
cached,
|
|
147
|
+
error,
|
|
148
|
+
blocks: biBlocks,
|
|
149
|
+
toggle,
|
|
150
|
+
retranslate,
|
|
151
|
+
forceRetranslate,
|
|
152
|
+
cancel,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type TranslateCache } from "@opendikw/web-client/translate";
|
|
2
|
+
interface UsePreviewTranslationOptions {
|
|
3
|
+
/** Fire only when warranted (translated-column click on an English target —
|
|
4
|
+
* the caller decides). Disabled → the originals pass through untouched. */
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
title: string;
|
|
7
|
+
summary: string;
|
|
8
|
+
cache: TranslateCache | null;
|
|
9
|
+
}
|
|
10
|
+
export interface PreviewTranslation {
|
|
11
|
+
/** Translated title / summary, or null while pending, disabled, or failed. */
|
|
12
|
+
title: string | null;
|
|
13
|
+
summary: string | null;
|
|
14
|
+
/** True once the translated pair is showing (drives the AI badge). */
|
|
15
|
+
translated: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Translates a wikilink-preview card's title + summary via /web/translate (two
|
|
19
|
+
* tiny blocks, shared IndexedDB cache, so a revisited card is instant). The
|
|
20
|
+
* original text shows until the translation lands; any failure falls back
|
|
21
|
+
* silently — the card is an enhancement, not a load-bearing surface.
|
|
22
|
+
*/
|
|
23
|
+
export declare function usePreviewTranslation({ enabled, title, summary, cache, }: UsePreviewTranslationOptions): PreviewTranslation;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { useEffect, useState } from "react";
|
|
2
|
+
import { translateBlocks } from "@opendikw/web-client/translate";
|
|
3
|
+
// NUL separator — unambiguous even when the title itself contains spaces.
|
|
4
|
+
const keyOf = (title, summary) => `${title}\u0000${summary}`;
|
|
5
|
+
/**
|
|
6
|
+
* Translates a wikilink-preview card's title + summary via /web/translate (two
|
|
7
|
+
* tiny blocks, shared IndexedDB cache, so a revisited card is instant). The
|
|
8
|
+
* original text shows until the translation lands; any failure falls back
|
|
9
|
+
* silently — the card is an enhancement, not a load-bearing surface.
|
|
10
|
+
*/
|
|
11
|
+
export function usePreviewTranslation({ enabled, title, summary, cache, }) {
|
|
12
|
+
// `result.key` ties a result to the inputs that produced it, so a
|
|
13
|
+
// late-resolving translation for a previous card never bleeds into this one.
|
|
14
|
+
const [result, setResult] = useState(null);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
if (!enabled)
|
|
17
|
+
return undefined;
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
void translateBlocks([title, summary], {
|
|
20
|
+
cache: cache ?? undefined,
|
|
21
|
+
signal: controller.signal,
|
|
22
|
+
})
|
|
23
|
+
.then(([trTitle, trSummary]) => {
|
|
24
|
+
// A non-empty source block that came back empty is a dropped/failed
|
|
25
|
+
// translation — fall back to the originals (no AI badge) rather than show a
|
|
26
|
+
// half-translated card. (`title` is always a non-empty input; `summary`
|
|
27
|
+
// may legitimately be empty, so only a non-empty summary must translate.)
|
|
28
|
+
if (!trTitle?.trim() || (summary.trim() && !trSummary?.trim()))
|
|
29
|
+
return;
|
|
30
|
+
setResult({ key: keyOf(title, summary), title: trTitle ?? "", summary: trSummary ?? "" });
|
|
31
|
+
})
|
|
32
|
+
.catch(() => {
|
|
33
|
+
// Silent fallback to the original text.
|
|
34
|
+
});
|
|
35
|
+
return () => controller.abort();
|
|
36
|
+
}, [enabled, title, summary, cache]);
|
|
37
|
+
const fresh = enabled && result && result.key === keyOf(title, summary) ? result : null;
|
|
38
|
+
return {
|
|
39
|
+
title: fresh ? fresh.title : null,
|
|
40
|
+
summary: fresh ? fresh.summary : null,
|
|
41
|
+
translated: fresh !== null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type MarkdownContext } from "./markdown-runtime.js";
|
|
2
|
+
export type BilingualSide = "src" | "tr";
|
|
3
|
+
export interface BilingualBlock {
|
|
4
|
+
kind: "text" | "special";
|
|
5
|
+
/** Original markdown for this block (rendered in the left / source column). */
|
|
6
|
+
source: string;
|
|
7
|
+
/**
|
|
8
|
+
* Translated markdown — text blocks only, and only once the translation has
|
|
9
|
+
* arrived. While it is `undefined` (and `translating` is true) the column
|
|
10
|
+
* shows a shimmer skeleton in its place. Special blocks never have one.
|
|
11
|
+
*/
|
|
12
|
+
translation?: string;
|
|
13
|
+
}
|
|
14
|
+
interface BilingualViewProps {
|
|
15
|
+
blocks: BilingualBlock[];
|
|
16
|
+
ctx: MarkdownContext;
|
|
17
|
+
/** True while the chunked translation is in flight; pairs whose translation
|
|
18
|
+
* has not arrived yet show a skeleton, the rest show their text. */
|
|
19
|
+
translating: boolean;
|
|
20
|
+
onWikiLink?: (target: string, side: BilingualSide) => void;
|
|
21
|
+
/** Column header labels, resolved to the active locale by the caller. */
|
|
22
|
+
sourceColHead: string;
|
|
23
|
+
trColHead: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Paragraph-aligned dual-column reader. Each text block is rendered once per
|
|
27
|
+
* column (source markdown left, translated markdown right); special blocks
|
|
28
|
+
* (code, tables, charts, display math, rules) render once, centered, and are
|
|
29
|
+
* never translated. Both columns share one post-render hydration pass.
|
|
30
|
+
*/
|
|
31
|
+
export declare function BilingualView({ blocks, ctx, translating, onWikiLink, sourceColHead, trColHead, }: BilingualViewProps): import("react").JSX.Element;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useMemo, useRef } from "react";
|
|
3
|
+
import { renderMarkdownBlockHtml, useMarkdownEffects, } from "./markdown-runtime.js";
|
|
4
|
+
/**
|
|
5
|
+
* Paragraph-aligned dual-column reader. Each text block is rendered once per
|
|
6
|
+
* column (source markdown left, translated markdown right); special blocks
|
|
7
|
+
* (code, tables, charts, display math, rules) render once, centered, and are
|
|
8
|
+
* never translated. Both columns share one post-render hydration pass.
|
|
9
|
+
*/
|
|
10
|
+
export function BilingualView({ blocks, ctx, translating, onWikiLink, sourceColHead, trColHead, }) {
|
|
11
|
+
const rootRef = useRef(null);
|
|
12
|
+
const html = useMemo(() => buildStackHtml(blocks, ctx, translating), [blocks, ctx, translating]);
|
|
13
|
+
// Memoize the wrapper object so React's dangerouslySetInnerHTML diff is a
|
|
14
|
+
// no-op when `html` is unchanged — otherwise it would re-set innerHTML and
|
|
15
|
+
// wipe the chart / mermaid / image DOM the effect below hydrates.
|
|
16
|
+
const innerHtml = useMemo(() => ({ __html: html }), [html]);
|
|
17
|
+
useMarkdownEffects(rootRef, { renderKey: html, assetToken: ctx.assetToken });
|
|
18
|
+
function handleClick(event) {
|
|
19
|
+
const node = event.target;
|
|
20
|
+
const link = node.closest("[data-wiki-link]");
|
|
21
|
+
const target = link?.dataset.wikiLink;
|
|
22
|
+
if (target) {
|
|
23
|
+
event.preventDefault();
|
|
24
|
+
const side = link.closest(".bi-block--tr") ? "tr" : "src";
|
|
25
|
+
onWikiLink?.(target, side);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const anchor = node.closest("a[href]");
|
|
29
|
+
const href = anchor?.getAttribute("href") ?? "";
|
|
30
|
+
if (href.startsWith("#") && href.length > 1) {
|
|
31
|
+
event.preventDefault();
|
|
32
|
+
const root = rootRef.current;
|
|
33
|
+
const targetEl = root?.ownerDocument.getElementById(decodeAnchorTarget(href.slice(1)));
|
|
34
|
+
if (targetEl && root?.contains(targetEl)) {
|
|
35
|
+
targetEl.scrollIntoView({ block: "start", behavior: "smooth" });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return (_jsxs("div", { className: "markdown-body bilingual-cols", ref: rootRef, onClick: handleClick, children: [_jsxs("div", { className: "bi-colhead", "aria-hidden": "true", children: [_jsx("span", { children: sourceColHead }), _jsx("span", { children: trColHead })] }), _jsx("div", { className: "bilingual-stack", dangerouslySetInnerHTML: innerHtml })] }));
|
|
40
|
+
}
|
|
41
|
+
function buildStackHtml(blocks, ctx, translating) {
|
|
42
|
+
// Separate envs per column so heading-slug dedup counters don't bleed across
|
|
43
|
+
// columns; the translated column is prefixed so its ids can't collide with
|
|
44
|
+
// the source column's in the same DOM.
|
|
45
|
+
const srcEnv = {};
|
|
46
|
+
const trEnv = { headingSlugPrefix: "tr-" };
|
|
47
|
+
return blocks
|
|
48
|
+
.map((block) => {
|
|
49
|
+
const srcHtml = renderMarkdownBlockHtml(block.source, ctx, srcEnv);
|
|
50
|
+
if (block.kind === "special") {
|
|
51
|
+
return `<div class="bi-pair--special"><div class="bi-special">${srcHtml}</div></div>`;
|
|
52
|
+
}
|
|
53
|
+
const trHtml = block.translation !== undefined
|
|
54
|
+
? renderMarkdownBlockHtml(block.translation, ctx, trEnv)
|
|
55
|
+
: "";
|
|
56
|
+
// Per-block loading: a pair shows its skeleton only until ITS translation
|
|
57
|
+
// arrives, so batches reveal independently instead of all at the end.
|
|
58
|
+
const loading = block.translation === undefined && translating;
|
|
59
|
+
return (`<div class="bi-pair${loading ? " is-loading" : ""}">` +
|
|
60
|
+
`<div class="bi-block bi-block--src">${srcHtml}</div>` +
|
|
61
|
+
`<div class="bi-block bi-block--tr">` +
|
|
62
|
+
`<div class="bi-skeleton" aria-hidden="true"><span></span><span></span><span></span></div>` +
|
|
63
|
+
`<div class="bi-tr-text">${trHtml}</div>` +
|
|
64
|
+
`</div></div>`);
|
|
65
|
+
})
|
|
66
|
+
.join("");
|
|
67
|
+
}
|
|
68
|
+
function decodeAnchorTarget(value) {
|
|
69
|
+
try {
|
|
70
|
+
return decodeURIComponent(value);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { PageAsset } from "@opendikw/web-client/types";
|
|
2
|
+
interface MarkdownViewProps {
|
|
3
|
+
body: string;
|
|
4
|
+
fallbackTitle?: string | null;
|
|
5
|
+
onWikiLink?: (target: string) => void;
|
|
6
|
+
showFrontmatter?: boolean;
|
|
7
|
+
assets?: PageAsset[];
|
|
8
|
+
assetBaseUrl?: string;
|
|
9
|
+
assetToken?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function MarkdownView({ body, fallbackTitle, onWikiLink, showFrontmatter, assets, assetBaseUrl, assetToken, }: MarkdownViewProps): import("react").JSX.Element;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useMemo, useRef } from "react";
|
|
3
|
+
import { parseMarkdownDocument, slugifyHeading, } from "@opendikw/web-client/document";
|
|
4
|
+
import { FrontmatterChip } from "../controls/FrontmatterChip.js";
|
|
5
|
+
import { renderMarkdown, useMarkdownEffects } from "./markdown-runtime.js";
|
|
6
|
+
export function MarkdownView({ body, fallbackTitle, onWikiLink, showFrontmatter = true, assets, assetBaseUrl, assetToken, }) {
|
|
7
|
+
const bodyRef = useRef(null);
|
|
8
|
+
const ctx = useMemo(() => ({
|
|
9
|
+
assets: assets ?? [],
|
|
10
|
+
assetBaseUrl: assetBaseUrl ?? "",
|
|
11
|
+
assetToken: assetToken ?? "",
|
|
12
|
+
}), [assets, assetBaseUrl, assetToken]);
|
|
13
|
+
const { html, meta, needsFallbackTitle } = useMemo(() => {
|
|
14
|
+
const parsed = parseMarkdownDocument(body, { stripDuplicateTitle: false });
|
|
15
|
+
return {
|
|
16
|
+
html: renderMarkdown(parsed.body, ctx),
|
|
17
|
+
meta: parsed.meta,
|
|
18
|
+
needsFallbackTitle: Boolean(fallbackTitle && !hasTopHeading(parsed.body)),
|
|
19
|
+
};
|
|
20
|
+
}, [body, ctx, fallbackTitle]);
|
|
21
|
+
// React diffs `dangerouslySetInnerHTML` by the wrapping object's identity, not
|
|
22
|
+
// by `__html` string equality, so a fresh `{ __html: html }` literal on every
|
|
23
|
+
// render makes React re-set `innerHTML` on every parent state change — which
|
|
24
|
+
// wipes any DOM mutations from mermaid / chart / image hydration done in the
|
|
25
|
+
// effect below. Memoize the wrapper so the diff is a no-op when `html` stays
|
|
26
|
+
// the same value.
|
|
27
|
+
const innerHtml = useMemo(() => ({ __html: html }), [html]);
|
|
28
|
+
useMarkdownEffects(bodyRef, { renderKey: html, assetToken: ctx.assetToken });
|
|
29
|
+
function handleClick(event) {
|
|
30
|
+
const element = event.target.closest("[data-wiki-link]");
|
|
31
|
+
const target = element?.dataset.wikiLink;
|
|
32
|
+
if (target) {
|
|
33
|
+
event.preventDefault();
|
|
34
|
+
onWikiLink?.(target);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const anchor = event.target.closest("a[href]");
|
|
38
|
+
const href = anchor?.getAttribute("href") ?? "";
|
|
39
|
+
if (href.startsWith("#") && href.length > 1) {
|
|
40
|
+
event.preventDefault();
|
|
41
|
+
const targetElement = findDocumentAnchor(event.currentTarget, href.slice(1));
|
|
42
|
+
targetElement?.scrollIntoView({ block: "start", behavior: "smooth" });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return (_jsxs("article", { className: "markdown-view", onClick: handleClick, children: [showFrontmatter ? _jsx(FrontmatterSummary, { meta: meta }) : null, needsFallbackTitle ? _jsx("h1", { className: "markdown-fallback-title", children: fallbackTitle }) : null, _jsx("div", { ref: bodyRef, className: "markdown-body", dangerouslySetInnerHTML: innerHtml })] }));
|
|
46
|
+
}
|
|
47
|
+
function hasTopHeading(body) {
|
|
48
|
+
return /^#\s+.+$/m.test(body);
|
|
49
|
+
}
|
|
50
|
+
function FrontmatterSummary({ meta }) {
|
|
51
|
+
const tags = asList(meta.tags);
|
|
52
|
+
const sources = asList(meta.sources);
|
|
53
|
+
const rows = [
|
|
54
|
+
["id", meta.id],
|
|
55
|
+
["type", meta.type ?? meta.kind],
|
|
56
|
+
["updated", meta.updated],
|
|
57
|
+
["status", meta.status],
|
|
58
|
+
].filter((row) => typeof row[1] === "string" && row[1].length > 0);
|
|
59
|
+
if (!rows.length && !tags.length && !sources.length) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
return (_jsxs("section", { className: "frontmatter-summary", "aria-label": "Document metadata", children: [rows.map(([label, value]) => (_jsxs(FrontmatterChip, { children: [_jsx("strong", { children: label }), value] }, label))), tags.map((tag) => (_jsxs(FrontmatterChip, { variant: "tag", children: ["#", tag] }, `tag-${tag}`))), sources.map((source) => (_jsx(FrontmatterChip, { variant: "source", children: source }, `source-${source}`)))] }));
|
|
63
|
+
}
|
|
64
|
+
function asList(value) {
|
|
65
|
+
if (Array.isArray(value)) {
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
if (typeof value === "string" && value) {
|
|
69
|
+
return [value];
|
|
70
|
+
}
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
function findDocumentAnchor(root, rawTarget) {
|
|
74
|
+
const target = decodeAnchorTarget(rawTarget);
|
|
75
|
+
const exact = root.ownerDocument.getElementById(target);
|
|
76
|
+
if (exact instanceof HTMLElement && root.contains(exact)) {
|
|
77
|
+
return exact;
|
|
78
|
+
}
|
|
79
|
+
const slug = slugifyHeading(target);
|
|
80
|
+
const slugMatch = slug ? root.ownerDocument.getElementById(slug) : null;
|
|
81
|
+
if (slugMatch instanceof HTMLElement && root.contains(slugMatch)) {
|
|
82
|
+
return slugMatch;
|
|
83
|
+
}
|
|
84
|
+
const headings = Array.from(root.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]"));
|
|
85
|
+
return headings.find((heading) => heading.id.startsWith(slug || target)) ?? null;
|
|
86
|
+
}
|
|
87
|
+
function decodeAnchorTarget(value) {
|
|
88
|
+
try {
|
|
89
|
+
return decodeURIComponent(value);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { EChartsOption } from "echarts";
|
|
2
|
+
export type ChartType = "bar" | "heatmap" | "line" | "scatter";
|
|
3
|
+
export interface ChartSpec {
|
|
4
|
+
type: ChartType;
|
|
5
|
+
headers: string[];
|
|
6
|
+
rows: string[][];
|
|
7
|
+
freeText: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare function parseChartFromDetails(content: string, type: ChartType): ChartSpec | null;
|
|
10
|
+
export declare function buildBarOption(spec: ChartSpec): EChartsOption;
|
|
11
|
+
export declare function buildLineOption(spec: ChartSpec): EChartsOption;
|
|
12
|
+
export declare function buildScatterOption(spec: ChartSpec): EChartsOption;
|
|
13
|
+
export declare function buildHeatmapOption(spec: ChartSpec): EChartsOption;
|
|
14
|
+
export declare function buildChartOption(spec: ChartSpec): EChartsOption;
|
|
15
|
+
export declare const CHART_TYPES: readonly ChartType[];
|
|
16
|
+
export declare function isChartType(value: string): value is ChartType;
|
|
17
|
+
export declare function isChartSpec(value: unknown): value is ChartSpec;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
const ALIGNMENT_CELL = /^:?-+:?$/;
|
|
2
|
+
function isPipeRow(line) {
|
|
3
|
+
return line.includes("|");
|
|
4
|
+
}
|
|
5
|
+
function isAlignmentRow(cells) {
|
|
6
|
+
return cells.length > 0 && cells.every((cell) => ALIGNMENT_CELL.test(cell.trim()));
|
|
7
|
+
}
|
|
8
|
+
export function parseChartFromDetails(content, type) {
|
|
9
|
+
const lines = content.split("\n").map((line) => line.replace(/\s+$/, ""));
|
|
10
|
+
const tableLines = [];
|
|
11
|
+
const freeText = [];
|
|
12
|
+
let inTable = false;
|
|
13
|
+
for (const line of lines) {
|
|
14
|
+
if (isPipeRow(line)) {
|
|
15
|
+
tableLines.push(line);
|
|
16
|
+
inTable = true;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (inTable && line.trim() === "") {
|
|
20
|
+
inTable = false;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (line.trim() !== "") {
|
|
24
|
+
freeText.push(line.trim());
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (tableLines.length < 2) {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
const cells = tableLines.map(splitPipeRow);
|
|
31
|
+
const headers = cells[0];
|
|
32
|
+
const remaining = cells.slice(1);
|
|
33
|
+
const dataRows = remaining.filter((row) => !isAlignmentRow(row));
|
|
34
|
+
if (dataRows.length === 0) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
type,
|
|
39
|
+
headers,
|
|
40
|
+
rows: dataRows,
|
|
41
|
+
freeText,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function splitPipeRow(line) {
|
|
45
|
+
const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
|
|
46
|
+
return trimmed.split("|").map((cell) => cell.trim());
|
|
47
|
+
}
|
|
48
|
+
const LEADING_NUMERIC = /^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/;
|
|
49
|
+
function toNumber(cell) {
|
|
50
|
+
const match = cell.match(LEADING_NUMERIC);
|
|
51
|
+
if (!match) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const value = Number.parseFloat(match[1]);
|
|
55
|
+
return Number.isFinite(value) ? value : null;
|
|
56
|
+
}
|
|
57
|
+
function buildCategoryOption(spec, seriesType) {
|
|
58
|
+
const categories = spec.rows.map((row) => row[0]);
|
|
59
|
+
const values = spec.rows.map((row) => toNumber(row[1] ?? ""));
|
|
60
|
+
const series = {
|
|
61
|
+
type: seriesType,
|
|
62
|
+
data: values,
|
|
63
|
+
name: spec.headers[1] ?? "value",
|
|
64
|
+
};
|
|
65
|
+
if (seriesType === "line") {
|
|
66
|
+
series.smooth = true;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
grid: { left: 48, right: 24, top: 32, bottom: 40, containLabel: true },
|
|
70
|
+
tooltip: { trigger: "axis" },
|
|
71
|
+
xAxis: { type: "category", data: categories, name: spec.headers[0] ?? "" },
|
|
72
|
+
yAxis: { type: "value", name: spec.headers[1] ?? "" },
|
|
73
|
+
series: [series],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function buildBarOption(spec) {
|
|
77
|
+
return buildCategoryOption(spec, "bar");
|
|
78
|
+
}
|
|
79
|
+
export function buildLineOption(spec) {
|
|
80
|
+
return buildCategoryOption(spec, "line");
|
|
81
|
+
}
|
|
82
|
+
export function buildScatterOption(spec) {
|
|
83
|
+
const points = spec.rows
|
|
84
|
+
.map((row) => [toNumber(row[0] ?? ""), toNumber(row[1] ?? "")])
|
|
85
|
+
.filter((point) => point[0] !== null && point[1] !== null);
|
|
86
|
+
return {
|
|
87
|
+
grid: { left: 48, right: 24, top: 32, bottom: 40, containLabel: true },
|
|
88
|
+
tooltip: { trigger: "item" },
|
|
89
|
+
xAxis: { type: "value", name: spec.headers[0] ?? "" },
|
|
90
|
+
yAxis: { type: "value", name: spec.headers[1] ?? "" },
|
|
91
|
+
series: [
|
|
92
|
+
{
|
|
93
|
+
type: "scatter",
|
|
94
|
+
data: points,
|
|
95
|
+
name: spec.headers[1] ?? "value",
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function buildHeatmapOption(spec) {
|
|
101
|
+
const xLabels = spec.headers.slice(1);
|
|
102
|
+
const yLabels = spec.rows.map((row) => row[0]);
|
|
103
|
+
const data = [];
|
|
104
|
+
let min = Number.POSITIVE_INFINITY;
|
|
105
|
+
let max = Number.NEGATIVE_INFINITY;
|
|
106
|
+
for (let y = 0; y < spec.rows.length; y += 1) {
|
|
107
|
+
const row = spec.rows[y];
|
|
108
|
+
for (let x = 0; x < xLabels.length; x += 1) {
|
|
109
|
+
const cell = row[x + 1] ?? "";
|
|
110
|
+
const value = toNumber(cell);
|
|
111
|
+
data.push([x, y, value]);
|
|
112
|
+
if (value !== null) {
|
|
113
|
+
if (value < min)
|
|
114
|
+
min = value;
|
|
115
|
+
if (value > max)
|
|
116
|
+
max = value;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!Number.isFinite(min))
|
|
121
|
+
min = 0;
|
|
122
|
+
if (!Number.isFinite(max))
|
|
123
|
+
max = 1;
|
|
124
|
+
return {
|
|
125
|
+
grid: { left: 80, right: 32, top: 32, bottom: 60, containLabel: true },
|
|
126
|
+
tooltip: { position: "top" },
|
|
127
|
+
xAxis: { type: "category", data: xLabels, splitArea: { show: true } },
|
|
128
|
+
yAxis: { type: "category", data: yLabels, splitArea: { show: true } },
|
|
129
|
+
visualMap: {
|
|
130
|
+
min,
|
|
131
|
+
max,
|
|
132
|
+
calculable: true,
|
|
133
|
+
orient: "horizontal",
|
|
134
|
+
left: "center",
|
|
135
|
+
bottom: 0,
|
|
136
|
+
},
|
|
137
|
+
series: [
|
|
138
|
+
{
|
|
139
|
+
type: "heatmap",
|
|
140
|
+
data,
|
|
141
|
+
name: "value",
|
|
142
|
+
label: { show: false },
|
|
143
|
+
},
|
|
144
|
+
],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
export function buildChartOption(spec) {
|
|
148
|
+
switch (spec.type) {
|
|
149
|
+
case "bar":
|
|
150
|
+
return buildBarOption(spec);
|
|
151
|
+
case "line":
|
|
152
|
+
return buildLineOption(spec);
|
|
153
|
+
case "scatter":
|
|
154
|
+
return buildScatterOption(spec);
|
|
155
|
+
case "heatmap":
|
|
156
|
+
return buildHeatmapOption(spec);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
export const CHART_TYPES = ["bar", "heatmap", "line", "scatter"];
|
|
160
|
+
export function isChartType(value) {
|
|
161
|
+
return CHART_TYPES.includes(value);
|
|
162
|
+
}
|
|
163
|
+
export function isChartSpec(value) {
|
|
164
|
+
if (!value || typeof value !== "object") {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
const candidate = value;
|
|
168
|
+
return (typeof candidate.type === "string" &&
|
|
169
|
+
isChartType(candidate.type) &&
|
|
170
|
+
Array.isArray(candidate.headers) &&
|
|
171
|
+
Array.isArray(candidate.rows) &&
|
|
172
|
+
Array.isArray(candidate.freeText) &&
|
|
173
|
+
candidate.rows.every((row) => Array.isArray(row)));
|
|
174
|
+
}
|