@vetta-org/theme-ui 0.1.0 → 0.1.2

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 (301) hide show
  1. package/package.json +735 -7
  2. package/src/action-approval/AppearanceActionPickerView.tsx +2 -78
  3. package/src/action-approval/AppearanceApprovalDrawerView.tsx +2 -9
  4. package/src/action-approval/BatchTasksApprovalFrameView.tsx +4 -1
  5. package/src/action-approval/GenericActionApprovalView.tsx +2 -9
  6. package/src/action-approval/ManageActionApprovalFrameView.tsx +4 -1
  7. package/src/action-approval/NavigationOpenApprovalView.tsx +2 -9
  8. package/src/action-approval/SchedulerActionApprovalDialogView.tsx +3 -1
  9. package/src/action-approval/SchedulerEditApprovalDrawerView.tsx +3 -10
  10. package/src/action-approval/index.ts +0 -1
  11. package/src/activity/ActivityPanel.tsx +13 -10
  12. package/src/activity/ActivityPanelFrame.test.tsx +32 -0
  13. package/src/activity/ActivityPanelFrame.tsx +3 -2
  14. package/src/activity/BackgroundTasksTabPanelView.tsx +1 -1
  15. package/src/activity/BrowserPanelView.tsx +48 -49
  16. package/src/activity/DebugTabPanelView.tsx +1 -1
  17. package/src/activity/MarkdownPreviewView.tsx +56 -59
  18. package/src/activity/PluginTabPickerView.tsx +5 -3
  19. package/src/activity/PortsTabPanelView.tsx +911 -0
  20. package/src/activity/ToolCallsSubTabView.tsx +1 -1
  21. package/src/activity/WorkflowTabPanelView.tsx +1 -1
  22. package/src/activity/index.ts +9 -0
  23. package/src/app/AppBackground.tsx +1 -1
  24. package/src/app/AppBootLoadingView.tsx +4 -2
  25. package/src/app-shell/DefaultWindowControls.tsx +1 -1
  26. package/src/app-shell/PageHeaderActionGroup.tsx +1 -1
  27. package/src/app-shell/PageHeaderContent.tsx +36 -7
  28. package/src/app-shell/PageHeaderFrame.tsx +15 -3
  29. package/src/app-shell/PageHeaderSidebarTrigger.tsx +1 -1
  30. package/src/app-shell/PageHeaderTitle.tsx +1 -1
  31. package/src/app-shell/WindowControlButton.tsx +1 -1
  32. package/src/app-shell/header-crowding.test.ts +62 -0
  33. package/src/app-shell/header-crowding.tsx +137 -0
  34. package/src/appearance/BackgroundImageFrame.tsx +1 -1
  35. package/src/appearance/CenterSliceImageFrame.tsx +1 -1
  36. package/src/appearance/CornerImageFrame.tsx +1 -1
  37. package/src/appearance/HorizontalSliceImageFrame.tsx +1 -1
  38. package/src/appearance/NineSliceImageFrame.tsx +1 -1
  39. package/src/appearance/ThemeSurface.tsx +1 -1
  40. package/src/batch-tasks/BatchProjectFoldersFieldView.tsx +2 -1
  41. package/src/batch-tasks/BatchTaskProjectActionsView.test.tsx +97 -0
  42. package/src/batch-tasks/BatchTaskProjectActionsView.tsx +45 -35
  43. package/src/batch-tasks/batchTaskUi.tsx +0 -29
  44. package/src/bottom-panel/BottomPanelView.test.tsx +43 -0
  45. package/src/bottom-panel/BottomPanelView.tsx +222 -0
  46. package/src/bottom-panel/index.ts +26 -0
  47. package/src/chat/AgentAvatarView.tsx +1 -1
  48. package/src/chat/AnnotationViews.tsx +107 -0
  49. package/src/chat/AskUserQuestionView.tsx +18 -11
  50. package/src/chat/AssistantMessageView.tsx +48 -13
  51. package/src/chat/AtPanelView.test.tsx +61 -0
  52. package/src/chat/AtPanelView.tsx +63 -38
  53. package/src/chat/BashTerminalCard.tsx +1 -2
  54. package/src/chat/ChatHeaderActionsView.tsx +74 -18
  55. package/src/chat/CompactionStepView.test.tsx +34 -0
  56. package/src/chat/CompactionStepView.tsx +85 -0
  57. package/src/chat/ExecutionModeSelectorView.tsx +20 -5
  58. package/src/chat/HeaderActionBarView.tsx +731 -0
  59. package/src/chat/HeaderActionOverflowMenu.tsx +137 -0
  60. package/src/chat/InlineModelPicker.test.tsx +81 -0
  61. package/src/chat/InlineModelPicker.tsx +201 -0
  62. package/src/chat/InlineTokenChip.tsx +2 -68
  63. package/src/chat/InputBarBackground.tsx +1 -1
  64. package/src/chat/InputBarPlaceholder.tsx +26 -3
  65. package/src/chat/LiveThinkingView.tsx +51 -37
  66. package/src/chat/MessageBoundaryViews.tsx +21 -0
  67. package/src/chat/MessageFeedContext.tsx +13 -5
  68. package/src/chat/MessageFeedLayoutView.tsx +28 -3
  69. package/src/chat/MessageFeedView.test.tsx +81 -0
  70. package/src/chat/MessageFeedView.tsx +72 -152
  71. package/src/chat/MessageInputView.tsx +1 -1
  72. package/src/chat/MessageLayoutView.tsx +1 -1
  73. package/src/chat/MessageSelectionContextMenuView.tsx +4 -1
  74. package/src/chat/MessageTimelineView.tsx +1 -1
  75. package/src/chat/MessageView.tsx +1 -1
  76. package/src/chat/MessageVisualView.tsx +1 -1
  77. package/src/chat/ModelConfiguration.tsx +283 -0
  78. package/src/chat/ModelSelectorTrigger.tsx +63 -0
  79. package/src/chat/ModelSelectorView.tsx +1037 -223
  80. package/src/chat/NewSession.ts +1 -37
  81. package/src/chat/NewSessionPicker.tsx +3 -2
  82. package/src/chat/ProjectSelectorView.tsx +3 -2
  83. package/src/chat/ReasoningStepSlider.tsx +61 -0
  84. package/src/chat/RemoteSessionBadgeView.tsx +24 -0
  85. package/src/chat/SkillPromptAreaView.tsx +5 -19
  86. package/src/chat/TeamMemberReplyCardView.test.tsx +33 -0
  87. package/src/chat/TeamMemberReplyCardView.tsx +133 -0
  88. package/src/chat/TextBlockView.tsx +7 -770
  89. package/src/chat/TodoProgress.tsx +25 -53
  90. package/src/chat/TodoStatusBarView.tsx +14 -5
  91. package/src/chat/UserMessageView.tsx +113 -33
  92. package/src/chat/header-action-narrow.test.ts +21 -0
  93. package/src/chat/header-action-narrow.ts +38 -0
  94. package/src/chat/index.ts +32 -27
  95. package/src/chat/markdown-link.ts +7 -279
  96. package/src/chat/send-button.css +4 -22
  97. package/src/chat/streaming-reveal.test.ts +218 -0
  98. package/src/chat/streaming-reveal.ts +13 -0
  99. package/src/file-explorer/ConfirmDeleteDialogView.tsx +2 -1
  100. package/src/file-explorer/FileContextMenuView.tsx +44 -11
  101. package/src/file-explorer/FileExplorerSettingsView.tsx +97 -0
  102. package/src/file-explorer/FileTreeCreateRow.tsx +1 -1
  103. package/src/file-explorer/FileTreeNodeView.tsx +59 -18
  104. package/src/file-explorer/FileTreeView.tsx +236 -129
  105. package/src/file-explorer/file-tree-dom.ts +23 -0
  106. package/src/file-explorer/file-tree-rows.test.ts +74 -0
  107. package/src/file-explorer/file-tree-rows.ts +168 -0
  108. package/src/file-explorer/index.ts +17 -0
  109. package/src/file-explorer/types.ts +3 -0
  110. package/src/file-explorer/useFileTreeMarqueeSelection.ts +24 -16
  111. package/src/file-preview/FilePreviewDialogView.tsx +2 -2
  112. package/src/file-preview/FilePreviewView.tsx +12 -2
  113. package/src/file-preview/TextFileEditorView.tsx +2 -1
  114. package/src/index.ts +1 -0
  115. package/src/knowledge/KnowledgeHowItWorksDialogView.tsx +1 -1
  116. package/src/layout/AppFrame.tsx +3 -2
  117. package/src/layout/MainContentFrame.tsx +7 -2
  118. package/src/layout/ResizeHandle.tsx +68 -17
  119. package/src/layout/SidebarDock.tsx +75 -19
  120. package/src/layout/SidebarOverlay.tsx +1 -1
  121. package/src/layout/index.ts +1 -1
  122. package/src/layout/resize-handle-axis.test.ts +51 -0
  123. package/src/live-indicators.test.ts +43 -0
  124. package/src/markdown/CodeBlock.tsx +123 -0
  125. package/src/markdown/InlineTokenChip.tsx +68 -0
  126. package/src/markdown/MarkdownContent.tsx +411 -0
  127. package/src/markdown/MarkdownImage.tsx +51 -0
  128. package/src/markdown/MathFormula.tsx +46 -0
  129. package/src/markdown/MermaidBlock.tsx +43 -0
  130. package/src/markdown/RichCodeBlock.tsx +127 -0
  131. package/src/markdown/SvgPreview.tsx +45 -0
  132. package/src/markdown/WebsiteIcon.tsx +94 -0
  133. package/src/markdown/builtin-renderers.tsx +43 -0
  134. package/src/markdown/definition.tsx +49 -0
  135. package/src/markdown/host.tsx +18 -0
  136. package/src/markdown/index.ts +11 -0
  137. package/src/markdown/inline-tokens.ts +187 -0
  138. package/src/markdown/markdown-link.ts +279 -0
  139. package/src/markdown/math-client.ts +116 -0
  140. package/src/markdown/math-render.ts +23 -0
  141. package/src/markdown/math-syntax.ts +80 -0
  142. package/src/markdown/math.worker.ts +16 -0
  143. package/src/markdown/nodes.ts +15 -0
  144. package/src/markdown/preview-policy.ts +43 -0
  145. package/src/markdown/rich-labels.ts +49 -0
  146. package/src/markdown/rich-syntax.ts +93 -0
  147. package/src/markdown/stable-blocks.test.ts +90 -0
  148. package/src/markdown/stable-blocks.ts +124 -0
  149. package/src/markdown/streaming-reveal.ts +297 -0
  150. package/src/markdown/streaming.test.ts +57 -0
  151. package/src/markdown/streaming.ts +211 -0
  152. package/src/markdown/use-render-snapshot.ts +24 -0
  153. package/src/markdown/use-rich-visibility.ts +24 -0
  154. package/src/overlays/CommandMenuRow.tsx +38 -9
  155. package/src/overlays/CommandMenuView.tsx +77 -117
  156. package/src/overlays/ConfirmDialogView.tsx +25 -20
  157. package/src/overlays/ReleaseNoteMarkdown.tsx +29 -0
  158. package/src/overlays/SplashOptionRow.tsx +46 -0
  159. package/src/overlays/SplashPanel.tsx +85 -0
  160. package/src/overlays/SplashParts.tsx +213 -0
  161. package/src/overlays/UpdateCheckerView.tsx +34 -18
  162. package/src/overlays/UpdateRestartDialogView.tsx +139 -54
  163. package/src/overlays/command-menu-types.ts +2 -0
  164. package/src/overlays/command-menu.css +1 -20
  165. package/src/overlays/index.ts +14 -1
  166. package/src/plugin-ui/index.ts +8 -0
  167. package/src/project/ConversationTagDotsView.tsx +1 -1
  168. package/src/project/ConversationTagEditorDialogView.tsx +4 -1
  169. package/src/project/DefaultConversationSectionView.tsx +4 -4
  170. package/src/project/DefaultSessionListView.tsx +5 -31
  171. package/src/project/DefaultSessionRowView.tsx +106 -55
  172. package/src/project/ManageSessionsSplashView.tsx +439 -0
  173. package/src/project/NewProjectDialogView.tsx +3 -10
  174. package/src/project/ProjectContextMenuView.tsx +30 -139
  175. package/src/project/ProjectDetailPageView.test.tsx +140 -0
  176. package/src/project/ProjectDetailPageView.tsx +372 -165
  177. package/src/project/ProjectGroupView.tsx +1 -1
  178. package/src/project/ProjectRowView.tsx +29 -12
  179. package/src/project/ProjectSessionsView.tsx +25 -47
  180. package/src/project/QuickScrollOverlay.tsx +1 -1
  181. package/src/project/SessionContextMenuView.tsx +15 -7
  182. package/src/project/SessionRowMoreButton.tsx +50 -0
  183. package/src/project/SessionRowView.tsx +106 -63
  184. package/src/project/SessionTitleMarquee.tsx +54 -0
  185. package/src/project/SidebarProjectDisclosure.tsx +60 -0
  186. package/src/project/SidebarProjectsSectionView.tsx +6 -1
  187. package/src/project/index.ts +12 -0
  188. package/src/project/session-row-transition.ts +9 -0
  189. package/src/project/types.ts +4 -2
  190. package/src/project/useActiveSessionAutoScroll.ts +10 -4
  191. package/src/registry.ts +0 -2
  192. package/src/scheduler/AutomationDetailPaneView.tsx +68 -0
  193. package/src/scheduler/AutomationPageView.tsx +118 -121
  194. package/src/scheduler/ExecutionHistoryView.tsx +7 -5
  195. package/src/scheduler/TaskListView.tsx +52 -201
  196. package/src/scheduler/index.ts +7 -12
  197. package/src/settings/AchievementSettingsView.tsx +0 -1
  198. package/src/settings/AppshotSettingsView.tsx +0 -1
  199. package/src/settings/BuiltinMcpSectionView.tsx +1 -1
  200. package/src/settings/EnvironmentGitRowView.tsx +156 -0
  201. package/src/settings/EnvironmentSettingsView.tsx +25 -3
  202. package/src/settings/GeneralSettingsView.tsx +17 -20
  203. package/src/settings/ImChannelGuideDialogView.tsx +2 -2
  204. package/src/settings/ImFeishuDialogView.tsx +1 -1
  205. package/src/settings/ImLegacyImportBannerView.tsx +1 -1
  206. package/src/settings/ImLogDrawerView.tsx +2 -1
  207. package/src/settings/JsonConfigInputView.tsx +171 -0
  208. package/src/settings/ModelsFetchedModelsDrawerView.tsx +292 -0
  209. package/src/settings/ModelsProvidersSectionView.tsx +26 -23
  210. package/src/settings/MotionSelect.tsx +9 -7
  211. package/src/settings/NotificationSettingsView.tsx +79 -0
  212. package/src/settings/PermissionsSettingsView.tsx +3 -7
  213. package/src/settings/PresetProviderModelsListView.tsx +141 -24
  214. package/src/settings/PresetProviderRowView.tsx +205 -182
  215. package/src/settings/ProxySettingsSectionView.tsx +182 -0
  216. package/src/settings/QrBindDialogView.tsx +1 -1
  217. package/src/settings/QuickPanelSettingsSectionView.tsx +0 -2
  218. package/src/settings/RemoteMcpSectionView.tsx +1 -1
  219. package/src/settings/SettingChrome.tsx +2 -2
  220. package/src/settings/SettingsAiAssistButtonView.tsx +9 -119
  221. package/src/settings/SettingsFormFields.tsx +4 -7
  222. package/src/settings/SettingsSidebarView.tsx +64 -3
  223. package/src/settings/ShortcutRecorderView.test.tsx +108 -0
  224. package/src/settings/ShortcutRecorderView.tsx +15 -9
  225. package/src/settings/ShortcutsSettingsView.tsx +1 -1
  226. package/src/settings/SpaceEditorDialogView.tsx +120 -0
  227. package/src/settings/SpacesSettingsView.tsx +105 -0
  228. package/src/settings/WebhookEndpointListView.tsx +4 -5
  229. package/src/settings/index.ts +41 -29
  230. package/src/shared/ActivityStatusDot.tsx +69 -0
  231. package/src/shared/AvatarStackView.tsx +13 -13
  232. package/src/shared/BotAvatar.tsx +11 -9
  233. package/src/shared/CodeBlockCopyButton.tsx +1 -1
  234. package/src/shared/ContextMenuView.tsx +4 -11
  235. package/src/shared/MarkdownTable.tsx +2 -2
  236. package/src/shared/SyntaxHighlightedCode.tsx +0 -0
  237. package/src/shared/TabBar.outline.test.tsx +59 -0
  238. package/src/shared/TabBar.tsx +22 -17
  239. package/src/shared/VettaKbd.test.tsx +52 -0
  240. package/src/shared/VettaKbd.tsx +81 -0
  241. package/src/shared/connected-tab-outline.test.ts +2 -2
  242. package/src/shared/connected-tab-outline.ts +2 -1
  243. package/src/shared/index.ts +6 -0
  244. package/src/shared/kbd-keys.test.ts +61 -0
  245. package/src/shared/kbd-keys.ts +253 -0
  246. package/src/shared/provider-icon/icons.ts +4 -2
  247. package/src/shared/provider-icon/index.tsx +1 -1
  248. package/src/shared/provider-icon/magpie.svg +1 -0
  249. package/src/sidebar/AddProjectMenuTriggerView.tsx +25 -15
  250. package/src/sidebar/DefaultSidebar.tsx +3 -1
  251. package/src/sidebar/MessageCenterDialogView.tsx +3 -2
  252. package/src/sidebar/MessageCenterEmptyState.tsx +1 -1
  253. package/src/sidebar/MessageCenterTabs.tsx +1 -1
  254. package/src/sidebar/MessageCenterToolbarButton.tsx +1 -1
  255. package/src/sidebar/MessageCenterTriggerView.tsx +2 -2
  256. package/src/sidebar/ProjectsPanelEmptyState.tsx +26 -7
  257. package/src/sidebar/SessionStatusIcon.tsx +16 -1
  258. package/src/sidebar/SettingsMenuThemeSection.tsx +1 -1
  259. package/src/sidebar/SettingsMenuTriggerView.test.tsx +42 -0
  260. package/src/sidebar/SettingsMenuTriggerView.tsx +28 -50
  261. package/src/sidebar/ShowMoreSessionsButton.tsx +1 -1
  262. package/src/sidebar/SidebarFilterSelectView.tsx +8 -16
  263. package/src/sidebar/SidebarNavBadgeView.tsx +1 -1
  264. package/src/sidebar/SidebarNavIcon.tsx +1 -1
  265. package/src/sidebar/SidebarNavItemButton.tsx +1 -1
  266. package/src/sidebar/SidebarNavMorePanel.tsx +19 -7
  267. package/src/sidebar/SidebarNavigation.tsx +24 -15
  268. package/src/sidebar/SidebarPanel.tsx +11 -2
  269. package/src/sidebar/SidebarSectionTriggerLabel.tsx +20 -0
  270. package/src/sidebar/SidebarTopBar.tsx +10 -7
  271. package/src/sidebar/WaitingPulseBadge.tsx +19 -0
  272. package/src/sidebar/index.ts +1 -16
  273. package/src/skills/index.ts +0 -19
  274. package/src/skills/skill-icon.tsx +4 -8
  275. package/src/styles.css +24 -6
  276. package/src/chat/DefaultSceneCarousel.tsx +0 -113
  277. package/src/chat/SceneCard.tsx +0 -138
  278. package/src/scheduler/HistoryDrawerView.tsx +0 -149
  279. package/src/scheduler/TaskFormDialogView.tsx +0 -60
  280. package/src/settings/SubscriptionActionsView.tsx +0 -63
  281. package/src/settings/SubscriptionCardsView.tsx +0 -212
  282. package/src/settings/TeamDetailView.tsx +0 -148
  283. package/src/settings/TeamDialogsView.tsx +0 -151
  284. package/src/settings/TeamListView.tsx +0 -57
  285. package/src/settings/TeamSettingsView.tsx +0 -51
  286. package/src/settings/TokenActivityChartView.tsx +0 -286
  287. package/src/settings/UsageStatsView.tsx +0 -101
  288. package/src/settings/shouldCloseEmptyApiKeyEditor.test.ts +0 -135
  289. package/src/settings/shouldCloseEmptyApiKeyEditor.ts +0 -40
  290. package/src/settings/token-activity.test.ts +0 -195
  291. package/src/settings/token-activity.ts +0 -320
  292. package/src/sidebar/AddProjectMenuItem.tsx +0 -21
  293. package/src/sidebar/AddProjectMenuPopoverView.tsx +0 -52
  294. package/src/sidebar/NotificationMessageListView.tsx +0 -136
  295. package/src/sidebar/SettingsMenuAccountSection.tsx +0 -32
  296. package/src/sidebar/SettingsMenuQuotaSection.tsx +0 -45
  297. package/src/skills/SceneCardView.tsx +0 -194
  298. package/src/skills/SkillCardView.tsx +0 -186
  299. package/src/skills/SkillDetailDialogView.tsx +0 -138
  300. package/src/skills/SkillTagGroupView.tsx +0 -56
  301. package/src/skills/SkillToggleSwitch.tsx +0 -31
@@ -0,0 +1,411 @@
1
+ import { MarkdownHostProvider } from "./host";
2
+ import type { MarkdownHost } from "./host";
3
+ import { MarkdownImage } from "./MarkdownImage";
4
+ import { createContext, memo, useContext, useMemo, useRef } from "react";
5
+ import type { JSX } from "react";
6
+ import ReactMarkdown from "react-markdown";
7
+ import type { Components, Options } from "react-markdown";
8
+ import remarkGfm from "remark-gfm";
9
+ import { BuiltinCodeBlock, Formula } from "./builtin-renderers";
10
+ import { richRemarkPlugins } from "./rich-syntax";
11
+ import { SvgPreview } from "./SvgPreview";
12
+ import { defaultRichContentLabels } from "./rich-labels";
13
+ import type { MarkdownLabels } from "./rich-labels";
14
+ export type { MarkdownLabels } from "./rich-labels";
15
+ import {
16
+ MarkdownTable,
17
+ MarkdownTableBody,
18
+ MarkdownTableCell,
19
+ MarkdownTableHead,
20
+ MarkdownTableHeaderCell,
21
+ MarkdownTableRow,
22
+ } from "../shared/MarkdownTable";
23
+ import { SkillTypeIcon } from "../skills/skill-icon";
24
+ import { InlineTokenChip } from "./InlineTokenChip";
25
+ import { WebsiteIcon } from "./WebsiteIcon";
26
+ import { useRenderSnapshot } from "./use-render-snapshot";
27
+ import { chatUrlTransform, classifyMarkdownLink, normalizeLocalFileLinksInMarkdown } from "./markdown-link";
28
+ import { useStreamingDisplayText, rehypeStreamingChunks } from "./streaming";
29
+ import {
30
+ INLINE_TOKEN_TAG,
31
+ rehypeInlineTokens,
32
+ remarkInlineTokenAnnotations,
33
+ projectAnnotationsToNormalizedMarkdown,
34
+ } from "./inline-tokens";
35
+ import type { InlineTokenSupport } from "./inline-tokens";
36
+ import type { HastElement } from "./nodes";
37
+ import { useMarkdownDefinition } from "./definition";
38
+ import type { MarkdownDefinition } from "./definition";
39
+ import { splitStableMarkdownBlocks } from "./stable-blocks";
40
+
41
+ /** 文件 / 链接 badge 的公共样式:半透明主题色底 + 主题色描边与文字。 */
42
+ const LINK_BADGE_CLASS =
43
+ "inline-flex max-w-full items-center gap-1 rounded-md border border-primary/25 bg-primary/10 px-1.5 py-px align-middle text-[13px] font-medium text-primary no-underline transition-colors hover:bg-primary/20";
44
+
45
+ const remarkPlugins = [remarkGfm, ...richRemarkPlugins];
46
+
47
+ const MarkdownCodeLiveContext = createContext(false);
48
+
49
+ function cn(...parts: Array<string | false | null | undefined>): string {
50
+ return parts.filter(Boolean).join(" ");
51
+ }
52
+
53
+ export interface MarkdownContentProps {
54
+ host?: MarkdownHost;
55
+ definition?: MarkdownDefinition;
56
+ text: string;
57
+ isStreamingTail?: boolean;
58
+ className?: string;
59
+ theme: "light" | "dark";
60
+ labels: MarkdownLabels;
61
+ getFileIconClass: (fileName: string) => string;
62
+ onOpenFile: (path: string) => void;
63
+ onOpenUrl: (url: string) => void;
64
+ /** 传入即启用行内 token 渲染;仅用户消息需要,助手 markdown 不受影响。 */
65
+ inlineTokens?: InlineTokenSupport;
66
+ }
67
+
68
+ /** 绝对路径形式的链接文字(POSIX、Windows 盘符、UNC、~/)。相对路径保留原样,用于同名文件的区分。 */
69
+ const ABSOLUTE_PATH_LABEL = /^(?:\/|[A-Za-z]:[\\/]|\\\\|~\/)/;
70
+
71
+ function basename(path: string): string {
72
+ const normalized = path.replace(/[\\/]+$/, "");
73
+ const idx = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\"));
74
+ return idx === -1 ? normalized : normalized.slice(idx + 1);
75
+ }
76
+
77
+ interface MarkdownDocumentProps {
78
+ animateChunks: boolean;
79
+ components: Components;
80
+ definition: MarkdownDefinition;
81
+ inlineTokens?: InlineTokenSupport;
82
+ live: boolean;
83
+ text: string;
84
+ }
85
+
86
+ /**
87
+ * 一块已经冻结或仍在增长的 markdown。独立 memo:流式时只有 tail 的 `text` 变,
88
+ * 已提交块不会跟着整篇重跑 remark;流式结束后分块结构保持不变,已提交块不会重挂。
89
+ */
90
+ const MarkdownDocument = memo(function MarkdownDocument({
91
+ animateChunks,
92
+ components,
93
+ definition,
94
+ inlineTokens,
95
+ live,
96
+ text,
97
+ }: MarkdownDocumentProps): JSX.Element {
98
+ const hasStructuredAnnotations = inlineTokens?.annotations !== undefined;
99
+ const rehypePlugins = useMemo(() => {
100
+ const plugins: NonNullable<Options["rehypePlugins"]> = [...(definition.rehypePlugins ?? [])];
101
+ if (animateChunks) plugins.push(rehypeStreamingChunks);
102
+ if (inlineTokens && !hasStructuredAnnotations) plugins.push(() => rehypeInlineTokens(inlineTokens.parse));
103
+ return plugins.length > 0 ? plugins : undefined;
104
+ }, [animateChunks, hasStructuredAnnotations, inlineTokens, definition]);
105
+ const markdownSource = useMemo(() => normalizeLocalFileLinksInMarkdown(text), [text]);
106
+ const normalizedAnnotations = useMemo(
107
+ () =>
108
+ inlineTokens?.annotations
109
+ ? projectAnnotationsToNormalizedMarkdown(text, markdownSource, inlineTokens.annotations)
110
+ : undefined,
111
+ [text, inlineTokens?.annotations, markdownSource],
112
+ );
113
+ const activeRemarkPlugins = useMemo(
114
+ () =>
115
+ normalizedAnnotations?.length
116
+ ? [
117
+ ...remarkPlugins,
118
+ ...(definition.remarkPlugins ?? []),
119
+ () => remarkInlineTokenAnnotations(normalizedAnnotations),
120
+ ]
121
+ : [...remarkPlugins, ...(definition.remarkPlugins ?? [])],
122
+ [normalizedAnnotations, definition],
123
+ );
124
+ const resolvedComponents = useMemo(
125
+ () => ({ ...components, ...definition.components, ...definition.elements }),
126
+ [components, definition],
127
+ );
128
+ return (
129
+ <MarkdownCodeLiveContext.Provider value={live}>
130
+ <ReactMarkdown
131
+ remarkPlugins={activeRemarkPlugins}
132
+ rehypePlugins={rehypePlugins}
133
+ components={resolvedComponents}
134
+ urlTransform={chatUrlTransform}
135
+ >
136
+ {markdownSource}
137
+ </ReactMarkdown>
138
+ </MarkdownCodeLiveContext.Provider>
139
+ );
140
+ });
141
+
142
+ /**
143
+ * Memo'd markdown renderer for chat text blocks. Host injects file/url handlers and theme.
144
+ *
145
+ * `components` 映射的函数引用必须在 streaming 期间保持稳定:React 把 components.p 等
146
+ * 当成元素类型;引用一变就会整树 remount,`.streaming-chunk` 的 CSS 入场动画对已有
147
+ * 文本整段重播,表现为 text block 高频闪烁。labels / 回调通过 ref 读取,不进 deps。
148
+ */
149
+ export const MarkdownContent = memo(function MarkdownContent({
150
+ text,
151
+ isStreamingTail = false,
152
+ className,
153
+ theme,
154
+ labels,
155
+ getFileIconClass,
156
+ onOpenFile,
157
+ onOpenUrl,
158
+ inlineTokens,
159
+ definition: definitionOverride,
160
+ host,
161
+ }: MarkdownContentProps): JSX.Element {
162
+ const inheritedDefinition = useMarkdownDefinition();
163
+ const definition = definitionOverride ?? inheritedDefinition;
164
+ const definitionRef = useRef(definition);
165
+ definitionRef.current = definition;
166
+ const { displayText, animateChunks } = useStreamingDisplayText(text, isStreamingTail);
167
+ const chunkedRef = useRef(false);
168
+ if (animateChunks) chunkedRef.current = true;
169
+ const frozenBlocksRef = useRef(false);
170
+ if (isStreamingTail && !inlineTokens) frozenBlocksRef.current = true;
171
+ const splitDocuments = frozenBlocksRef.current && !inlineTokens;
172
+ const candidateSplit = useMemo(
173
+ () => splitDocuments ? splitStableMarkdownBlocks(displayText) : null,
174
+ [displayText, splitDocuments],
175
+ );
176
+ // Keep small replies responsive; bound full parsing of long tails without splitting
177
+ // paragraphs/lists/reference definitions into semantically different documents.
178
+ const tailLength = (candidateSplit?.tail ?? displayText).length;
179
+ const renderInterval = tailLength >= 50000 ? 400 : tailLength >= 12000 ? 200 : 0;
180
+ const previousText = useRef(displayText);
181
+ const replaced = !displayText.startsWith(previousText.current);
182
+ previousText.current = displayText;
183
+ const renderText = useRenderSnapshot(displayText, true, isStreamingTail && renderInterval > 0 && !replaced, renderInterval);
184
+
185
+ const labelsRef = useRef(labels);
186
+ const getFileIconClassRef = useRef(getFileIconClass);
187
+ const onOpenFileRef = useRef(onOpenFile);
188
+ const onOpenUrlRef = useRef(onOpenUrl);
189
+ const inlineTokensRef = useRef(inlineTokens);
190
+ labelsRef.current = labels;
191
+ getFileIconClassRef.current = getFileIconClass;
192
+ onOpenFileRef.current = onOpenFile;
193
+ onOpenUrlRef.current = onOpenUrl;
194
+ inlineTokensRef.current = inlineTokens;
195
+
196
+ const components = useMemo<Components>(
197
+ () => ({
198
+ h1: ({ children }) => (
199
+ <h1 className="mb-3 mt-4 text-[20px] font-bold leading-tight text-foreground">{children}</h1>
200
+ ),
201
+ h2: ({ children }) => (
202
+ <h2 className="mb-2 mt-3.5 text-[17px] font-bold leading-tight text-foreground">{children}</h2>
203
+ ),
204
+ h3: ({ children }) => (
205
+ <h3 className="mb-2 mt-3 text-[15px] font-semibold leading-tight text-foreground">{children}</h3>
206
+ ),
207
+ h4: ({ children }) => <h4 className="mb-1.5 mt-2.5 text-[14px] font-semibold text-foreground">{children}</h4>,
208
+ p: ({ children }) => <p className="my-1.5 text-[14px] leading-[1.6] text-foreground">{children}</p>,
209
+ ul: ({ children }) => (
210
+ <ul className="md-bullet-list my-1.5 text-[14px] leading-[1.6] text-foreground">{children}</ul>
211
+ ),
212
+ ol: ({ children }) => (
213
+ <ol className="my-1.5 ml-4 list-decimal space-y-0.5 text-[14px] leading-[1.6] text-foreground marker:text-primary">
214
+ {children}
215
+ </ol>
216
+ ),
217
+ li: ({ children }) => <li>{children}</li>,
218
+ img: ({ src, alt, title }) => <MarkdownImage src={src} alt={alt} title={title} labels={labelsRef.current} />,
219
+ code: function MarkdownCode({ className: codeClassName, children }) {
220
+ const live = useContext(MarkdownCodeLiveContext);
221
+ const raw = String(children);
222
+ if (codeClassName?.includes("math-inline") || codeClassName?.includes("math-display")) {
223
+ return <Formula source={raw.replace(/\n$/, "")} display={codeClassName.includes("math-display")} live={live} labels={labelsRef.current} />;
224
+ }
225
+ const isBlock = (codeClassName?.startsWith("language-") ?? false) || raw.includes("\n");
226
+ if (isBlock) {
227
+ const lang = codeClassName?.replace("language-", "") ?? "";
228
+ const code = raw.replace(/\n$/, "");
229
+ const CodeBlock = definitionRef.current.codeBlock ?? BuiltinCodeBlock;
230
+ return <CodeBlock lang={lang} code={code} theme={theme} labels={labelsRef.current} live={live} />;
231
+ }
232
+ return <code className="rounded bg-muted px-1 py-0.5 text-[13px] text-foreground">{children}</code>;
233
+ },
234
+ pre: ({ children }) => <>{children}</>,
235
+ blockquote: ({ children }) => (
236
+ <blockquote className="my-2 border-l-2 border-primary/10 pl-3 text-[14px] italic text-muted-foreground">
237
+ {children}
238
+ </blockquote>
239
+ ),
240
+ table: ({ children }) => <MarkdownTable>{children}</MarkdownTable>,
241
+ thead: ({ children }) => <MarkdownTableHead>{children}</MarkdownTableHead>,
242
+ tbody: ({ children }) => <MarkdownTableBody>{children}</MarkdownTableBody>,
243
+ tr: ({ children }) => <MarkdownTableRow>{children}</MarkdownTableRow>,
244
+ // style 透传:remark-gfm 把 GFM 的列对齐(`|---:|`)写在这里。
245
+ th: ({ children, style }) => <MarkdownTableHeaderCell style={style}>{children}</MarkdownTableHeaderCell>,
246
+ td: ({ children, style }) => <MarkdownTableCell style={style}>{children}</MarkdownTableCell>,
247
+ hr: () => <hr className="my-3 border-border" />,
248
+ a: ({ href, children }) => {
249
+ const kind = classifyMarkdownLink(href);
250
+ if (kind.type === "file") {
251
+ const fileName = basename(kind.path);
252
+ // 模型偶尔把整条绝对路径写成 label,徽标里只留文件名,完整路径仍在 title 里。
253
+ const label =
254
+ typeof children === "string" && ABSOLUTE_PATH_LABEL.test(children.trim()) ? basename(children.trim()) : children;
255
+ return (
256
+ <button
257
+ type="button"
258
+ title={kind.path}
259
+ className={cn(LINK_BADGE_CLASS, "cursor-pointer")}
260
+ onClick={() => onOpenFileRef.current(kind.path)}
261
+ >
262
+ <span className={cn(getFileIconClassRef.current(fileName), "h-3.5 w-3.5 shrink-0")} />
263
+ <span className="truncate">{label}</span>
264
+ </button>
265
+ );
266
+ }
267
+ if (kind.type === "url") {
268
+ return (
269
+ <a
270
+ href={kind.url}
271
+ title={kind.url}
272
+ className={LINK_BADGE_CLASS}
273
+ onClick={(e) => {
274
+ e.preventDefault();
275
+ onOpenUrlRef.current(kind.url);
276
+ }}
277
+ >
278
+ <WebsiteIcon href={kind.url} />
279
+ <span className="truncate">{children}</span>
280
+ </a>
281
+ );
282
+ }
283
+ // mailto / fragment / unknown: never target=_blank — that opens the OS browser
284
+ // for misclassified local paths. Keep visible but non-navigating.
285
+ return (
286
+ <span className="text-chart-2 underline decoration-chart-2/30" title={kind.href || undefined}>
287
+ {children}
288
+ </span>
289
+ );
290
+ },
291
+ strong: ({ children }) => <strong className="font-semibold text-foreground">{children}</strong>,
292
+ "vetta-svg": ({ node }: { node?: HastElement }) => {
293
+ const source = node?.properties?.source;
294
+ const rich = labelsRef.current.rich ?? defaultRichContentLabels;
295
+ return typeof source === "string" ? <SvgPreview source={source} label={rich.svg} failed={rich.failed} live /> : null;
296
+ },
297
+ em: ({ children }) => <em className="italic">{children}</em>,
298
+ // 行内 token:与输入框里的胶囊同款(半透明主题色底 + 描边,align-middle 对齐正文)。
299
+ [INLINE_TOKEN_TAG]: ({ node }: { node?: HastElement }) => {
300
+ const properties = node?.properties ?? {};
301
+ const kind = String(properties["data-token-kind"] ?? "");
302
+ const value = String(properties["data-token-value"] ?? "");
303
+ if (!kind || !value) return null;
304
+ if (kind === "image") {
305
+ return (
306
+ <InlineTokenChip
307
+ icon="icon-[solar--gallery-linear]"
308
+ label={inlineTokensRef.current?.getImageLabel(value) ?? basename(value)}
309
+ title={basename(value)}
310
+ />
311
+ );
312
+ }
313
+ if (kind === "skill") {
314
+ const ability = inlineTokensRef.current?.getSkill?.(value);
315
+ return (
316
+ <InlineTokenChip
317
+ iconNode={<SkillTypeIcon icon={ability?.icon} className="h-3 w-3" />}
318
+ label={ability?.label ?? value}
319
+ title={value}
320
+ />
321
+ );
322
+ }
323
+ if (kind === "connector") {
324
+ const connector = inlineTokensRef.current?.getConnector?.(value);
325
+ return (
326
+ <InlineTokenChip
327
+ icon="icon-[solar--plug-circle-linear]"
328
+ iconUrl={connector?.iconUrl}
329
+ label={connector?.label ?? value}
330
+ title={value}
331
+ />
332
+ );
333
+ }
334
+ if (kind === "member") {
335
+ const member = inlineTokensRef.current?.getMember?.(value);
336
+ const handle = String(properties["data-token-handle"] ?? value);
337
+ if (!member) return <>{`@${handle}`}</>;
338
+ return (
339
+ <InlineTokenChip
340
+ iconNode={
341
+ member.avatar ? (
342
+ <img
343
+ src={member.avatar}
344
+ alt=""
345
+ draggable={false}
346
+ className="h-3 w-3 rounded-full object-cover"
347
+ />
348
+ ) : undefined
349
+ }
350
+ label={`@${member.label || handle}`}
351
+ title={member.meta ? `${member.label || handle} · ${member.meta}` : handle}
352
+ tone="member"
353
+ />
354
+ );
355
+ }
356
+ const isDirectory = properties["data-token-directory"] === "true";
357
+ const fileName = basename(value);
358
+ return (
359
+ <InlineTokenChip
360
+ asButton
361
+ icon={isDirectory ? "icon-[solar--folder-linear]" : getFileIconClassRef.current(fileName)}
362
+ label={fileName}
363
+ title={value}
364
+ onClick={() => onOpenFileRef.current(value)}
365
+ />
366
+ );
367
+ },
368
+ }),
369
+ // theme 进 deps:代码块高亮主题变化时需要换组件树。其余 host 注入值走 ref。
370
+ [theme],
371
+ );
372
+
373
+ // 分段 span 一旦挂上就保留到实例卸载:结束时若把 rehype 插件撤掉,整个尾块会重建 DOM,
374
+ // 表现为回复结尾「卡一下」。「最新短语略暗」只挂在包裹类上,撤掉包裹类就恢复全亮,DOM 不动。
375
+ // 切块一旦启用就保持到实例卸载:流式结束时 `animateChunks` 要等 settle 才关,若此刻把
376
+ // 已冻结块并回单一文档,已上屏的节点会整段重挂并再包成 `.streaming-chunk` 重放淡入。
377
+ // 稳定块只按已闭合的顶层围栏切分,分块与整篇渲染结果一致,因此结束后不需要再合并。
378
+ const split = useMemo(
379
+ () => renderText === displayText ? candidateSplit : splitDocuments ? splitStableMarkdownBlocks(renderText) : null,
380
+ [renderText, displayText, candidateSplit, splitDocuments],
381
+ );
382
+ const committed = split?.committed ?? [];
383
+ const tail = split ? split.tail : renderText;
384
+ const showTail = !split || tail.length > 0 || committed.length === 0;
385
+
386
+ return (
387
+ <MarkdownHostProvider host={host}><div className={cn("markdown-body break-words", animateChunks && "markdown-streaming-tail", className)}>
388
+ {committed.map((block, index) => (
389
+ <MarkdownDocument
390
+ key={`committed-${index}`}
391
+ animateChunks={false}
392
+ components={components}
393
+ definition={definition}
394
+ live={false}
395
+ text={block}
396
+ />
397
+ ))}
398
+ {showTail ? (
399
+ <MarkdownDocument
400
+ key="tail"
401
+ animateChunks={chunkedRef.current}
402
+ components={components}
403
+ definition={definition}
404
+ inlineTokens={inlineTokens}
405
+ live={isStreamingTail}
406
+ text={tail}
407
+ />
408
+ ) : null}
409
+ </div></MarkdownHostProvider>
410
+ );
411
+ });
@@ -0,0 +1,51 @@
1
+ import { Button } from "@vetta-org/ui/button";
2
+ import { memo, useEffect, useRef, useState } from "react";
3
+ import { useMarkdownHost } from "./host";
4
+ import type { MarkdownLabels } from "./rich-labels";
5
+ import { defaultRichContentLabels } from "./rich-labels";
6
+ import { useRichVisibility } from "./use-rich-visibility";
7
+
8
+ export const MarkdownImage = memo(function MarkdownImage({ src = "", alt = "", title, labels }: { src?: string; alt?: string; title?: string; labels: MarkdownLabels }) {
9
+ const host = useMarkdownHost();
10
+ const rich = labels.rich ?? defaultRichContentLabels;
11
+ const { ref, active } = useRichVisibility();
12
+ const [attempt, setAttempt] = useState(0);
13
+ const [result, setResult] = useState<{ source: string; url: string }>();
14
+ const [failed, setFailed] = useState(false);
15
+ const [action, setAction] = useState<"copy" | "save" | "failed" | "copied" | null>(null);
16
+ const generation = useRef(0);
17
+ useEffect(() => () => { generation.current++; }, [src]);
18
+ useEffect(() => {
19
+ if (!active || !src) return;
20
+ let cancelled = false;
21
+ setFailed(false);
22
+ setAction(null);
23
+ const request = host ? host.resolveImage(src) : Promise.resolve(src);
24
+ void request.then((url) => { if (!cancelled) setResult({ source: src, url }); }, () => { if (!cancelled) setFailed(true); });
25
+ return () => { cancelled = true; };
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
+ return <span ref={ref} className="my-2 inline-flex max-w-full flex-col gap-1 align-top">
38
+ {failed ? <span role="status">{rich.imageFailed ?? rich.failed} {alt}</span> : url ? (
39
+ <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)} />
40
+ ) : <span className="min-h-16" aria-busy="true">{alt}</span>}
41
+ <span className="flex flex-wrap items-center gap-1">
42
+ {failed && <Button variant="ghost" size="sm" onClick={(event) => { event.preventDefault(); event.stopPropagation(); setFailed(false); setAttempt((value) => value + 1); }}>{rich.retry ?? "Retry"}</Button>}
43
+ {host && url && !failed && <>
44
+ <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={action === "copy" || action === "save"} onClick={(event) => { event.preventDefault(); event.stopPropagation(); void run("copy"); }}>{action === "copied" ? labels.copied : labels.copy}</Button>
46
+ <Button variant="ghost" size="sm" disabled={action === "copy" || action === "save"} onClick={(event) => { event.preventDefault(); event.stopPropagation(); void run("save"); }}>{rich.save ?? "Save"}</Button>
47
+ </>}
48
+ </span>
49
+ {action === "failed" && <span role="status">{rich.actionFailed ?? rich.failed}</span>}
50
+ </span>;
51
+ });
@@ -0,0 +1,46 @@
1
+ import { Button } from "@vetta-org/ui";
2
+ import type { MarkdownLabels } from "./rich-labels";
3
+ import { memo, useEffect, useRef, useState } from "react";
4
+ import { requestFormula } from "./math-client";
5
+ import { useRichVisibility } from "./use-rich-visibility";
6
+ import { useRenderSnapshot } from "./use-render-snapshot";
7
+ import "katex/dist/katex.min.css";
8
+
9
+ export const MathFormula = memo(function MathFormula({
10
+ source,
11
+ display,
12
+ live = false,
13
+ labels,
14
+ }: {
15
+ source: string;
16
+ display: boolean;
17
+ live?: boolean;
18
+ labels?: MarkdownLabels;
19
+ }) {
20
+ const { ref, active } = useRichVisibility();
21
+ const currentSource = useRef(source);
22
+ currentSource.current = source;
23
+ const [copyState, setCopyState] = useState<"copied" | "failed" | null>(null);
24
+ useEffect(() => setCopyState(null), [source]);
25
+ const snapshot = useRenderSnapshot(source, active, live);
26
+ const [result, setResult] = useState<{ source: string; html: string | null } | null>(null);
27
+ useEffect(() => {
28
+ if (!active) return;
29
+ return requestFormula(snapshot, display, (html) => setResult({ source: snapshot, html }));
30
+ }, [active, display, snapshot]);
31
+ const html = result?.source === snapshot ? result.html : null;
32
+ return (
33
+ <span ref={ref} className={display ? "my-2 block max-w-full overflow-x-auto" : undefined}>
34
+ {html ? (
35
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: only bounded KaTeX output with trust:false, never raw model HTML
36
+ <span dangerouslySetInnerHTML={{ __html: html }} />
37
+ ) : (
38
+ <code>{source}</code>
39
+ )}
40
+ {labels && <Button variant="ghost" size="icon-xs" title={copyState === "copied" ? labels.copied : labels.copy} aria-label={copyState === "copied" ? labels.copied : labels.copy} onClick={() => {
41
+ void navigator.clipboard.writeText(source).then(() => { if (currentSource.current === source) setCopyState("copied"); }, () => { if (currentSource.current === source) setCopyState("failed"); });
42
+ }}><span aria-hidden="true" className={copyState === "copied" ? "icon-[solar--check-circle-linear]" : "icon-[solar--copy-linear]"} /></Button>}
43
+ {copyState === "failed" && <span role="status">{labels?.rich?.actionFailed}</span>}
44
+ </span>
45
+ );
46
+ });
@@ -0,0 +1,43 @@
1
+ import { Button } from "@vetta-org/ui";
2
+ import { memo, useEffect, useState } from "react";
3
+ import { CodeBlock } from "./CodeBlock";
4
+ import type { MarkdownCodeBlockProps } from "./definition";
5
+ import { useMarkdownHost } from "./host";
6
+ import { MarkdownImage } from "./MarkdownImage";
7
+ import { svgImageSource } from "./preview-policy";
8
+ import { defaultRichContentLabels } from "./rich-labels";
9
+ import { useRichVisibility } from "./use-rich-visibility";
10
+
11
+ export const MermaidBlock = memo(function MermaidBlock(props: MarkdownCodeBlockProps) {
12
+ const { code, theme, live } = props;
13
+ const host = useMarkdownHost();
14
+ const labels = props.labels.rich ?? defaultRichContentLabels;
15
+ const { ref, active } = useRichVisibility<HTMLDivElement>();
16
+ const [source, setSource] = useState(false);
17
+ const [attempt, setAttempt] = useState(0);
18
+ const [result, setResult] = useState<{ key: string; svg: string | null }>();
19
+ const key = `${theme}:${code}`;
20
+ const oversized = code.length > 12_000;
21
+ useEffect(() => {
22
+ if (!host || !active || live || source || oversized) return;
23
+ let cancelled = false;
24
+ void host.renderMermaid(code, theme).then(
25
+ (svg) => { if (!cancelled) setResult({ key, svg }); },
26
+ () => { if (!cancelled) setResult({ key, svg: null }); },
27
+ );
28
+ return () => { cancelled = true; };
29
+ }, [host, active, live, source, oversized, key, code, theme, attempt]);
30
+ const current = result?.key === key ? result : undefined;
31
+ const image = current?.svg ? svgImageSource(current.svg) : null;
32
+ return <CodeBlock.Root {...props}><CodeBlock.Copy><CodeBlock.Frame><div ref={ref}>
33
+ <div className="flex items-center gap-2 py-1.5 pr-12 pl-4">
34
+ <span className="text-[12px] text-muted-foreground">Mermaid</span>
35
+ <Button variant="ghost" size="sm" aria-pressed={source} onClick={() => setSource(!source)}>{source ? labels.preview : labels.source}</Button>
36
+ {current?.svg === null && <Button variant="ghost" size="sm" onClick={() => { setResult(undefined); setAttempt((value) => value + 1); }}>{labels.retry ?? "Retry"}</Button>}
37
+ </div>
38
+ {source || live || oversized || !host || current?.svg === null ? <>
39
+ {!source && <p role="status" className="px-4 pb-2 text-[12px] text-muted-foreground">{oversized ? labels.tooLarge : live ? labels.waiting : labels.failed}</p>}
40
+ <CodeBlock.Content />
41
+ </> : image ? <CodeBlock.Body><div className="p-4"><MarkdownImage src={image} alt={labels.diagram ?? "Diagram"} labels={props.labels} /></div></CodeBlock.Body> : <CodeBlock.Body><div className="min-h-24 p-4" role="status">{labels.loading ?? labels.waiting}</div></CodeBlock.Body>}
42
+ </div></CodeBlock.Frame></CodeBlock.Copy></CodeBlock.Root>;
43
+ });
@@ -0,0 +1,127 @@
1
+ import { useMarkdownHost } from "./host";
2
+ import { Button } from "@vetta-org/ui";
3
+ import { memo, useEffect, useMemo, useState } from "react";
4
+ import { CodeBlock } from "./CodeBlock";
5
+ import type { MarkdownCodeBlockProps } from "./definition";
6
+ import { createPreviewDocument, MARKDOWN_PREVIEW_FRAME_NAME, MAX_PREVIEW_LENGTH } from "./preview-policy";
7
+ import { defaultRichContentLabels } from "./rich-labels";
8
+ import { SvgPreview } from "./SvgPreview";
9
+ import { useRichVisibility } from "./use-rich-visibility";
10
+
11
+ /** Product recipe; source/copy retain the existing CodeBlock primitives. */
12
+ export const RichCodeBlock = memo(function RichCodeBlock(props: MarkdownCodeBlockProps) {
13
+ const { code, lang, live = false } = props;
14
+ const host = useMarkdownHost();
15
+ const [failed, setFailed] = useState(false);
16
+ const labels = props.labels.rich ?? defaultRichContentLabels;
17
+ const svg = lang.toLowerCase() === "svg";
18
+ const { ref, active } = useRichVisibility<HTMLDivElement>();
19
+ const [showSource, setShowSource] = useState(false);
20
+ const [runSource, setRunSource] = useState<string | null>(null);
21
+ const [paused, setPaused] = useState(false);
22
+ const oversized = code.length > MAX_PREVIEW_LENGTH;
23
+ const running = runSource === code && active && !live && !showSource;
24
+ useEffect(() => {
25
+ if (!active || live || showSource || (runSource !== null && runSource !== code)) {
26
+ if (runSource !== null) setPaused(true);
27
+ setRunSource(null);
28
+ }
29
+ }, [active, live, showSource, code, runSource]);
30
+ useEffect(() => {
31
+ if (!running) return;
32
+ // Main owns the hard timeout; this timer only updates the local controls.
33
+ const timeout = setTimeout(() => {
34
+ setRunSource(null);
35
+ setPaused(true);
36
+ }, 30_000);
37
+ return () => clearTimeout(timeout);
38
+ }, [running]);
39
+ useEffect(() => {
40
+ if (!running || !host) return;
41
+ let cancelled = false;
42
+ let stop: (() => void) | undefined;
43
+ setFailed(false);
44
+ void host.openHtml(code).then((close) => {
45
+ if (cancelled) close(); else stop = close;
46
+ }, () => { if (!cancelled) { setFailed(true); setRunSource(null); } });
47
+ return () => { cancelled = true; stop?.(); };
48
+ }, [running, code, host]);
49
+ const srcDoc = useMemo(
50
+ () => (active && !svg && !live && !oversized && !showSource ? createPreviewDocument(code) : ""),
51
+ [active, svg, live, oversized, showSource, code],
52
+ );
53
+ return (
54
+ <CodeBlock.Root {...props}>
55
+ <CodeBlock.Copy>
56
+ <CodeBlock.Frame>
57
+ <div ref={ref}>
58
+ <div className="flex flex-wrap items-center gap-2 py-1.5 pr-12 pl-4">
59
+ <span className="text-[12px] text-muted-foreground">{svg ? "SVG" : "HTML"}</span>
60
+ <Button variant="ghost" size="sm" aria-pressed={showSource} onClick={() => setShowSource(!showSource)}>
61
+ {showSource ? labels.preview : labels.source}
62
+ </Button>
63
+ {host && !svg && !showSource && !live && !oversized && (
64
+ <Button
65
+ variant="ghost"
66
+ size="sm"
67
+ onClick={() => {
68
+ setPaused(running);
69
+ setRunSource(running ? null : code);
70
+ }}
71
+ >
72
+ {running ? labels.stop : labels.run}
73
+ </Button>
74
+ )}
75
+ </div>
76
+ {live || oversized || showSource ? (
77
+ <>
78
+ {!showSource && (
79
+ <p className="px-4 pb-2 text-[12px] text-muted-foreground">
80
+ {oversized ? labels.tooLarge : labels.waiting}
81
+ </p>
82
+ )}
83
+ {oversized ? (
84
+ <CodeBlock.Body>
85
+ <pre className="max-h-96 overflow-auto py-3 pr-4 pl-5 text-[13px]">
86
+ <code>{code}</code>
87
+ </pre>
88
+ </CodeBlock.Body>
89
+ ) : (
90
+ <CodeBlock.Content />
91
+ )}
92
+ </>
93
+ ) : svg ? (
94
+ <CodeBlock.Body>
95
+ <div className="p-4">
96
+ <SvgPreview source={code} label={labels.svg} failed={labels.failed} />
97
+ </div>
98
+ </CodeBlock.Body>
99
+ ) : (
100
+ <>
101
+ <p className="px-4 pb-2 text-[12px] text-muted-foreground">
102
+ {failed ? labels.failed : running ? labels.running : paused ? labels.paused : labels.staticHtml}
103
+ </p>
104
+ <CodeBlock.Body>
105
+ {srcDoc ? (
106
+ <iframe
107
+ key="static"
108
+ name={MARKDOWN_PREVIEW_FRAME_NAME}
109
+ title={labels.html}
110
+ srcDoc={srcDoc}
111
+ sandbox=""
112
+ referrerPolicy="no-referrer"
113
+ allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'"
114
+ className="h-80 w-full border-0"
115
+ />
116
+ ) : (
117
+ <div className="h-80" aria-hidden="true" />
118
+ )}
119
+ </CodeBlock.Body>
120
+ </>
121
+ )}
122
+ </div>
123
+ </CodeBlock.Frame>
124
+ </CodeBlock.Copy>
125
+ </CodeBlock.Root>
126
+ );
127
+ });