@vetta-org/theme-ui 0.1.2 → 0.2.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/package.json +8 -16
- package/src/action-approval/StorageCleanListView.test.tsx +36 -0
- package/src/action-approval/StorageCleanListView.tsx +52 -0
- package/src/action-approval/index.ts +2 -0
- package/src/activity/ActivityPanel.tsx +7 -1
- package/src/activity/ActivityPanelFrame.tsx +1 -1
- package/src/activity/BackgroundTasksTabPanelView.tsx +18 -2
- package/src/activity/BrowserPanelView.tsx +15 -1
- package/src/activity/BrowserSelectionView.tsx +199 -0
- package/src/activity/CodePreview.tsx +15 -1
- package/src/activity/MarkdownPreviewView.test.tsx +53 -0
- package/src/activity/MarkdownPreviewView.tsx +86 -10
- package/src/activity/index.ts +1 -0
- package/src/chat/ContextRingView.test.tsx +81 -0
- package/src/chat/ContextRingView.tsx +78 -62
- package/src/chat/EditDiffView.tsx +4 -4
- package/src/chat/HeaderActionBarView.tsx +135 -48
- 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/chat/streaming-reveal.test.ts +1 -74
- package/src/chat/streaming-reveal.ts +0 -3
- package/src/file-preview/FilePreviewDialogView.tsx +2 -1
- 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/layout/ResizeHandle.tsx +4 -1
- package/src/layout/resize-handle-reset.test.tsx +50 -0
- package/src/markdown/FileLinkBadge.tsx +77 -0
- package/src/markdown/MarkdownContent.tsx +61 -31
- package/src/markdown/MarkdownImage.tsx +6 -16
- package/src/markdown/MermaidBlock.tsx +50 -11
- package/src/markdown/UrlLinkBadge.tsx +84 -0
- package/src/markdown/image-actions.ts +29 -0
- package/src/markdown/index.ts +2 -0
- package/src/markdown/nodes.ts +6 -1
- 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 +9 -0
- package/src/markdown/streaming-fade.test.ts +83 -0
- package/src/markdown/streaming-fade.tsx +141 -0
- package/src/markdown/streaming-reveal.ts +0 -67
- package/src/markdown/streaming.ts +64 -131
- package/src/overlays/CommandMenuRow.tsx +47 -26
- package/src/overlays/CommandMenuView.tsx +107 -15
- package/src/overlays/DiagnosticsExportDialogView.tsx +236 -0
- package/src/overlays/MagpieHandoverDialogView.tsx +217 -0
- package/src/overlays/ReleaseNoteImage.test.tsx +105 -0
- package/src/overlays/ReleaseNoteMarkdown.test.tsx +49 -0
- package/src/overlays/ReleaseNoteMarkdown.tsx +120 -7
- package/src/overlays/SplashPanel.tsx +4 -4
- package/src/overlays/SplashParts.tsx +6 -2
- package/src/overlays/UpdateCheckerView.tsx +17 -15
- package/src/overlays/UpdateRestartDialogView.tsx +76 -2
- package/src/overlays/assets/diagnostics-banner.webp +0 -0
- package/src/overlays/command-menu-types.ts +15 -1
- package/src/overlays/index.ts +13 -0
- package/src/plugin-ui/index.ts +4 -0
- package/src/project/DefaultConversationSectionView.tsx +17 -22
- package/src/project/DefaultSessionRowView.tsx +8 -0
- package/src/project/ManageSessionsSplashView.tsx +0 -2
- package/src/settings/ArchivedProjectsSettingsView.tsx +122 -1
- package/src/settings/GeneralSettingsView.tsx +21 -5
- package/src/settings/LauncherSettingsView.test.tsx +95 -0
- package/src/settings/LauncherSettingsView.tsx +272 -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/StorageBar.tsx +70 -0
- package/src/settings/StorageExplorer.tsx +488 -0
- package/src/settings/StorageReadout.tsx +64 -0
- package/src/settings/StorageSettingsView.test.tsx +181 -0
- package/src/settings/StorageSettingsView.tsx +458 -0
- package/src/settings/assets/space-editor-illustration.webp +0 -0
- package/src/settings/index.ts +28 -39
- package/src/settings/storage-treemap-layout.test.ts +32 -0
- package/src/settings/storage-treemap-layout.ts +55 -0
- package/src/shared/SegmentedControl.test.tsx +68 -0
- package/src/shared/SegmentedControl.tsx +18 -11
- package/src/shared/StageDialogContent.test.tsx +61 -0
- package/src/shared/StageDialogContent.tsx +80 -0
- package/src/shared/TabBar.tsx +2 -2
- package/src/shared/VettaKbd.tsx +20 -1
- package/src/shared/index.ts +4 -1
- package/src/shared/platform.ts +9 -0
- package/src/sidebar/AddProjectMenuTriggerView.tsx +13 -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 +7 -0
- package/src/markdown/streaming.test.ts +0 -57
- 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
|
@@ -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,84 @@
|
|
|
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 UrlLinkMenuLabels {
|
|
7
|
+
/** 按用户设置的默认方式打开,如「在 Vetta 中打开」。 */
|
|
8
|
+
open: string;
|
|
9
|
+
/** 另一种方式,如「在系统浏览器中打开」。 */
|
|
10
|
+
openAlternate: string;
|
|
11
|
+
copy: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `alternate` 为 true 表示不走默认方式,改用另一种(右键第二项或 ⌘/Ctrl+点击)。 */
|
|
15
|
+
export type OpenUrlHandler = (url: string, options?: { alternate?: boolean }) => void;
|
|
16
|
+
|
|
17
|
+
export interface UrlLinkBadgeProps {
|
|
18
|
+
url: string;
|
|
19
|
+
className: string;
|
|
20
|
+
children: ReactNode;
|
|
21
|
+
menuLabels?: UrlLinkMenuLabels;
|
|
22
|
+
onOpen: OpenUrlHandler;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 消息里的网址徽标:左键按默认方式打开,⌘/Ctrl+点击换另一种,右键可选打开方式或复制链接。 */
|
|
26
|
+
export function UrlLinkBadge({ url, className, children, menuLabels, onOpen }: UrlLinkBadgeProps): JSX.Element {
|
|
27
|
+
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
|
|
28
|
+
|
|
29
|
+
const handleContextMenu = (event: MouseEvent<HTMLAnchorElement>): void => {
|
|
30
|
+
if (!menuLabels) return;
|
|
31
|
+
// 有选中文字时让会话的「复制 / 加入输入框」菜单接手。
|
|
32
|
+
const selection = window.getSelection();
|
|
33
|
+
if (selection && !selection.isCollapsed) return;
|
|
34
|
+
event.preventDefault();
|
|
35
|
+
event.stopPropagation();
|
|
36
|
+
setMenu({ x: event.clientX, y: event.clientY });
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const items: ContextMenuNode[] = menuLabels
|
|
40
|
+
? [
|
|
41
|
+
{
|
|
42
|
+
kind: "item",
|
|
43
|
+
id: "open",
|
|
44
|
+
label: menuLabels.open,
|
|
45
|
+
iconClassName: "icon-[solar--global-linear]",
|
|
46
|
+
onSelect: () => onOpen(url),
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
kind: "item",
|
|
50
|
+
id: "open-alternate",
|
|
51
|
+
label: menuLabels.openAlternate,
|
|
52
|
+
iconClassName: "icon-[solar--square-top-down-linear]",
|
|
53
|
+
onSelect: () => onOpen(url, { alternate: true }),
|
|
54
|
+
},
|
|
55
|
+
{ kind: "separator", id: "separator" },
|
|
56
|
+
{
|
|
57
|
+
kind: "item",
|
|
58
|
+
id: "copy",
|
|
59
|
+
label: menuLabels.copy,
|
|
60
|
+
iconClassName: "icon-[solar--copy-linear]",
|
|
61
|
+
onSelect: () => void navigator.clipboard?.writeText(url).catch(() => undefined),
|
|
62
|
+
},
|
|
63
|
+
]
|
|
64
|
+
: [];
|
|
65
|
+
|
|
66
|
+
return (
|
|
67
|
+
<>
|
|
68
|
+
<a
|
|
69
|
+
href={url}
|
|
70
|
+
title={url}
|
|
71
|
+
className={className}
|
|
72
|
+
onClick={(event) => {
|
|
73
|
+
event.preventDefault();
|
|
74
|
+
if (event.metaKey || event.ctrlKey) onOpen(url, { alternate: true });
|
|
75
|
+
else onOpen(url);
|
|
76
|
+
}}
|
|
77
|
+
onContextMenu={handleContextMenu}
|
|
78
|
+
>
|
|
79
|
+
{children}
|
|
80
|
+
</a>
|
|
81
|
+
{menu ? <ContextMenuView items={items} x={menu.x} y={menu.y} onClose={() => setMenu(null)} /> : null}
|
|
82
|
+
</>
|
|
83
|
+
);
|
|
84
|
+
}
|
|
@@ -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";
|
|
@@ -9,3 +10,4 @@ export { MarkdownContent } from "./MarkdownContent";
|
|
|
9
10
|
export type { RichContentLabels } from "./rich-labels";
|
|
10
11
|
export type { StableMarkdownSplit } from "./stable-blocks";
|
|
11
12
|
export { splitStableMarkdownBlocks } from "./stable-blocks";
|
|
13
|
+
export type { OpenUrlHandler, UrlLinkMenuLabels } from "./UrlLinkBadge";
|
package/src/markdown/nodes.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
/** Minimal hast-like nodes for the
|
|
1
|
+
/** Minimal hast-like nodes for the markdown rehype plugins. */
|
|
2
|
+
export interface HastPosition {
|
|
3
|
+
start: { offset?: number };
|
|
4
|
+
end: { offset?: number };
|
|
5
|
+
}
|
|
2
6
|
export interface HastText {
|
|
3
7
|
type: "text";
|
|
4
8
|
value: string;
|
|
9
|
+
position?: HastPosition;
|
|
5
10
|
}
|
|
6
11
|
export interface HastElement {
|
|
7
12
|
type: "element";
|
|
@@ -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,6 @@
|
|
|
1
|
+
import type { FileLinkMenuLabels } from "./FileLinkBadge";
|
|
2
|
+
import type { UrlLinkMenuLabels } from "./UrlLinkBadge";
|
|
3
|
+
|
|
1
4
|
export interface RichContentLabels {
|
|
2
5
|
preview: string;
|
|
3
6
|
source: string;
|
|
@@ -14,6 +17,7 @@ export interface RichContentLabels {
|
|
|
14
17
|
loading?: string;
|
|
15
18
|
retry?: string;
|
|
16
19
|
enlarge?: string;
|
|
20
|
+
copyImage?: string;
|
|
17
21
|
save?: string;
|
|
18
22
|
diagram?: string;
|
|
19
23
|
imageFailed?: string;
|
|
@@ -36,6 +40,7 @@ export const defaultRichContentLabels: RichContentLabels = {
|
|
|
36
40
|
loading: "Loading preview…",
|
|
37
41
|
retry: "Retry",
|
|
38
42
|
enlarge: "Enlarge",
|
|
43
|
+
copyImage: "Copy image",
|
|
39
44
|
save: "Save",
|
|
40
45
|
diagram: "Diagram",
|
|
41
46
|
imageFailed: "Could not load image.",
|
|
@@ -45,5 +50,9 @@ export const defaultRichContentLabels: RichContentLabels = {
|
|
|
45
50
|
export interface MarkdownLabels {
|
|
46
51
|
copy: string;
|
|
47
52
|
copied: string;
|
|
53
|
+
/** 文件徽标右键菜单文案;缺省时不出菜单。 */
|
|
54
|
+
fileLink?: FileLinkMenuLabels;
|
|
55
|
+
/** 网址徽标右键菜单文案;缺省时不出菜单。 */
|
|
56
|
+
urlLink?: UrlLinkMenuLabels;
|
|
48
57
|
rich?: RichContentLabels;
|
|
49
58
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import type { HastElement, HastRoot, HastText } from "./nodes";
|
|
3
|
+
import { pruneReveals, rehypeStreamingFade, STREAMING_FADE_MS, STREAMING_FADE_TAG } from "./streaming-fade";
|
|
4
|
+
|
|
5
|
+
function text(value: string, start: number, end = start + value.length): HastText {
|
|
6
|
+
return { type: "text", value, position: { start: { offset: start }, end: { offset: end } } };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function element(tagName: string, ...children: Array<HastText | HastElement>): HastElement {
|
|
10
|
+
return { type: "element", tagName, properties: {}, children };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 把树压成「普通文字 / [淡入时刻:文字]」的串,便于断言。 */
|
|
14
|
+
function flatten(node: HastRoot | HastElement): string {
|
|
15
|
+
return node.children
|
|
16
|
+
.map((child) => {
|
|
17
|
+
if (child.type === "text") return child.value;
|
|
18
|
+
if (child.tagName === STREAMING_FADE_TAG) return `[${child.properties?.dataRevealAt}:${flatten(child)}]`;
|
|
19
|
+
return flatten(child);
|
|
20
|
+
})
|
|
21
|
+
.join("");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function run(tree: HastRoot, reveals: Parameters<typeof rehypeStreamingFade>[0], offset = 0): string {
|
|
25
|
+
rehypeStreamingFade(reveals, offset)()(tree);
|
|
26
|
+
return flatten(tree);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe("rehypeStreamingFade", () => {
|
|
30
|
+
test("wraps only the text revealed within the fade window, one span per reveal", () => {
|
|
31
|
+
const tree: HastRoot = { type: "root", children: [element("p", text("Hello there, general Kenobi.", 0))] };
|
|
32
|
+
const out = run(tree, [
|
|
33
|
+
{ start: 6, end: 13, at: 100 },
|
|
34
|
+
{ start: 13, end: 28, at: 200 },
|
|
35
|
+
]);
|
|
36
|
+
expect(out).toBe("Hello [100:there, ][200:general Kenobi.]");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("maps reveals across inline formatting by source position", () => {
|
|
40
|
+
// 源码 "Say **bold** now":strong 内文字源码位置是 6..10。
|
|
41
|
+
const tree: HastRoot = {
|
|
42
|
+
type: "root",
|
|
43
|
+
children: [element("p", text("Say ", 0), element("strong", text("bold", 6)), text(" now", 12))],
|
|
44
|
+
};
|
|
45
|
+
expect(run(tree, [{ start: 8, end: 16, at: 5 }])).toBe("Say bo[5:ld][5: now]");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("leaves code, tables and svg previews untouched", () => {
|
|
49
|
+
const tree: HastRoot = {
|
|
50
|
+
type: "root",
|
|
51
|
+
children: [element("pre", element("code", text("let a = 1;", 4))), element("p", text("after", 16))],
|
|
52
|
+
};
|
|
53
|
+
expect(run(tree, [{ start: 0, end: 21, at: 7 }])).toBe("let a = 1;[7:after]");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("shifts reveal ranges by the document offset of the streaming tail", () => {
|
|
57
|
+
const tree: HastRoot = { type: "root", children: [element("p", text("tail text", 0))] };
|
|
58
|
+
expect(run(tree, [{ start: 105, end: 109, at: 9 }], 100)).toBe("tail [9:text]");
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("assigns a node whose source length differs from its text as a whole by where it ends", () => {
|
|
62
|
+
// "a & b" 渲染成 "a & b":源码 9 个字符,文字 5 个。
|
|
63
|
+
const tree: HastRoot = { type: "root", children: [element("p", text("a & b", 0, 9))] };
|
|
64
|
+
expect(run(tree, [{ start: 4, end: 9, at: 3 }])).toBe("[3:a & b]");
|
|
65
|
+
const older: HastRoot = { type: "root", children: [element("p", text("a & b", 0, 9))] };
|
|
66
|
+
expect(run(older, [{ start: 9, end: 12, at: 3 }])).toBe("a & b");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("does nothing without reveals", () => {
|
|
70
|
+
const tree: HastRoot = { type: "root", children: [element("p", text("steady", 0))] };
|
|
71
|
+
expect(run(tree, [])).toBe("steady");
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
describe("pruneReveals", () => {
|
|
76
|
+
test("drops reveals whose fade has finished", () => {
|
|
77
|
+
const reveals = [
|
|
78
|
+
{ start: 0, end: 3, at: 0 },
|
|
79
|
+
{ start: 3, end: 6, at: 100 },
|
|
80
|
+
];
|
|
81
|
+
expect(pruneReveals(reveals, STREAMING_FADE_MS + 50)).toEqual([{ start: 3, end: 6, at: 100 }]);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { JSX, ReactNode } from "react";
|
|
2
|
+
import { useLayoutEffect, useRef } from "react";
|
|
3
|
+
import type { HastElement, HastRoot, HastText } from "./nodes";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 流式新文字的淡入。
|
|
7
|
+
*
|
|
8
|
+
* 放字只有约 10Hz:文字一次性全亮上屏像「闪出来」,按放字节奏分级变亮又像掉帧。这里给每次新放出的
|
|
9
|
+
* 那段文字挂一段平滑的 opacity 淡入,由合成器按屏幕刷新率插值。实测(M4,毛玻璃开关均测):平滑
|
|
10
|
+
* 淡入与 30fps 分格淡入的 WindowServer 开销几乎相同,只比直接上屏多约 7 个百分点,且只在有字流出时发生。
|
|
11
|
+
*
|
|
12
|
+
* 动画起点锁在「放出那一刻」的绝对时间上:尾块每次重渲染都可能重建这些 span,新建的动画会接着原进度
|
|
13
|
+
* 播,而不是从 0 重播(那会让文字反复闪)。淡入结束后的放出记录会被丢弃,包裹随之撤掉。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** 单段新文字的淡入时长。 */
|
|
17
|
+
export const STREAMING_FADE_MS = 220;
|
|
18
|
+
const FADE_EASING = "cubic-bezier(0.2, 0, 0, 1)";
|
|
19
|
+
export const STREAMING_FADE_TAG = "vetta-reveal";
|
|
20
|
+
|
|
21
|
+
/** 一次放出:显示文本从 `start` 长到 `end`(UTF-16 下标),发生在 `at`(performance.now 时间基)。 */
|
|
22
|
+
export interface StreamingReveal {
|
|
23
|
+
readonly start: number;
|
|
24
|
+
readonly end: number;
|
|
25
|
+
readonly at: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 丢掉已经淡入完的放出记录。 */
|
|
29
|
+
export function pruneReveals(reveals: readonly StreamingReveal[], now: number): StreamingReveal[] {
|
|
30
|
+
return reveals.filter((reveal) => now - reveal.at < STREAMING_FADE_MS);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isLiteralTag(tag: string): boolean {
|
|
34
|
+
// 代码、表格、SVG 预览由各自组件按原文渲染,不能拆开包裹。
|
|
35
|
+
return tag === "code" || tag === "pre" || tag === "table" || tag === "vetta-svg";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 把仍在淡入期的放出区间包成 `<vetta-reveal data-reveal-at>`。区间是文档源码坐标,按 hast 文本节点的
|
|
40
|
+
* position 对齐;节点源码长度与文字长度不一致(转义、实体)时整段按其末尾归属,不做逐字映射。
|
|
41
|
+
* `offset` 是本文档在整段显示文本中的起始下标(尾块前面还有已冻结的块)。
|
|
42
|
+
*/
|
|
43
|
+
export function rehypeStreamingFade(reveals: readonly StreamingReveal[], offset: number) {
|
|
44
|
+
return () =>
|
|
45
|
+
(tree: HastRoot): void => {
|
|
46
|
+
if (reveals.length === 0) return;
|
|
47
|
+
const local = reveals
|
|
48
|
+
.map((reveal) => ({ start: reveal.start - offset, end: reveal.end - offset, at: reveal.at }))
|
|
49
|
+
.filter((reveal) => reveal.end > 0);
|
|
50
|
+
if (local.length === 0) return;
|
|
51
|
+
const firstStart = Math.max(0, Math.min(...local.map((reveal) => reveal.start)));
|
|
52
|
+
|
|
53
|
+
const split = (node: HastText): Array<HastText | HastElement> | null => {
|
|
54
|
+
const start = node.position?.start.offset;
|
|
55
|
+
const end = node.position?.end.offset;
|
|
56
|
+
if (start === undefined || end === undefined || end <= firstStart) return null;
|
|
57
|
+
const value = node.value;
|
|
58
|
+
const exact = value.length === end - start;
|
|
59
|
+
const pieces: Array<HastText | HastElement> = [];
|
|
60
|
+
let cursor = 0;
|
|
61
|
+
for (const reveal of local) {
|
|
62
|
+
let from: number;
|
|
63
|
+
let to: number;
|
|
64
|
+
if (exact) {
|
|
65
|
+
from = Math.max(0, reveal.start - start);
|
|
66
|
+
to = Math.min(value.length, reveal.end - start);
|
|
67
|
+
} else {
|
|
68
|
+
const owns = end > reveal.start && end <= reveal.end;
|
|
69
|
+
from = 0;
|
|
70
|
+
to = owns ? value.length : 0;
|
|
71
|
+
}
|
|
72
|
+
const pieceStart = Math.max(cursor, from);
|
|
73
|
+
if (to <= pieceStart) continue;
|
|
74
|
+
if (pieceStart > cursor) pieces.push({ type: "text", value: value.slice(cursor, pieceStart) } as HastText);
|
|
75
|
+
pieces.push({
|
|
76
|
+
type: "element",
|
|
77
|
+
tagName: STREAMING_FADE_TAG,
|
|
78
|
+
properties: { dataRevealAt: String(reveal.at) },
|
|
79
|
+
children: [{ type: "text", value: value.slice(pieceStart, to) } as HastText],
|
|
80
|
+
} as HastElement);
|
|
81
|
+
cursor = to;
|
|
82
|
+
}
|
|
83
|
+
if (pieces.length === 0) return null;
|
|
84
|
+
if (cursor < value.length) pieces.push({ type: "text", value: value.slice(cursor) } as HastText);
|
|
85
|
+
return pieces;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const visit = (node: HastRoot | HastElement): void => {
|
|
89
|
+
const next: Array<(typeof node.children)[number]> = [];
|
|
90
|
+
let changed = false;
|
|
91
|
+
for (const child of node.children) {
|
|
92
|
+
if (child.type === "text") {
|
|
93
|
+
const pieces = split(child as HastText);
|
|
94
|
+
if (pieces) {
|
|
95
|
+
next.push(...(pieces as typeof next));
|
|
96
|
+
changed = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
} else if (child.type === "element" && !isLiteralTag(child.tagName)) {
|
|
100
|
+
visit(child);
|
|
101
|
+
}
|
|
102
|
+
next.push(child);
|
|
103
|
+
}
|
|
104
|
+
if (changed) node.children = next as typeof node.children;
|
|
105
|
+
};
|
|
106
|
+
visit(tree);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function prefersReducedMotion(): boolean {
|
|
111
|
+
return typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 正在淡入的一段文字。起点锁在放出时刻,重建也不会重播。 */
|
|
115
|
+
export function StreamingFadeSpan({
|
|
116
|
+
children,
|
|
117
|
+
"data-reveal-at": revealAt,
|
|
118
|
+
}: {
|
|
119
|
+
children?: ReactNode;
|
|
120
|
+
"data-reveal-at"?: string;
|
|
121
|
+
}): JSX.Element {
|
|
122
|
+
const ref = useRef<HTMLSpanElement>(null);
|
|
123
|
+
useLayoutEffect(() => {
|
|
124
|
+
const element = ref.current;
|
|
125
|
+
const at = Number(revealAt);
|
|
126
|
+
if (!element || !Number.isFinite(at) || typeof element.animate !== "function") return;
|
|
127
|
+
if (performance.now() - at >= STREAMING_FADE_MS || prefersReducedMotion()) return;
|
|
128
|
+
const animation = element.animate([{ opacity: 0 }, { opacity: 1 }], {
|
|
129
|
+
duration: STREAMING_FADE_MS,
|
|
130
|
+
easing: FADE_EASING,
|
|
131
|
+
fill: "backwards",
|
|
132
|
+
});
|
|
133
|
+
animation.startTime = at;
|
|
134
|
+
return () => animation.cancel();
|
|
135
|
+
}, [revealAt]);
|
|
136
|
+
return (
|
|
137
|
+
<span ref={ref} className="streaming-fade">
|
|
138
|
+
{children}
|
|
139
|
+
</span>
|
|
140
|
+
);
|
|
141
|
+
}
|