@vetta-org/theme-ui 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +8 -16
- package/src/activity/ActivityPanelFrame.tsx +1 -1
- package/src/activity/CodePreview.tsx +15 -1
- package/src/activity/MarkdownPreviewView.test.tsx +53 -0
- package/src/activity/MarkdownPreviewView.tsx +86 -10
- package/src/chat/ContextRingView.test.tsx +81 -0
- package/src/chat/ContextRingView.tsx +78 -62
- package/src/chat/HeaderActionBarView.tsx +122 -47
- package/src/chat/HeaderActionOverflowMenu.tsx +11 -20
- package/src/chat/MessageFeedLayoutView.tsx +6 -5
- package/src/chat/MessageInputView.tsx +5 -1
- package/src/chat/index.ts +2 -1
- package/src/chat/message-feed-fade.css +80 -0
- package/src/chat/message-feed-fade.test.tsx +75 -0
- package/src/file-preview/ReadonlyCodeView.tsx +46 -0
- package/src/file-preview/syntax-tokens.css +1 -1
- package/src/image-assets.d.ts +4 -0
- package/src/markdown/FileLinkBadge.tsx +77 -0
- package/src/markdown/MarkdownContent.tsx +12 -5
- package/src/markdown/MarkdownImage.tsx +6 -16
- package/src/markdown/MermaidBlock.tsx +50 -11
- package/src/markdown/image-actions.ts +29 -0
- package/src/markdown/index.ts +1 -0
- package/src/markdown/preview-policy.test.ts +31 -0
- package/src/markdown/preview-policy.ts +33 -0
- package/src/markdown/progressive-chunks.test.ts +43 -0
- package/src/markdown/progressive-chunks.ts +58 -0
- package/src/markdown/rich-labels.ts +6 -0
- package/src/overlays/CommandMenuRow.tsx +43 -12
- package/src/overlays/CommandMenuView.tsx +96 -11
- package/src/overlays/DiagnosticsExportDialogView.tsx +236 -0
- package/src/overlays/MagpieHandoverDialogView.tsx +217 -0
- package/src/overlays/ReleaseNoteMarkdown.test.tsx +24 -0
- package/src/overlays/ReleaseNoteMarkdown.tsx +26 -0
- package/src/overlays/SplashPanel.tsx +4 -4
- package/src/overlays/SplashParts.tsx +6 -2
- package/src/overlays/UpdateRestartDialogView.tsx +65 -0
- package/src/overlays/assets/diagnostics-banner.webp +0 -0
- package/src/overlays/command-menu-types.ts +13 -1
- package/src/overlays/index.ts +12 -0
- package/src/plugin-ui/index.ts +2 -0
- package/src/project/DefaultConversationSectionView.tsx +13 -22
- package/src/project/DefaultSessionRowView.tsx +8 -0
- package/src/settings/ArchivedProjectsSettingsView.tsx +122 -1
- package/src/settings/GeneralSettingsView.tsx +2 -5
- package/src/settings/LauncherSettingsView.test.tsx +95 -0
- package/src/settings/LauncherSettingsView.tsx +273 -0
- package/src/settings/PetActionGalleryView.test.tsx +163 -0
- package/src/settings/PetActionGalleryView.tsx +216 -0
- package/src/settings/PetSettingsView.test.tsx +117 -0
- package/src/settings/PetSettingsView.tsx +86 -22
- package/src/settings/PresetProviderRowView.tsx +37 -98
- package/src/settings/ShortcutsSettingsView.tsx +0 -4
- package/src/settings/SpaceEditorDialogView.tsx +94 -56
- package/src/settings/SpacesSettingsView.tsx +53 -8
- package/src/settings/assets/space-editor-illustration.webp +0 -0
- package/src/settings/index.ts +18 -39
- package/src/shared/SegmentedControl.test.tsx +68 -0
- package/src/shared/SegmentedControl.tsx +10 -2
- package/src/shared/TabBar.tsx +2 -2
- package/src/shared/VettaKbd.tsx +20 -1
- package/src/shared/index.ts +2 -1
- package/src/shared/platform.ts +9 -0
- package/src/sidebar/AddProjectMenuTriggerView.tsx +11 -12
- package/src/sidebar/SettingsMenuTriggerView.tsx +2 -1
- package/src/sidebar/SidebarSectionActionButton.test.tsx +91 -0
- package/src/sidebar/SidebarSectionActionButton.tsx +52 -0
- package/src/styles.css +2 -0
- package/src/settings/AchievementNavigationButtonView.tsx +0 -90
- package/src/settings/AchievementPromotionDialogView.tsx +0 -91
- package/src/settings/AchievementSettingsView.tsx +0 -43
- package/src/settings/PetBubbleStylePreviewView.tsx +0 -44
- package/src/settings/QuickPanelSettingsSectionView.tsx +0 -64
- package/src/settings/achievements/AchievementCurtains.tsx +0 -50
- package/src/settings/achievements/AchievementPromotionBadge3D.tsx +0 -350
- package/src/settings/achievements/AchievementPromotionConfetti.tsx +0 -71
- package/src/settings/achievements/AchievementTitle.tsx +0 -52
- package/src/settings/achievements/index.ts +0 -13
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { EditorState } from "@codemirror/state";
|
|
2
|
+
import { EditorView } from "@codemirror/view";
|
|
3
|
+
import { basicSetup } from "codemirror";
|
|
4
|
+
import { useEffect, useRef, type JSX } from "react";
|
|
5
|
+
import { textCodeEditorTheme } from "./text-code-editor-theme";
|
|
6
|
+
import { getTextEditorLanguageExtension, normalizeFileExtension } from "./text-editor-language";
|
|
7
|
+
|
|
8
|
+
const fillPane = EditorView.theme({ "&": { height: "100%" } });
|
|
9
|
+
|
|
10
|
+
export interface ReadonlyCodeViewProps {
|
|
11
|
+
content: string;
|
|
12
|
+
extension: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Read-only CodeMirror for sources too large to highlight whole. It lays out and
|
|
17
|
+
* highlights only the visible lines, so opening a multi-megabyte file stays responsive.
|
|
18
|
+
*/
|
|
19
|
+
export function ReadonlyCodeView({ content, extension }: ReadonlyCodeViewProps): JSX.Element {
|
|
20
|
+
const hostRef = useRef<HTMLDivElement>(null);
|
|
21
|
+
const languageKey = normalizeFileExtension(extension);
|
|
22
|
+
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
const host = hostRef.current;
|
|
25
|
+
if (!host) return;
|
|
26
|
+
const view = new EditorView({
|
|
27
|
+
state: EditorState.create({
|
|
28
|
+
doc: content,
|
|
29
|
+
extensions: [
|
|
30
|
+
basicSetup,
|
|
31
|
+
EditorState.readOnly.of(true),
|
|
32
|
+
EditorView.editable.of(false),
|
|
33
|
+
getTextEditorLanguageExtension(languageKey),
|
|
34
|
+
textCodeEditorTheme,
|
|
35
|
+
// Fill the preview pane and scroll inside the editor, so long lines get their
|
|
36
|
+
// own horizontal scrollbar instead of one at the bottom of the whole file.
|
|
37
|
+
fillPane,
|
|
38
|
+
],
|
|
39
|
+
}),
|
|
40
|
+
parent: host,
|
|
41
|
+
});
|
|
42
|
+
return () => view.destroy();
|
|
43
|
+
}, [content, languageKey]);
|
|
44
|
+
|
|
45
|
+
return <div ref={hostRef} className="h-full min-h-0 w-full bg-background" />;
|
|
46
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { useState } from "react";
|
|
2
|
+
import type { JSX, MouseEvent, ReactNode } from "react";
|
|
3
|
+
import { ContextMenuView } from "../shared/ContextMenuView";
|
|
4
|
+
import type { ContextMenuNode } from "../shared/ContextMenuView";
|
|
5
|
+
|
|
6
|
+
export interface FileLinkMenuLabels {
|
|
7
|
+
open: string;
|
|
8
|
+
/** 平台相关:macOS「在访达中显示」,Windows「在资源管理器中显示」。 */
|
|
9
|
+
reveal: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface FileLinkBadgeProps {
|
|
13
|
+
path: string;
|
|
14
|
+
className: string;
|
|
15
|
+
children: ReactNode;
|
|
16
|
+
menuLabels?: FileLinkMenuLabels;
|
|
17
|
+
onOpen: (path: string) => void;
|
|
18
|
+
/** 宿主能在本机文件管理器里定位该文件时才传;不传则右键保持浏览器默认行为。 */
|
|
19
|
+
onReveal?: (path: string) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 消息里的文件徽标:左键在应用内预览,右键菜单可在系统文件管理器中定位。 */
|
|
23
|
+
export function FileLinkBadge({
|
|
24
|
+
path,
|
|
25
|
+
className,
|
|
26
|
+
children,
|
|
27
|
+
menuLabels,
|
|
28
|
+
onOpen,
|
|
29
|
+
onReveal,
|
|
30
|
+
}: FileLinkBadgeProps): JSX.Element {
|
|
31
|
+
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
|
|
32
|
+
const canReveal = onReveal !== undefined && menuLabels !== undefined;
|
|
33
|
+
|
|
34
|
+
const handleContextMenu = (event: MouseEvent<HTMLButtonElement>): void => {
|
|
35
|
+
if (!canReveal) return;
|
|
36
|
+
// 有选中文字时让会话的「复制 / 加入输入框」菜单接手。
|
|
37
|
+
const selection = window.getSelection();
|
|
38
|
+
if (selection && !selection.isCollapsed) return;
|
|
39
|
+
event.preventDefault();
|
|
40
|
+
event.stopPropagation();
|
|
41
|
+
setMenu({ x: event.clientX, y: event.clientY });
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const items: ContextMenuNode[] = canReveal
|
|
45
|
+
? [
|
|
46
|
+
{
|
|
47
|
+
kind: "item",
|
|
48
|
+
id: "open",
|
|
49
|
+
label: menuLabels.open,
|
|
50
|
+
iconClassName: "icon-[solar--eye-linear]",
|
|
51
|
+
onSelect: () => onOpen(path),
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
kind: "item",
|
|
55
|
+
id: "reveal",
|
|
56
|
+
label: menuLabels.reveal,
|
|
57
|
+
iconClassName: "icon-[solar--folder-open-linear]",
|
|
58
|
+
onSelect: () => onReveal(path),
|
|
59
|
+
},
|
|
60
|
+
]
|
|
61
|
+
: [];
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<>
|
|
65
|
+
<button
|
|
66
|
+
type="button"
|
|
67
|
+
title={path}
|
|
68
|
+
className={className}
|
|
69
|
+
onClick={() => onOpen(path)}
|
|
70
|
+
onContextMenu={handleContextMenu}
|
|
71
|
+
>
|
|
72
|
+
{children}
|
|
73
|
+
</button>
|
|
74
|
+
{menu ? <ContextMenuView items={items} x={menu.x} y={menu.y} onClose={() => setMenu(null)} /> : null}
|
|
75
|
+
</>
|
|
76
|
+
);
|
|
77
|
+
}
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "../shared/MarkdownTable";
|
|
23
23
|
import { SkillTypeIcon } from "../skills/skill-icon";
|
|
24
24
|
import { InlineTokenChip } from "./InlineTokenChip";
|
|
25
|
+
import { FileLinkBadge } from "./FileLinkBadge";
|
|
25
26
|
import { WebsiteIcon } from "./WebsiteIcon";
|
|
26
27
|
import { useRenderSnapshot } from "./use-render-snapshot";
|
|
27
28
|
import { chatUrlTransform, classifyMarkdownLink, normalizeLocalFileLinksInMarkdown } from "./markdown-link";
|
|
@@ -60,6 +61,8 @@ export interface MarkdownContentProps {
|
|
|
60
61
|
labels: MarkdownLabels;
|
|
61
62
|
getFileIconClass: (fileName: string) => string;
|
|
62
63
|
onOpenFile: (path: string) => void;
|
|
64
|
+
/** 在系统文件管理器中定位文件;传入后文件徽标右键出现「在访达中显示」。 */
|
|
65
|
+
onRevealFile?: (path: string) => void;
|
|
63
66
|
onOpenUrl: (url: string) => void;
|
|
64
67
|
/** 传入即启用行内 token 渲染;仅用户消息需要,助手 markdown 不受影响。 */
|
|
65
68
|
inlineTokens?: InlineTokenSupport;
|
|
@@ -154,6 +157,7 @@ export const MarkdownContent = memo(function MarkdownContent({
|
|
|
154
157
|
labels,
|
|
155
158
|
getFileIconClass,
|
|
156
159
|
onOpenFile,
|
|
160
|
+
onRevealFile,
|
|
157
161
|
onOpenUrl,
|
|
158
162
|
inlineTokens,
|
|
159
163
|
definition: definitionOverride,
|
|
@@ -185,11 +189,13 @@ export const MarkdownContent = memo(function MarkdownContent({
|
|
|
185
189
|
const labelsRef = useRef(labels);
|
|
186
190
|
const getFileIconClassRef = useRef(getFileIconClass);
|
|
187
191
|
const onOpenFileRef = useRef(onOpenFile);
|
|
192
|
+
const onRevealFileRef = useRef(onRevealFile);
|
|
188
193
|
const onOpenUrlRef = useRef(onOpenUrl);
|
|
189
194
|
const inlineTokensRef = useRef(inlineTokens);
|
|
190
195
|
labelsRef.current = labels;
|
|
191
196
|
getFileIconClassRef.current = getFileIconClass;
|
|
192
197
|
onOpenFileRef.current = onOpenFile;
|
|
198
|
+
onRevealFileRef.current = onRevealFile;
|
|
193
199
|
onOpenUrlRef.current = onOpenUrl;
|
|
194
200
|
inlineTokensRef.current = inlineTokens;
|
|
195
201
|
|
|
@@ -253,15 +259,16 @@ export const MarkdownContent = memo(function MarkdownContent({
|
|
|
253
259
|
const label =
|
|
254
260
|
typeof children === "string" && ABSOLUTE_PATH_LABEL.test(children.trim()) ? basename(children.trim()) : children;
|
|
255
261
|
return (
|
|
256
|
-
<
|
|
257
|
-
|
|
258
|
-
title={kind.path}
|
|
262
|
+
<FileLinkBadge
|
|
263
|
+
path={kind.path}
|
|
259
264
|
className={cn(LINK_BADGE_CLASS, "cursor-pointer")}
|
|
260
|
-
|
|
265
|
+
menuLabels={labelsRef.current.fileLink}
|
|
266
|
+
onOpen={(path) => onOpenFileRef.current(path)}
|
|
267
|
+
onReveal={onRevealFileRef.current ? (path) => onRevealFileRef.current?.(path) : undefined}
|
|
261
268
|
>
|
|
262
269
|
<span className={cn(getFileIconClassRef.current(fileName), "h-3.5 w-3.5 shrink-0")} />
|
|
263
270
|
<span className="truncate">{label}</span>
|
|
264
|
-
</
|
|
271
|
+
</FileLinkBadge>
|
|
265
272
|
);
|
|
266
273
|
}
|
|
267
274
|
if (kind.type === "url") {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Button } from "@vetta-org/ui/button";
|
|
2
|
-
import { memo, useEffect,
|
|
2
|
+
import { memo, useEffect, useState } from "react";
|
|
3
3
|
import { useMarkdownHost } from "./host";
|
|
4
|
+
import { useImageActions } from "./image-actions";
|
|
4
5
|
import type { MarkdownLabels } from "./rich-labels";
|
|
5
6
|
import { defaultRichContentLabels } from "./rich-labels";
|
|
6
7
|
import { useRichVisibility } from "./use-rich-visibility";
|
|
@@ -12,9 +13,8 @@ export const MarkdownImage = memo(function MarkdownImage({ src = "", alt = "", t
|
|
|
12
13
|
const [attempt, setAttempt] = useState(0);
|
|
13
14
|
const [result, setResult] = useState<{ source: string; url: string }>();
|
|
14
15
|
const [failed, setFailed] = useState(false);
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
useEffect(() => () => { generation.current++; }, [src]);
|
|
16
|
+
const url = result?.source === src ? result.url : undefined;
|
|
17
|
+
const { action, setAction, run, busy } = useImageActions(host, url, src);
|
|
18
18
|
useEffect(() => {
|
|
19
19
|
if (!active || !src) return;
|
|
20
20
|
let cancelled = false;
|
|
@@ -24,16 +24,6 @@ export const MarkdownImage = memo(function MarkdownImage({ src = "", alt = "", t
|
|
|
24
24
|
void request.then((url) => { if (!cancelled) setResult({ source: src, url }); }, () => { if (!cancelled) setFailed(true); });
|
|
25
25
|
return () => { cancelled = true; };
|
|
26
26
|
}, [active, host, src, attempt]);
|
|
27
|
-
const url = result?.source === src ? result.url : undefined;
|
|
28
|
-
const run = async (kind: "copy" | "save") => {
|
|
29
|
-
if (!host || !url) return;
|
|
30
|
-
const current = generation.current;
|
|
31
|
-
setAction(kind);
|
|
32
|
-
try {
|
|
33
|
-
await (kind === "copy" ? host.copyImage(url) : host.saveImage(url));
|
|
34
|
-
if (current === generation.current) setAction(kind === "copy" ? "copied" : null);
|
|
35
|
-
} catch { if (current === generation.current) setAction("failed"); }
|
|
36
|
-
};
|
|
37
27
|
return <span ref={ref} className="my-2 inline-flex max-w-full flex-col gap-1 align-top">
|
|
38
28
|
{failed ? <span role="status">{rich.imageFailed ?? rich.failed} {alt}</span> : url ? (
|
|
39
29
|
<img key={`${url}:${attempt}`} src={url} alt={alt} title={title} loading="lazy" decoding="async" referrerPolicy="no-referrer" className="max-h-96 max-w-full rounded object-contain" onError={() => setFailed(true)} />
|
|
@@ -42,8 +32,8 @@ export const MarkdownImage = memo(function MarkdownImage({ src = "", alt = "", t
|
|
|
42
32
|
{failed && <Button variant="ghost" size="sm" onClick={(event) => { event.preventDefault(); event.stopPropagation(); setFailed(false); setAttempt((value) => value + 1); }}>{rich.retry ?? "Retry"}</Button>}
|
|
43
33
|
{host && url && !failed && <>
|
|
44
34
|
<Button variant="ghost" size="sm" onClick={(event) => { event.preventDefault(); event.stopPropagation(); host.openImage(url, alt); }}>{rich.enlarge ?? "Enlarge"}</Button>
|
|
45
|
-
<Button variant="ghost" size="sm" disabled={
|
|
46
|
-
<Button variant="ghost" size="sm" disabled={
|
|
35
|
+
<Button variant="ghost" size="sm" disabled={busy} onClick={(event) => { event.preventDefault(); event.stopPropagation(); void run("copy"); }}>{action === "copied" ? labels.copied : labels.copy}</Button>
|
|
36
|
+
<Button variant="ghost" size="sm" disabled={busy} onClick={(event) => { event.preventDefault(); event.stopPropagation(); void run("save"); }}>{rich.save ?? "Save"}</Button>
|
|
47
37
|
</>}
|
|
48
38
|
</span>
|
|
49
39
|
{action === "failed" && <span role="status">{rich.actionFailed ?? rich.failed}</span>}
|
|
@@ -1,13 +1,35 @@
|
|
|
1
1
|
import { Button } from "@vetta-org/ui";
|
|
2
|
+
import type { MouseEvent } from "react";
|
|
2
3
|
import { memo, useEffect, useState } from "react";
|
|
3
4
|
import { CodeBlock } from "./CodeBlock";
|
|
4
5
|
import type { MarkdownCodeBlockProps } from "./definition";
|
|
5
6
|
import { useMarkdownHost } from "./host";
|
|
6
|
-
import {
|
|
7
|
-
import { svgImageSource } from "./preview-policy";
|
|
7
|
+
import { useImageActions } from "./image-actions";
|
|
8
|
+
import { svgImageSource, withBackground, withIntrinsicSize } from "./preview-policy";
|
|
8
9
|
import { defaultRichContentLabels } from "./rich-labels";
|
|
9
10
|
import { useRichVisibility } from "./use-rich-visibility";
|
|
10
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Mermaid's dark theme renders poorly, so diagrams always use the light palette.
|
|
14
|
+
* In dark mode they sit on a soft gray canvas instead of a glaring white one.
|
|
15
|
+
*/
|
|
16
|
+
const DARK_MODE_CANVAS = "#e4e4e7";
|
|
17
|
+
/** Copies and saved files are shared elsewhere; a transparent diagram looks broken there. */
|
|
18
|
+
const EXPORT_CANVAS = "#ffffff";
|
|
19
|
+
|
|
20
|
+
function DiagramAction({ label, icon, disabled, onClick }: { label: string; icon: string; disabled?: boolean; onClick: () => void }) {
|
|
21
|
+
const handle = (event: MouseEvent<HTMLButtonElement>) => {
|
|
22
|
+
event.preventDefault();
|
|
23
|
+
event.stopPropagation();
|
|
24
|
+
onClick();
|
|
25
|
+
};
|
|
26
|
+
return (
|
|
27
|
+
<Button variant="ghost" size="icon-sm" aria-label={label} title={label} disabled={disabled} onClick={handle} className="text-muted-foreground hover:text-foreground">
|
|
28
|
+
<span className={`${icon} h-4 w-4`} />
|
|
29
|
+
</Button>
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
11
33
|
export const MermaidBlock = memo(function MermaidBlock(props: MarkdownCodeBlockProps) {
|
|
12
34
|
const { code, theme, live } = props;
|
|
13
35
|
const host = useMarkdownHost();
|
|
@@ -16,28 +38,45 @@ export const MermaidBlock = memo(function MermaidBlock(props: MarkdownCodeBlockP
|
|
|
16
38
|
const [source, setSource] = useState(false);
|
|
17
39
|
const [attempt, setAttempt] = useState(0);
|
|
18
40
|
const [result, setResult] = useState<{ key: string; svg: string | null }>();
|
|
19
|
-
const key = `${theme}:${code}`;
|
|
20
41
|
const oversized = code.length > 12_000;
|
|
21
42
|
useEffect(() => {
|
|
22
43
|
if (!host || !active || live || source || oversized) return;
|
|
23
44
|
let cancelled = false;
|
|
24
|
-
void host.renderMermaid(code,
|
|
25
|
-
(svg) => { if (!cancelled) setResult({ key, svg }); },
|
|
26
|
-
() => { if (!cancelled) setResult({ key, svg: null }); },
|
|
45
|
+
void host.renderMermaid(code, "light").then(
|
|
46
|
+
(svg) => { if (!cancelled) setResult({ key: code, svg }); },
|
|
47
|
+
() => { if (!cancelled) setResult({ key: code, svg: null }); },
|
|
27
48
|
);
|
|
28
49
|
return () => { cancelled = true; };
|
|
29
|
-
}, [host, active, live, source, oversized,
|
|
30
|
-
const current = result?.key ===
|
|
31
|
-
const
|
|
50
|
+
}, [host, active, live, source, oversized, code, attempt]);
|
|
51
|
+
const current = result?.key === code ? result : undefined;
|
|
52
|
+
const dark = theme === "dark";
|
|
53
|
+
const image = current?.svg ? svgImageSource(withIntrinsicSize(dark ? withBackground(current.svg, DARK_MODE_CANVAS) : current.svg)) : null;
|
|
54
|
+
const exported = current?.svg ? svgImageSource(withIntrinsicSize(withBackground(current.svg, EXPORT_CANVAS))) : null;
|
|
55
|
+
const { action, setAction, run, busy } = useImageActions(host, exported ?? undefined, code);
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (action !== "copied") return;
|
|
58
|
+
const timer = setTimeout(() => setAction(null), 1500);
|
|
59
|
+
return () => clearTimeout(timer);
|
|
60
|
+
}, [action, setAction]);
|
|
61
|
+
const showing = !(source || live || oversized || !host || current?.svg === null);
|
|
62
|
+
const diagram = labels.diagram ?? "Diagram";
|
|
32
63
|
return <CodeBlock.Root {...props}><CodeBlock.Copy><CodeBlock.Frame><div ref={ref}>
|
|
33
64
|
<div className="flex items-center gap-2 py-1.5 pr-12 pl-4">
|
|
34
65
|
<span className="text-[12px] text-muted-foreground">Mermaid</span>
|
|
35
66
|
<Button variant="ghost" size="sm" aria-pressed={source} onClick={() => setSource(!source)}>{source ? labels.preview : labels.source}</Button>
|
|
36
67
|
{current?.svg === null && <Button variant="ghost" size="sm" onClick={() => { setResult(undefined); setAttempt((value) => value + 1); }}>{labels.retry ?? "Retry"}</Button>}
|
|
68
|
+
{showing && image && host && <div className="ml-auto flex items-center gap-0.5">
|
|
69
|
+
{action === "failed" && <span role="status" className="mr-1 text-[12px] text-muted-foreground">{labels.actionFailed ?? labels.failed}</span>}
|
|
70
|
+
<div className="flex items-center gap-0.5 opacity-0 transition-opacity group-hover/code-block:opacity-100 focus-within:opacity-100">
|
|
71
|
+
<DiagramAction label={labels.enlarge ?? "Enlarge"} icon="icon-[solar--maximize-square-minimalistic-linear]" onClick={() => host.openImage(image, diagram)} />
|
|
72
|
+
<DiagramAction label={action === "copied" ? props.labels.copied : (labels.copyImage ?? "Copy image")} icon={action === "copied" ? "icon-[mdi--check]" : "icon-[solar--gallery-send-linear]"} disabled={busy} onClick={() => void run("copy")} />
|
|
73
|
+
<DiagramAction label={labels.save ?? "Save"} icon="icon-[solar--download-minimalistic-linear]" disabled={busy} onClick={() => void run("save")} />
|
|
74
|
+
</div>
|
|
75
|
+
</div>}
|
|
37
76
|
</div>
|
|
38
|
-
{
|
|
77
|
+
{!showing ? <>
|
|
39
78
|
{!source && <p role="status" className="px-4 pb-2 text-[12px] text-muted-foreground">{oversized ? labels.tooLarge : live ? labels.waiting : labels.failed}</p>}
|
|
40
79
|
<CodeBlock.Content />
|
|
41
|
-
</> : image ? <CodeBlock.Body><div className="p-4"><
|
|
80
|
+
</> : image ? <CodeBlock.Body><div className="overflow-x-auto p-4" style={dark ? { backgroundColor: DARK_MODE_CANVAS } : undefined}><img src={image} alt={diagram} decoding="async" className="mx-auto block h-auto max-w-full" /></div></CodeBlock.Body> : <CodeBlock.Body><div className="min-h-24 p-4" role="status">{labels.loading ?? labels.waiting}</div></CodeBlock.Body>}
|
|
42
81
|
</div></CodeBlock.Frame></CodeBlock.Copy></CodeBlock.Root>;
|
|
43
82
|
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
import type { MarkdownHost } from "./host";
|
|
3
|
+
|
|
4
|
+
export type ImageActionState = "copy" | "save" | "failed" | "copied" | null;
|
|
5
|
+
|
|
6
|
+
/** Copy/save through the host; a result that lands after `resetKey` changes is dropped. */
|
|
7
|
+
export function useImageActions(host: MarkdownHost | null | undefined, url: string | undefined, resetKey: string) {
|
|
8
|
+
const [action, setAction] = useState<ImageActionState>(null);
|
|
9
|
+
const generation = useRef(0);
|
|
10
|
+
// biome-ignore lint/correctness/useExhaustiveDependencies: a new image invalidates pending results.
|
|
11
|
+
useEffect(
|
|
12
|
+
() => () => {
|
|
13
|
+
generation.current++;
|
|
14
|
+
},
|
|
15
|
+
[resetKey],
|
|
16
|
+
);
|
|
17
|
+
const run = async (kind: "copy" | "save") => {
|
|
18
|
+
if (!host || !url) return;
|
|
19
|
+
const current = generation.current;
|
|
20
|
+
setAction(kind);
|
|
21
|
+
try {
|
|
22
|
+
await (kind === "copy" ? host.copyImage(url) : host.saveImage(url));
|
|
23
|
+
if (current === generation.current) setAction(kind === "copy" ? "copied" : null);
|
|
24
|
+
} catch {
|
|
25
|
+
if (current === generation.current) setAction("failed");
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
return { action, setAction, run, busy: action === "copy" || action === "save" };
|
|
29
|
+
}
|
package/src/markdown/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { CodeBlock, DefaultCodeBlock } from "./CodeBlock";
|
|
2
2
|
export type { MarkdownCodeBlockProps, MarkdownDefinition, MarkdownElementProps } from "./definition";
|
|
3
3
|
export { defaultMarkdown, extendMarkdown, MarkdownProvider, useMarkdownDefinition } from "./definition";
|
|
4
|
+
export type { FileLinkMenuLabels } from "./FileLinkBadge";
|
|
4
5
|
export type { MarkdownHost } from "./host";
|
|
5
6
|
export { MarkdownHostProvider } from "./host";
|
|
6
7
|
export type { InlineTokenAnnotation, InlineTokenPiece, InlineTokenSupport } from "./inline-tokens";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { withBackground, withIntrinsicSize } from "./preview-policy";
|
|
3
|
+
|
|
4
|
+
describe("withIntrinsicSize", () => {
|
|
5
|
+
it("sizes a Mermaid diagram from its viewBox so an image is not shrunk to the default box", () => {
|
|
6
|
+
const svg =
|
|
7
|
+
'<svg id="diagram" width="100%" xmlns="http://www.w3.org/2000/svg" style="max-width: 812.5px; background-color: white;" viewBox="0 0 812.5 1460"><path stroke-width="2"/></svg>';
|
|
8
|
+
expect(withIntrinsicSize(svg)).toBe(
|
|
9
|
+
'<svg id="diagram" xmlns="http://www.w3.org/2000/svg" style="background-color: white;" viewBox="0 0 812.5 1460" width="812.5" height="1460"><path stroke-width="2"/></svg>',
|
|
10
|
+
);
|
|
11
|
+
});
|
|
12
|
+
it("leaves SVGs with an absolute width or no usable viewBox unchanged", () => {
|
|
13
|
+
for (const svg of [
|
|
14
|
+
'<svg width="320" height="200" viewBox="0 0 640 400"></svg>',
|
|
15
|
+
'<svg width="100%"></svg>',
|
|
16
|
+
'<svg width="100%" viewBox="0 0 0 10"></svg>',
|
|
17
|
+
])
|
|
18
|
+
expect(withIntrinsicSize(svg)).toBe(svg);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe("withBackground", () => {
|
|
23
|
+
it("replaces Mermaid's own background so a dark-mode diagram keeps a light canvas", () => {
|
|
24
|
+
expect(
|
|
25
|
+
withBackground('<svg id="d" style="max-width: 10px; background-color: white;"><g/></svg>', "#e8e8ea"),
|
|
26
|
+
).toBe('<svg id="d" style="max-width: 10px; background-color: #e8e8ea;"><g/></svg>');
|
|
27
|
+
expect(withBackground('<svg viewBox="0 0 1 1"></svg>', "#e8e8ea")).toBe(
|
|
28
|
+
'<svg viewBox="0 0 1 1" style="background-color: #e8e8ea;"></svg>',
|
|
29
|
+
);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -41,3 +41,36 @@ export function svgImageSource(source: string): string | null {
|
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Mermaid emits `width="100%"` with no height. As an `<img>`, such an SVG has no intrinsic size,
|
|
47
|
+
* so the browser fits it into the 300×150 default box. Give it the viewBox size instead.
|
|
48
|
+
*/
|
|
49
|
+
export function withIntrinsicSize(source: string): string {
|
|
50
|
+
return source.replace(/<svg\b([^>]*)>/i, (tag: string, attributes: string) => {
|
|
51
|
+
const width = /\swidth\s*=\s*["']([^"']*)["']/i.exec(attributes)?.[1]?.trim();
|
|
52
|
+
if (width && !width.endsWith("%")) return tag;
|
|
53
|
+
const box = /\sviewBox\s*=\s*["']([^"']*)["']/i
|
|
54
|
+
.exec(attributes)?.[1]
|
|
55
|
+
?.trim()
|
|
56
|
+
.split(/[\s,]+/)
|
|
57
|
+
.map(Number);
|
|
58
|
+
const [, , w = 0, h = 0] = box ?? [];
|
|
59
|
+
if (box?.length !== 4 || !(w > 0) || !(h > 0)) return tag;
|
|
60
|
+
const rest = attributes
|
|
61
|
+
.replace(/\s(?:width|height)\s*=\s*(["'])[^"']*\1/gi, "")
|
|
62
|
+
.replace(/max-width\s*:\s*[^;"']*;?\s*/i, "");
|
|
63
|
+
return `<svg${rest} width="${w}" height="${h}">`;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Paints the SVG root so a diagram stays readable when enlarged, copied or saved onto a dark surface. */
|
|
68
|
+
export function withBackground(source: string, color: string): string {
|
|
69
|
+
return source.replace(/<svg\b([^>]*)>/i, (_tag: string, attributes: string) => {
|
|
70
|
+
const style = /\sstyle\s*=\s*(["'])([^"']*)\1/i.exec(attributes);
|
|
71
|
+
if (!style) return `<svg${attributes} style="background-color: ${color};">`;
|
|
72
|
+
const rest = (style[2] ?? "").replace(/background(?:-color)?\s*:\s*[^;]*;?\s*/gi, "").trim();
|
|
73
|
+
const merged = `${rest}${rest && !rest.endsWith(";") ? ";" : ""}${rest ? " " : ""}background-color: ${color};`;
|
|
74
|
+
return `<svg${attributes.replace(style[0], ` style="${merged}"`)}>`;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { PROGRESSIVE_MARKDOWN_THRESHOLD, splitMarkdownForProgressiveRender } from "./progressive-chunks";
|
|
3
|
+
|
|
4
|
+
function sections(count: number, body = "text ".repeat(600)): string {
|
|
5
|
+
return Array.from({ length: count }, (_, index) => `## Section ${index}\n\n${body}\n`).join("\n");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
describe("splitMarkdownForProgressiveRender", () => {
|
|
9
|
+
it("keeps small documents whole", () => {
|
|
10
|
+
const small = "# Title\n\nshort";
|
|
11
|
+
expect(splitMarkdownForProgressiveRender(small)).toEqual([small]);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it("cuts large documents before headings and loses no text", () => {
|
|
15
|
+
const markdown = sections(40);
|
|
16
|
+
expect(markdown.length).toBeGreaterThan(PROGRESSIVE_MARKDOWN_THRESHOLD);
|
|
17
|
+
const chunks = splitMarkdownForProgressiveRender(markdown);
|
|
18
|
+
expect(chunks.length).toBeGreaterThan(1);
|
|
19
|
+
expect(chunks.join("\n")).toBe(markdown);
|
|
20
|
+
for (const chunk of chunks.slice(1)) expect(chunk.startsWith("## Section")).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("never cuts inside fenced code, even before a heading-like line", () => {
|
|
24
|
+
const fenced = `\`\`\`md\n${Array.from({ length: 400 }, (_, i) => `\n# not a heading ${i}`).join("\n")}\n\`\`\`\n`;
|
|
25
|
+
const markdown = `${sections(10)}\n${fenced}\n${sections(10)}`;
|
|
26
|
+
const chunks = splitMarkdownForProgressiveRender(markdown);
|
|
27
|
+
for (const chunk of chunks) {
|
|
28
|
+
expect((chunk.match(/^```/gm) ?? []).length % 2).toBe(0);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("repeats link reference definitions in every chunk", () => {
|
|
33
|
+
const markdown = `${sections(40, `${"text ".repeat(600)} see [docs][ref]`)}\n[ref]: https://example.com\n`;
|
|
34
|
+
const chunks = splitMarkdownForProgressiveRender(markdown);
|
|
35
|
+
expect(chunks.length).toBeGreaterThan(1);
|
|
36
|
+
for (const chunk of chunks) expect(chunk).toContain("[ref]: https://example.com");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("does not split documents with footnotes", () => {
|
|
40
|
+
const markdown = `${sections(40)}\nNote[^1]\n\n[^1]: footnote\n`;
|
|
41
|
+
expect(splitMarkdownForProgressiveRender(markdown)).toEqual([markdown]);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Below this size a document renders in one pass; above it, section by section. */
|
|
2
|
+
export const PROGRESSIVE_MARKDOWN_THRESHOLD = 40_000;
|
|
3
|
+
/** Each chunk takes roughly a frame or two to parse and render. */
|
|
4
|
+
const TARGET_CHUNK_CHARACTERS = 12_000;
|
|
5
|
+
|
|
6
|
+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
|
|
7
|
+
const ATX_HEADING_RE = /^ {0,3}#{1,6}(\s|$)/;
|
|
8
|
+
const FOOTNOTE_DEFINITION_RE = /^ {0,3}\[\^[^\]]+\]:/m;
|
|
9
|
+
const LINK_DEFINITION_RE = /^ {0,3}\[[^\]^][^\]]*\]:\s*\S/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Splits a large Markdown document into independently renderable chunks, cutting only
|
|
13
|
+
* before an ATX heading that follows a blank line outside fenced code. A heading always
|
|
14
|
+
* starts a new block, so no list, quote, table or paragraph spans two chunks.
|
|
15
|
+
*
|
|
16
|
+
* Link reference definitions apply document-wide, so they are repeated at the end of every
|
|
17
|
+
* chunk (they render nothing). Footnotes collect into one section per render, so a document
|
|
18
|
+
* that defines any is never split.
|
|
19
|
+
*/
|
|
20
|
+
export function splitMarkdownForProgressiveRender(markdown: string): string[] {
|
|
21
|
+
if (markdown.length <= PROGRESSIVE_MARKDOWN_THRESHOLD || FOOTNOTE_DEFINITION_RE.test(markdown)) {
|
|
22
|
+
return [markdown];
|
|
23
|
+
}
|
|
24
|
+
const lines = markdown.split("\n");
|
|
25
|
+
const chunks: string[] = [];
|
|
26
|
+
const definitions: string[] = [];
|
|
27
|
+
let current: string[] = [];
|
|
28
|
+
let currentLength = 0;
|
|
29
|
+
let fence: string | null = null;
|
|
30
|
+
for (let index = 0; index < lines.length; index++) {
|
|
31
|
+
const line = lines[index] ?? "";
|
|
32
|
+
const fenceMatch = FENCE_RE.exec(line);
|
|
33
|
+
if (fence === null) {
|
|
34
|
+
if (fenceMatch?.[1]) {
|
|
35
|
+
fence = fenceMatch[1];
|
|
36
|
+
} else if (
|
|
37
|
+
ATX_HEADING_RE.test(line) &&
|
|
38
|
+
index > 0 &&
|
|
39
|
+
(lines[index - 1] ?? "").trim() === "" &&
|
|
40
|
+
currentLength >= TARGET_CHUNK_CHARACTERS
|
|
41
|
+
) {
|
|
42
|
+
chunks.push(current.join("\n"));
|
|
43
|
+
current = [];
|
|
44
|
+
currentLength = 0;
|
|
45
|
+
} else if (LINK_DEFINITION_RE.test(line)) {
|
|
46
|
+
definitions.push(line);
|
|
47
|
+
}
|
|
48
|
+
} else if (fenceMatch?.[1] && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) {
|
|
49
|
+
fence = null;
|
|
50
|
+
}
|
|
51
|
+
current.push(line);
|
|
52
|
+
currentLength += line.length + 1;
|
|
53
|
+
}
|
|
54
|
+
if (current.length > 0) chunks.push(current.join("\n"));
|
|
55
|
+
if (definitions.length === 0 || chunks.length === 1) return chunks;
|
|
56
|
+
const shared = `\n\n${definitions.join("\n")}\n`;
|
|
57
|
+
return chunks.map((chunk) => `${chunk}${shared}`);
|
|
58
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { FileLinkMenuLabels } from "./FileLinkBadge";
|
|
2
|
+
|
|
1
3
|
export interface RichContentLabels {
|
|
2
4
|
preview: string;
|
|
3
5
|
source: string;
|
|
@@ -14,6 +16,7 @@ export interface RichContentLabels {
|
|
|
14
16
|
loading?: string;
|
|
15
17
|
retry?: string;
|
|
16
18
|
enlarge?: string;
|
|
19
|
+
copyImage?: string;
|
|
17
20
|
save?: string;
|
|
18
21
|
diagram?: string;
|
|
19
22
|
imageFailed?: string;
|
|
@@ -36,6 +39,7 @@ export const defaultRichContentLabels: RichContentLabels = {
|
|
|
36
39
|
loading: "Loading preview…",
|
|
37
40
|
retry: "Retry",
|
|
38
41
|
enlarge: "Enlarge",
|
|
42
|
+
copyImage: "Copy image",
|
|
39
43
|
save: "Save",
|
|
40
44
|
diagram: "Diagram",
|
|
41
45
|
imageFailed: "Could not load image.",
|
|
@@ -45,5 +49,7 @@ export const defaultRichContentLabels: RichContentLabels = {
|
|
|
45
49
|
export interface MarkdownLabels {
|
|
46
50
|
copy: string;
|
|
47
51
|
copied: string;
|
|
52
|
+
/** 文件徽标右键菜单文案;缺省时不出菜单。 */
|
|
53
|
+
fileLink?: FileLinkMenuLabels;
|
|
48
54
|
rich?: RichContentLabels;
|
|
49
55
|
}
|