@vetta-org/theme-ui 0.2.0 → 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.
Files changed (54) hide show
  1. package/package.json +1 -1
  2. package/src/action-approval/StorageCleanListView.test.tsx +36 -0
  3. package/src/action-approval/StorageCleanListView.tsx +52 -0
  4. package/src/action-approval/index.ts +2 -0
  5. package/src/activity/ActivityPanel.tsx +7 -1
  6. package/src/activity/BackgroundTasksTabPanelView.tsx +18 -2
  7. package/src/activity/BrowserPanelView.tsx +15 -1
  8. package/src/activity/BrowserSelectionView.tsx +199 -0
  9. package/src/activity/index.ts +1 -0
  10. package/src/chat/EditDiffView.tsx +4 -4
  11. package/src/chat/HeaderActionBarView.tsx +16 -4
  12. package/src/chat/streaming-reveal.test.ts +1 -74
  13. package/src/chat/streaming-reveal.ts +0 -3
  14. package/src/file-preview/FilePreviewDialogView.tsx +2 -1
  15. package/src/layout/ResizeHandle.tsx +4 -1
  16. package/src/layout/resize-handle-reset.test.tsx +50 -0
  17. package/src/markdown/MarkdownContent.tsx +49 -26
  18. package/src/markdown/UrlLinkBadge.tsx +84 -0
  19. package/src/markdown/index.ts +1 -0
  20. package/src/markdown/nodes.ts +6 -1
  21. package/src/markdown/rich-labels.ts +3 -0
  22. package/src/markdown/streaming-fade.test.ts +83 -0
  23. package/src/markdown/streaming-fade.tsx +141 -0
  24. package/src/markdown/streaming-reveal.ts +0 -67
  25. package/src/markdown/streaming.ts +64 -131
  26. package/src/overlays/CommandMenuRow.tsx +4 -14
  27. package/src/overlays/CommandMenuView.tsx +11 -4
  28. package/src/overlays/ReleaseNoteImage.test.tsx +105 -0
  29. package/src/overlays/ReleaseNoteMarkdown.test.tsx +25 -0
  30. package/src/overlays/ReleaseNoteMarkdown.tsx +94 -7
  31. package/src/overlays/UpdateCheckerView.tsx +17 -15
  32. package/src/overlays/UpdateRestartDialogView.tsx +14 -5
  33. package/src/overlays/command-menu-types.ts +2 -0
  34. package/src/overlays/index.ts +1 -0
  35. package/src/plugin-ui/index.ts +2 -0
  36. package/src/project/DefaultConversationSectionView.tsx +4 -0
  37. package/src/project/ManageSessionsSplashView.tsx +0 -2
  38. package/src/settings/GeneralSettingsView.tsx +19 -0
  39. package/src/settings/LauncherSettingsView.tsx +0 -1
  40. package/src/settings/StorageBar.tsx +70 -0
  41. package/src/settings/StorageExplorer.tsx +488 -0
  42. package/src/settings/StorageReadout.tsx +64 -0
  43. package/src/settings/StorageSettingsView.test.tsx +181 -0
  44. package/src/settings/StorageSettingsView.tsx +458 -0
  45. package/src/settings/index.ts +10 -0
  46. package/src/settings/storage-treemap-layout.test.ts +32 -0
  47. package/src/settings/storage-treemap-layout.ts +55 -0
  48. package/src/shared/SegmentedControl.tsx +10 -11
  49. package/src/shared/StageDialogContent.test.tsx +61 -0
  50. package/src/shared/StageDialogContent.tsx +80 -0
  51. package/src/shared/index.ts +2 -0
  52. package/src/sidebar/AddProjectMenuTriggerView.tsx +4 -2
  53. package/src/styles.css +5 -0
  54. package/src/markdown/streaming.test.ts +0 -57
@@ -1,68 +1,6 @@
1
1
  import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
2
- import type { HastElement, HastRoot, HastText } from "./nodes";
3
- import {
4
- DEFAULT_RATE_PER_MS,
5
- planReveal,
6
- REVEAL_TICK_MS,
7
- STREAMING_IDLE_SETTLE_MS,
8
- STREAMING_SETTLE_MS,
9
- STREAMING_STALL_FLUSH_MS,
10
- splitStreamingSegments,
11
- } from "./streaming-reveal";
12
-
13
- const WHITESPACE_ONLY = /^\s+$/;
14
-
15
- /**
16
- * 把流式尾块的正文按短语包成 `.streaming-chunk`,最新的两个短语再加 `-latest` / `-recent`:
17
- * 宿主 CSS 让它们略暗,下一次放出短语时随重渲染一起变亮。不用 CSS 淡入动画——每个短语各跑一段
18
- * 动画意味着流式全程连续出帧,毛玻璃窗口每帧都要整窗重合成;这样亮度只随放出节奏变,不多一帧。
19
- */
20
- export function rehypeStreamingChunks() {
21
- return (tree: HastRoot): void => {
22
- const chunks: HastElement[] = [];
23
- function visit(node: HastRoot | HastElement, inCode: boolean): void {
24
- const newChildren: Array<(typeof node.children)[number]> = [];
25
- for (const child of node.children) {
26
- if (child.type === "text" && !inCode) {
27
- for (const segment of splitStreamingSegments((child as HastText).value)) {
28
- if (WHITESPACE_ONLY.test(segment)) {
29
- newChildren.push({ type: "text", value: segment } as HastText);
30
- continue;
31
- }
32
- const chunk: HastElement = {
33
- type: "element",
34
- tagName: "span",
35
- properties: { className: ["streaming-chunk"] },
36
- children: [{ type: "text", value: segment } as HastText],
37
- };
38
- chunks.push(chunk);
39
- newChildren.push(chunk);
40
- }
41
- } else {
42
- newChildren.push(child);
43
- if (child.type === "element") {
44
- const tag = child.tagName;
45
- // 表格也当字面量:单元格文字被拆成片段再逐步增长会反复触发列宽重算,
46
- // 流式期表格会抖动。
47
- visit(child, inCode || tag === "code" || tag === "pre" || tag === "table" || tag === "vetta-svg");
48
- }
49
- }
50
- }
51
- node.children = newChildren as typeof node.children;
52
- }
53
-
54
- visit(tree, false);
55
- const latest = chunks.at(-1);
56
- const recent = chunks.at(-2);
57
- if (latest) latest.properties = { className: ["streaming-chunk", "streaming-chunk-latest"] };
58
- if (recent) recent.properties = { className: ["streaming-chunk", "streaming-chunk-recent"] };
59
- };
60
- }
61
-
62
- interface StreamingDisplayState {
63
- displayText: string;
64
- animateChunks: boolean;
65
- }
2
+ import { pruneReveals, STREAMING_FADE_MS, type StreamingReveal } from "./streaming-fade";
3
+ import { DEFAULT_RATE_PER_MS, planReveal, REVEAL_TICK_MS, STREAMING_STALL_FLUSH_MS } from "./streaming-reveal";
66
4
 
67
5
  function clearTimeoutRef(ref: { current: number | null }): void {
68
6
  if (ref.current !== null) {
@@ -87,16 +25,24 @@ function estimateRate(samples: readonly ArrivalSample[], now: number): number {
87
25
  return (last.length - first.length) / (last.at - first.at);
88
26
  }
89
27
 
28
+ export interface StreamingDisplay {
29
+ readonly text: string;
30
+ /** 仍在淡入期的放出区间,供尾块给新文字挂淡入(见 streaming-fade)。 */
31
+ readonly reveals: readonly StreamingReveal[];
32
+ }
33
+
34
+ const NO_REVEALS: readonly StreamingReveal[] = [];
35
+
90
36
  /**
91
- * 流式尾块:把显示文本匀速追向宿主文本(节奏见 streaming-reveal),配合 rehype 分段做「最新短语略暗」。
37
+ * 流式尾块:把显示文本匀速追向宿主文本(节奏见 streaming-reveal),并记下每次放出的区间与时刻,
38
+ * 让新文字平滑淡入(streaming-fade)。
92
39
  * 放出由 `text` 变化(宿主每 100ms 一次的增量刷新)驱动,在布局效果里同步更新,与那次渲染落在同一帧;
93
- * 没有新文本时由兜底 tick 收尾。尾部未写完的词、未闭合的行内语法先扣着;流结束后按节奏放完再撤掉分段。
40
+ * 没有新文本时由兜底 tick 收尾。尾部未写完的词、未闭合的行内语法先扣着;流结束后一次放完。
94
41
  *
95
- * 从未作为尾块流式过的实例(历史消息、产品故事等由宿主自己驱动逐字的场景)直接镜像 `text`。
42
+ * 从未作为尾块流式过的实例(历史消息、产品故事等由宿主自己驱动逐字的场景)直接镜像 `text`,不淡入。
96
43
  */
97
- export function useStreamingDisplayText(text: string, active: boolean): StreamingDisplayState {
98
- const [displayText, setDisplayText] = useState(() => (active ? "" : text));
99
- const [animateChunks, setAnimateChunks] = useState(active);
44
+ export function useStreamingDisplayText(text: string, active: boolean): StreamingDisplay {
45
+ const [display, setDisplay] = useState<StreamingDisplay>(() => ({ text: active ? "" : text, reveals: NO_REVEALS }));
100
46
  const displayRef = useRef(active ? "" : text);
101
47
  const targetRef = useRef(text);
102
48
  const activeRef = useRef(active);
@@ -108,67 +54,58 @@ export function useStreamingDisplayText(text: string, active: boolean): Streamin
108
54
  /** 扣留开始的时间;null 表示当前没有扣留。 */
109
55
  const heldSinceRef = useRef<number | null>(null);
110
56
  const tickTimerRef = useRef<number | null>(null);
111
- const settleTimerRef = useRef<number | null>(null);
57
+ /** 最后一段淡入结束后撤掉包裹,让尾块回到纯文本节点。 */
58
+ const fadeClearTimerRef = useRef<number | null>(null);
112
59
 
113
- const settle = useCallback((): void => {
114
- if (settleTimerRef.current !== null) return;
115
- settleTimerRef.current = window.setTimeout(() => {
116
- settleTimerRef.current = null;
60
+ const reveal = useCallback(function reveal(): void {
61
+ clearTimeoutRef(tickTimerRef);
62
+ const now = Date.now();
63
+ const target = targetRef.current;
64
+ const shown = displayRef.current.length;
65
+ const final = !activeRef.current;
66
+ const stalled = !final && now - lastArrivalAtRef.current >= STREAMING_STALL_FLUSH_MS;
67
+ const step = planReveal({
68
+ text: target,
69
+ revealed: shown,
70
+ final,
71
+ ratePerMs: estimateRate(samplesRef.current, now),
72
+ elapsedMs: lastAdvanceAtRef.current ? now - lastAdvanceAtRef.current : REVEAL_TICK_MS,
73
+ stalled,
74
+ heldMs: heldSinceRef.current === null ? 0 : now - heldSinceRef.current,
75
+ });
76
+ if (step?.held) heldSinceRef.current ??= now;
77
+ else heldSinceRef.current = null;
78
+ if (step && step.end > shown) {
79
+ const next = target.slice(0, step.end);
80
+ displayRef.current = next;
81
+ const at = performance.now();
82
+ setDisplay((current) => ({
83
+ text: next,
84
+ reveals: [...pruneReveals(current.reveals, at), { start: shown, end: next.length, at }],
85
+ }));
86
+ clearTimeoutRef(fadeClearTimerRef);
87
+ fadeClearTimerRef.current = window.setTimeout(() => {
88
+ fadeClearTimerRef.current = null;
89
+ // 计时从最后一次放出算起,到点时所有记录都已淡入完。
90
+ setDisplay((current) =>
91
+ current.reveals.length === 0 ? current : { text: current.text, reveals: NO_REVEALS },
92
+ );
93
+ }, STREAMING_FADE_MS);
94
+ lastAdvanceAtRef.current = now;
95
+ }
96
+ if (displayRef.current.length >= target.length) lastAdvanceAtRef.current = now;
97
+ if (displayRef.current.length < target.length) {
98
+ tickTimerRef.current = window.setTimeout(reveal, REVEAL_TICK_MS);
99
+ } else if (final) {
100
+ // 流已结束且已放完:之后的文本变化直接镜像。
117
101
  streamedRef.current = false;
118
- setAnimateChunks(false);
119
- }, STREAMING_SETTLE_MS);
120
- }, []);
121
-
122
- /** 已追平但流未结束:静默一会儿后只撤暗色,保留 streamedRef,新文本到达时布局效果会重新挂上。 */
123
- const settleIdle = useCallback((): void => {
124
- if (settleTimerRef.current !== null) return;
125
- settleTimerRef.current = window.setTimeout(() => {
126
- settleTimerRef.current = null;
127
- setAnimateChunks(false);
128
- }, STREAMING_IDLE_SETTLE_MS);
102
+ }
129
103
  }, []);
130
104
 
131
- const reveal = useCallback(
132
- function reveal(): void {
133
- clearTimeoutRef(tickTimerRef);
134
- const now = Date.now();
135
- const target = targetRef.current;
136
- const shown = displayRef.current.length;
137
- const final = !activeRef.current;
138
- const stalled = !final && now - lastArrivalAtRef.current >= STREAMING_STALL_FLUSH_MS;
139
- const step = planReveal({
140
- text: target,
141
- revealed: shown,
142
- final,
143
- ratePerMs: estimateRate(samplesRef.current, now),
144
- elapsedMs: lastAdvanceAtRef.current ? now - lastAdvanceAtRef.current : REVEAL_TICK_MS,
145
- stalled,
146
- heldMs: heldSinceRef.current === null ? 0 : now - heldSinceRef.current,
147
- });
148
- if (step?.held) heldSinceRef.current ??= now;
149
- else heldSinceRef.current = null;
150
- if (step && step.end > shown) {
151
- const next = target.slice(0, step.end);
152
- displayRef.current = next;
153
- setDisplayText(next);
154
- lastAdvanceAtRef.current = now;
155
- }
156
- if (displayRef.current.length >= target.length) lastAdvanceAtRef.current = now;
157
- if (displayRef.current.length < target.length) {
158
- tickTimerRef.current = window.setTimeout(reveal, REVEAL_TICK_MS);
159
- } else if (final) {
160
- settle();
161
- } else {
162
- settleIdle();
163
- }
164
- },
165
- [settle, settleIdle],
166
- );
167
-
168
105
  useEffect(
169
106
  () => () => {
170
107
  clearTimeoutRef(tickTimerRef);
171
- clearTimeoutRef(settleTimerRef);
108
+ clearTimeoutRef(fadeClearTimerRef);
172
109
  },
173
110
  [],
174
111
  );
@@ -184,19 +121,15 @@ export function useStreamingDisplayText(text: string, active: boolean): Streamin
184
121
  if (!streamedRef.current || !text.startsWith(shown)) {
185
122
  // 从未流式过,或宿主改写了已显示内容(不是追加):直接对齐,不做节奏。
186
123
  clearTimeoutRef(tickTimerRef);
187
- clearTimeoutRef(settleTimerRef);
124
+ clearTimeoutRef(fadeClearTimerRef);
188
125
  samplesRef.current = [];
189
126
  heldSinceRef.current = null;
190
127
  displayRef.current = text;
191
- setDisplayText(text);
192
- setAnimateChunks(false);
128
+ setDisplay({ text, reveals: NO_REVEALS });
193
129
  streamedRef.current = active;
194
130
  return;
195
131
  }
196
132
 
197
- clearTimeoutRef(settleTimerRef);
198
- // 只在有新内容要放时挂暗色:空闲撤暗后回合才结束(文本没变)时不能再暗一下。
199
- if (textChanged || shown.length < text.length) setAnimateChunks(true);
200
133
  const now = Date.now();
201
134
  if (textChanged || lastArrivalAtRef.current === 0) {
202
135
  lastArrivalAtRef.current = now;
@@ -207,5 +140,5 @@ export function useStreamingDisplayText(text: string, active: boolean): Streamin
207
140
  reveal();
208
141
  }, [text, active, reveal]);
209
142
 
210
- return { displayText, animateChunks };
143
+ return display;
211
144
  }
@@ -1,4 +1,3 @@
1
- import { motion } from "motion/react";
2
1
  import { memo, type JSX } from "react";
3
2
  import { cn } from "@vetta-org/ui/utils";
4
3
  import { ConversationTagDotsView } from "../project/ConversationTagDotsView";
@@ -39,8 +38,6 @@ function Highlighted({
39
38
  export interface CommandMenuRowProps {
40
39
  readonly item: CommandMenuItemView;
41
40
  readonly active: boolean;
42
- /** 结果集刚变化时抑制指示条的位移动画,避免逐击键抖动。 */
43
- readonly suppressSelectionAnimation: boolean;
44
41
  readonly onActivate: (id: string) => void;
45
42
  readonly onHover: (id: string) => void;
46
43
  /** 给了就在悬停 / 选中时于行尾显示「更多」按钮,给不爱用键盘的人。 */
@@ -52,7 +49,6 @@ export interface CommandMenuRowProps {
52
49
  export const CommandMenuRow = memo(function CommandMenuRow({
53
50
  item,
54
51
  active,
55
- suppressSelectionAnimation,
56
52
  onActivate,
57
53
  onHover,
58
54
  onMore,
@@ -82,17 +78,11 @@ export const CommandMenuRow = memo(function CommandMenuRow({
82
78
  )}
83
79
  >
84
80
  {active && (
85
- <motion.span
81
+ // 选中底色由当前行直接画,换行即换,不做行间滑动:连按方向键时滑动动画会被反复打断,
82
+ // 再叠上列表滚动跟随,指示条会落后、回跳,手感发飘。
83
+ <span
86
84
  aria-hidden="true"
87
- layoutId="command-menu-active-marker"
88
- // 结果重算时 layout 动画会把指示条从旧行“弹”到新行,逐击键播放既抖又费;
89
- // 只有用户主动上下移动选中项时才让它滑动。
90
- layout={!suppressSelectionAnimation}
91
- transition={
92
- suppressSelectionAnimation
93
- ? { duration: 0 }
94
- : { type: "spring", stiffness: 500, damping: 32 }
95
- }
85
+ data-slot="command-menu-active-marker"
96
86
  className="absolute inset-0 rounded-lg bg-foreground/[0.06] dark:bg-white/[0.08] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.08)]"
97
87
  />
98
88
  )}
@@ -41,8 +41,8 @@ export interface CommandMenuViewProps {
41
41
  readonly onNewSession?: () => void;
42
42
  /** 新建会话的生效快捷键,显示在按钮里。 */
43
43
  readonly newSessionShortcut?: string;
44
- /** 结果集因击键刚变化:抑制选中指示条的位移动画。 */
45
- readonly suppressSelectionAnimation: boolean;
44
+ /** 给了就在「新会话」同一组里追加「全部已读」;宿主只在有跑完未看的会话时传。 */
45
+ readonly onMarkAllRead?: () => void;
46
46
  readonly inputRef?: RefObject<HTMLInputElement | null>;
47
47
  readonly onQueryChange: (value: string) => void;
48
48
  readonly onHoverItem: (id: string) => void;
@@ -59,7 +59,7 @@ export function CommandMenuView({
59
59
  toggleShortcut,
60
60
  onNewSession,
61
61
  newSessionShortcut,
62
- suppressSelectionAnimation,
62
+ onMarkAllRead,
63
63
  inputRef,
64
64
  onQueryChange,
65
65
  onHoverItem,
@@ -147,7 +147,6 @@ export function CommandMenuView({
147
147
  key={item.id}
148
148
  item={item}
149
149
  active={item.id === selectedId}
150
- suppressSelectionAnimation={suppressSelectionAnimation}
151
150
  onActivate={onActivateItem}
152
151
  onHover={handleHoverItem}
153
152
  registerRef={registerRef}
@@ -187,6 +186,7 @@ export function CommandMenuView({
187
186
  <div className="pointer-events-none absolute inset-x-2.5 bottom-2.5 z-10 flex items-center justify-between gap-2">
188
187
  {onNewSession ? (
189
188
  // 只有图标的圆形按钮:胶囊里单个纯图标项正好是一颗与右侧按钮组等高的圆。
189
+ // 有跑完未看的会话时同组追加「全部已读」,胶囊随之拉长,不另起一组。
190
190
  <ButtonGroup className={COMMAND_MENU_FLOATING_GROUP_CLASS}>
191
191
  <ButtonGroupItem
192
192
  onClick={onNewSession}
@@ -194,6 +194,13 @@ export function CommandMenuView({
194
194
  title={newSessionShortcut ? `${labels.newSession} (${formatKbdTitle(newSessionShortcut)})` : labels.newSession}
195
195
  icon={<span aria-hidden="true" className="icon-[solar--pen-new-square-linear] size-4" />}
196
196
  />
197
+ {onMarkAllRead && labels.markAllRead ? (
198
+ <ButtonGroupItem
199
+ onClick={onMarkAllRead}
200
+ icon={<span aria-hidden="true" className="icon-[solar--check-read-linear] size-4" />}
201
+ label={labels.markAllRead}
202
+ />
203
+ ) : null}
197
204
  </ButtonGroup>
198
205
  ) : (
199
206
  <span />
@@ -0,0 +1,105 @@
1
+ // @vitest-environment jsdom
2
+
3
+ import { act, type JSX, useState } from "react";
4
+ import { createRoot, type Root } from "react-dom/client";
5
+ import { afterEach, describe, expect, it } from "vitest";
6
+ import { ReleaseNoteMarkdown } from "./ReleaseNoteMarkdown";
7
+
8
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
9
+
10
+ const URL_ZH = "https://github.com/openvetta/open-vetta/releases/download/v0.6.34/whats-new-zh.webp";
11
+ const mounted: Array<{ root: Root; container: HTMLDivElement }> = [];
12
+
13
+ afterEach(() => {
14
+ for (const { root, container } of mounted.splice(0)) {
15
+ act(() => root.unmount());
16
+ container.remove();
17
+ }
18
+ });
19
+
20
+ function mount(note: string, onOpenImage?: (image: { src: string; alt: string }) => void): HTMLDivElement {
21
+ const container = document.createElement("div");
22
+ document.body.append(container);
23
+ const root = createRoot(container);
24
+ mounted.push({ root, container });
25
+ act(() => root.render(<ReleaseNoteMarkdown onOpenImage={onOpenImage}>{note}</ReleaseNoteMarkdown>));
26
+ return container;
27
+ }
28
+
29
+ /** 最小宿主:点图后显示一个灯箱,测的是用户看到的结果而不是回调本身。 */
30
+ function HostWithLightbox({ note }: { readonly note: string }): JSX.Element {
31
+ const [opened, setOpened] = useState<{ src: string; alt: string } | null>(null);
32
+ return (
33
+ <>
34
+ <ReleaseNoteMarkdown onOpenImage={setOpened}>{note}</ReleaseNoteMarkdown>
35
+ {opened && (
36
+ <div role="dialog" data-src={opened.src}>
37
+ {opened.alt}
38
+ </div>
39
+ )}
40
+ </>
41
+ );
42
+ }
43
+
44
+ describe("release note images", () => {
45
+ it("shows the image once it has loaded", () => {
46
+ const container = mount(`![本版介绍](${URL_ZH})\n\n- 一条`);
47
+ const image = container.querySelector("img") as HTMLImageElement;
48
+ expect(image.classList.contains("hidden")).toBe(true);
49
+
50
+ act(() => {
51
+ image.dispatchEvent(new Event("load"));
52
+ });
53
+
54
+ expect(image.classList.contains("hidden")).toBe(false);
55
+ expect(image.dataset.releaseImage).toBe("loaded");
56
+ });
57
+
58
+ it("renders as if there were no image when loading fails, keeping the text", () => {
59
+ const container = mount(`[![本版介绍](${URL_ZH})](${URL_ZH})\n\n- 一条`);
60
+ const image = container.querySelector("img") as HTMLImageElement;
61
+
62
+ act(() => {
63
+ image.dispatchEvent(new Event("error"));
64
+ });
65
+
66
+ expect(container.querySelector("img")).toBeNull();
67
+ expect(container.textContent?.trim()).toBe("一条");
68
+ // 只装着配图的段落要收起边距,否则失败后会多出一段空白。
69
+ const paragraph = container.querySelector("p") as HTMLParagraphElement;
70
+ expect(paragraph.querySelector('[data-release-image="failed"]')).not.toBeNull();
71
+ expect(paragraph.className).toContain("[&:has([data-release-image])]:my-0");
72
+ });
73
+
74
+ it("opens the loaded image in the host lightbox instead of following the GitHub link", () => {
75
+ const container = document.createElement("div");
76
+ document.body.append(container);
77
+ const root = createRoot(container);
78
+ mounted.push({ root, container });
79
+ act(() => root.render(<HostWithLightbox note={`[![本版介绍](${URL_ZH})](${URL_ZH})`} />));
80
+ const image = container.querySelector("img") as HTMLImageElement;
81
+ const button = container.querySelector("button") as HTMLButtonElement;
82
+ expect(button.className).toBe("hidden");
83
+
84
+ act(() => {
85
+ image.dispatchEvent(new Event("load"));
86
+ });
87
+ expect(button.className).toContain("cursor-zoom-in");
88
+ expect(button.getAttribute("aria-label")).toBe("本版介绍");
89
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
90
+
91
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
92
+ act(() => {
93
+ button.dispatchEvent(click);
94
+ });
95
+ const lightbox = container.querySelector('[role="dialog"]') as HTMLElement;
96
+ expect(lightbox.getAttribute("data-src")).toBe(URL_ZH);
97
+ expect(lightbox.textContent).toBe("本版介绍");
98
+ expect(click.defaultPrevented).toBe(true);
99
+ });
100
+
101
+ it("is not clickable when the host offers no lightbox", () => {
102
+ const container = mount(`![本版介绍](${URL_ZH})`);
103
+ expect(container.querySelector("button")).toBeNull();
104
+ });
105
+ });
@@ -21,4 +21,29 @@ describe("ReleaseNoteMarkdown", () => {
21
21
  expect(html).not.toContain("<a");
22
22
  expect(html).toContain("the docs");
23
23
  });
24
+
25
+ it("keeps a release image hidden until it loads, so a failed load shows nothing", () => {
26
+ const url = "https://github.com/openvetta/open-vetta/releases/download/v0.6.34/whats-new-zh.webp";
27
+ const html = renderNote(`![本版介绍](${url})\n\n- 一条`);
28
+
29
+ expect(html).toContain(`src="${url}"`);
30
+ expect(html).toContain('alt="本版介绍"');
31
+ expect(html).toContain('data-release-image="loading"');
32
+ expect(html).toMatch(/<img[^>]*class="hidden"/);
33
+ expect(html).not.toContain('loading="lazy"');
34
+ });
35
+
36
+ it("does not load images from non-https addresses", () => {
37
+ for (const src of ["file:///etc/hosts", "http://example.com/a.png"]) {
38
+ const html = renderNote(`![x](${src})`);
39
+ expect(html).not.toContain("<img");
40
+ expect(html).toContain('data-release-image="failed"');
41
+ }
42
+ });
43
+
44
+ it("shows inline image data used by the development preview, but no other data URLs", () => {
45
+ const html = renderNote("![预览](data:image/webp;base64,UklGRg==)");
46
+ expect(html).toContain('src="data:image/webp;base64,UklGRg=="');
47
+ expect(renderNote("![x](data:text/html;base64,PGI+)")).not.toContain("<img");
48
+ });
24
49
  });
@@ -1,5 +1,5 @@
1
- import type { JSX } from "react";
2
- import ReactMarkdown, { type Components } from "react-markdown";
1
+ import { createContext, type JSX, type MouseEvent, useContext, useState } from "react";
2
+ import ReactMarkdown, { type Components, defaultUrlTransform } from "react-markdown";
3
3
  import remarkGfm from "remark-gfm";
4
4
 
5
5
  const EXTERNAL_LINK_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);
@@ -13,6 +13,74 @@ function isExternalLink(href: string | undefined): href is string {
13
13
  }
14
14
  }
15
15
 
16
+ // 开发态预览会把本地暂存的配图内嵌成 data URL;只放行图片类型。
17
+ const INLINE_IMAGE = /^data:image\/(?:webp|png|jpeg|gif|avif);base64,/;
18
+
19
+ function isWebImage(src: string | undefined): src is string {
20
+ if (!src) return false;
21
+ if (INLINE_IMAGE.test(src)) return true;
22
+ try {
23
+ return new URL(src).protocol === "https:";
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ export interface ReleaseNoteImageTarget {
30
+ readonly src: string;
31
+ readonly alt: string;
32
+ }
33
+
34
+ const OpenImageContext = createContext<((image: ReleaseNoteImageTarget) => void) | undefined>(undefined);
35
+
36
+ /**
37
+ * 发布说明的配图托管在 GitHub Release 附件里,离线、被墙或还没上传时都会加载失败。
38
+ * 加载成功前不占位,失败就整张不渲染:用户看到的和没配图时一样,不出现破图图标。
39
+ * 不用 loading="lazy":懒加载的图在 display:none 时不会发起请求,永远等不到 onLoad。
40
+ */
41
+ function ReleaseNoteImage({ src, alt }: { readonly src?: string; readonly alt?: string }): JSX.Element {
42
+ const [state, setState] = useState<"loading" | "loaded" | "failed">("loading");
43
+ const onOpen = useContext(OpenImageContext);
44
+ // 失败时留一个隐藏标记,让外层段落仍认得「这里只有配图」而收起边距。
45
+ if (!isWebImage(src) || state === "failed") return <span hidden data-release-image="failed" />;
46
+ const loaded = state === "loaded";
47
+ const image = (
48
+ <img
49
+ src={src}
50
+ alt={alt ?? ""}
51
+ decoding="async"
52
+ draggable={false}
53
+ data-release-image={state}
54
+ onLoad={() => setState("loaded")}
55
+ onError={() => setState("failed")}
56
+ className={
57
+ !loaded ? "hidden" : onOpen ? "block h-auto w-full" : "my-2 block h-auto w-full rounded-md border border-border/60"
58
+ }
59
+ />
60
+ );
61
+ if (!onOpen) return image;
62
+ // 点图在宿主的灯箱里放大看;GitHub 正文会把图包在链接里,这里拦下,不跳去浏览器。
63
+ const open = (event: MouseEvent) => {
64
+ event.preventDefault();
65
+ event.stopPropagation();
66
+ onOpen({ src, alt: alt ?? "" });
67
+ };
68
+ return (
69
+ <button
70
+ type="button"
71
+ aria-label={alt}
72
+ onClick={open}
73
+ className={
74
+ loaded
75
+ ? "my-2 block w-full cursor-zoom-in overflow-hidden rounded-md border border-border/60 outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
76
+ : "hidden"
77
+ }
78
+ >
79
+ {image}
80
+ </button>
81
+ );
82
+ }
83
+
16
84
  /** 更新日志的排版:标题、列表、行内代码要有层次和间距,不依赖宿主的 markdown 样式。 */
17
85
  const releaseNoteComponents: Components = {
18
86
  h1: ({ children }) => <h1 className="mb-2 text-[14px] font-semibold text-foreground">{children}</h1>,
@@ -20,7 +88,9 @@ const releaseNoteComponents: Components = {
20
88
  <h2 className="mb-1.5 mt-4 text-[13px] font-semibold text-foreground first:mt-0">{children}</h2>
21
89
  ),
22
90
  h3: ({ children }) => <h3 className="mb-1 mt-3 text-[12.5px] font-semibold text-foreground">{children}</h3>,
23
- p: ({ children }) => <p className="my-1.5">{children}</p>,
91
+ // 只装着配图的段落不留外边距:图没加载出来时整段高度为零,和没配图一样。
92
+ p: ({ children }) => <p className="my-1.5 [&:has([data-release-image])]:my-0">{children}</p>,
93
+ img: ({ src, alt }) => <ReleaseNoteImage src={typeof src === "string" ? src : undefined} alt={alt} />,
24
94
  ul: ({ children }) => <ul className="my-1.5 list-disc space-y-1.5 pl-5">{children}</ul>,
25
95
  ol: ({ children }) => <ol className="my-1.5 list-decimal space-y-1.5 pl-5">{children}</ol>,
26
96
  li: ({ children }) => <li className="pl-0.5">{children}</li>,
@@ -45,11 +115,28 @@ const releaseNoteComponents: Components = {
45
115
  ),
46
116
  };
47
117
 
118
+ function releaseNoteUrlTransform(url: string, key: string): string {
119
+ return key === "src" && INLINE_IMAGE.test(url) ? url : defaultUrlTransform(url);
120
+ }
121
+
48
122
  /** 更新日志的 Markdown 渲染:设置页预览与更新弹窗共用。 */
49
- export function ReleaseNoteMarkdown({ children }: { readonly children: string }): JSX.Element {
123
+ export function ReleaseNoteMarkdown({
124
+ children,
125
+ onOpenImage,
126
+ }: {
127
+ readonly children: string;
128
+ /** 点配图时调用,宿主据此打开灯箱;不传时配图只展示、不可点。 */
129
+ readonly onOpenImage?: (image: ReleaseNoteImageTarget) => void;
130
+ }): JSX.Element {
50
131
  return (
51
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={releaseNoteComponents}>
52
- {children}
53
- </ReactMarkdown>
132
+ <OpenImageContext.Provider value={onOpenImage}>
133
+ <ReactMarkdown
134
+ remarkPlugins={[remarkGfm]}
135
+ components={releaseNoteComponents}
136
+ urlTransform={releaseNoteUrlTransform}
137
+ >
138
+ {children}
139
+ </ReactMarkdown>
140
+ </OpenImageContext.Provider>
54
141
  );
55
142
  }
@@ -31,7 +31,7 @@ export interface UpdateCheckerViewProps {
31
31
  readonly currentVersion: string;
32
32
  readonly labels: UpdateCheckerViewLabels;
33
33
  readonly latestVersion?: string;
34
- readonly onCheck: () => void;
34
+ readonly onCheck?: () => void;
35
35
  readonly onPrimary: () => void;
36
36
  readonly onViewMore?: () => void;
37
37
  readonly onViewCurrent?: () => void;
@@ -61,20 +61,22 @@ export function UpdateCheckerAction({
61
61
  {labels.viewCurrent}
62
62
  </Button>
63
63
  )}
64
- <Button
65
- variant="field"
66
- onClick={onCheck}
67
- disabled={busy}
68
- data-testid="updater-check"
69
- data-updater-phase={phase}
70
- >
71
- <span className={`icon-[mdi--refresh] h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
72
- {downloading
73
- ? labels.downloading(Math.round((progress ?? 0) * 100))
74
- : checking
75
- ? labels.checkingBtn
76
- : labels.check}
77
- </Button>
64
+ {onCheck && (
65
+ <Button
66
+ variant="field"
67
+ onClick={onCheck}
68
+ disabled={busy}
69
+ data-testid="updater-check"
70
+ data-updater-phase={phase}
71
+ >
72
+ <span className={`icon-[mdi--refresh] h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
73
+ {downloading
74
+ ? labels.downloading(Math.round((progress ?? 0) * 100))
75
+ : checking
76
+ ? labels.checkingBtn
77
+ : labels.check}
78
+ </Button>
79
+ )}
78
80
  </div>
79
81
  );
80
82
  }