@vetta-org/theme-ui 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/package.json +740 -20
  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/CodePreview.tsx +15 -1
  17. package/src/activity/DebugTabPanelView.tsx +1 -1
  18. package/src/activity/MarkdownPreviewView.test.tsx +53 -0
  19. package/src/activity/MarkdownPreviewView.tsx +135 -62
  20. package/src/activity/PluginTabPickerView.tsx +5 -3
  21. package/src/activity/PortsTabPanelView.tsx +911 -0
  22. package/src/activity/ToolCallsSubTabView.tsx +1 -1
  23. package/src/activity/WorkflowTabPanelView.tsx +1 -1
  24. package/src/activity/index.ts +9 -0
  25. package/src/app/AppBackground.tsx +1 -1
  26. package/src/app/AppBootLoadingView.tsx +4 -2
  27. package/src/app-shell/DefaultWindowControls.tsx +1 -1
  28. package/src/app-shell/PageHeaderActionGroup.tsx +1 -1
  29. package/src/app-shell/PageHeaderContent.tsx +36 -7
  30. package/src/app-shell/PageHeaderFrame.tsx +15 -3
  31. package/src/app-shell/PageHeaderSidebarTrigger.tsx +1 -1
  32. package/src/app-shell/PageHeaderTitle.tsx +1 -1
  33. package/src/app-shell/WindowControlButton.tsx +1 -1
  34. package/src/app-shell/header-crowding.test.ts +62 -0
  35. package/src/app-shell/header-crowding.tsx +137 -0
  36. package/src/appearance/BackgroundImageFrame.tsx +1 -1
  37. package/src/appearance/CenterSliceImageFrame.tsx +1 -1
  38. package/src/appearance/CornerImageFrame.tsx +1 -1
  39. package/src/appearance/HorizontalSliceImageFrame.tsx +1 -1
  40. package/src/appearance/NineSliceImageFrame.tsx +1 -1
  41. package/src/appearance/ThemeSurface.tsx +1 -1
  42. package/src/batch-tasks/BatchProjectFoldersFieldView.tsx +2 -1
  43. package/src/batch-tasks/BatchTaskProjectActionsView.test.tsx +97 -0
  44. package/src/batch-tasks/BatchTaskProjectActionsView.tsx +45 -35
  45. package/src/batch-tasks/batchTaskUi.tsx +0 -29
  46. package/src/bottom-panel/BottomPanelView.test.tsx +43 -0
  47. package/src/bottom-panel/BottomPanelView.tsx +222 -0
  48. package/src/bottom-panel/index.ts +26 -0
  49. package/src/chat/AgentAvatarView.tsx +1 -1
  50. package/src/chat/AnnotationViews.tsx +107 -0
  51. package/src/chat/AskUserQuestionView.tsx +18 -11
  52. package/src/chat/AssistantMessageView.tsx +48 -13
  53. package/src/chat/AtPanelView.test.tsx +61 -0
  54. package/src/chat/AtPanelView.tsx +63 -38
  55. package/src/chat/BashTerminalCard.tsx +1 -2
  56. package/src/chat/ChatHeaderActionsView.tsx +74 -18
  57. package/src/chat/CompactionStepView.test.tsx +34 -0
  58. package/src/chat/CompactionStepView.tsx +85 -0
  59. package/src/chat/ContextRingView.test.tsx +81 -0
  60. package/src/chat/ContextRingView.tsx +78 -62
  61. package/src/chat/ExecutionModeSelectorView.tsx +20 -5
  62. package/src/chat/HeaderActionBarView.tsx +806 -0
  63. package/src/chat/HeaderActionOverflowMenu.tsx +128 -0
  64. package/src/chat/InlineModelPicker.test.tsx +81 -0
  65. package/src/chat/InlineModelPicker.tsx +201 -0
  66. package/src/chat/InlineTokenChip.tsx +2 -68
  67. package/src/chat/InputBarBackground.tsx +1 -1
  68. package/src/chat/InputBarPlaceholder.tsx +26 -3
  69. package/src/chat/LiveThinkingView.tsx +51 -37
  70. package/src/chat/MessageBoundaryViews.tsx +21 -0
  71. package/src/chat/MessageFeedContext.tsx +13 -5
  72. package/src/chat/MessageFeedLayoutView.tsx +29 -3
  73. package/src/chat/MessageFeedView.test.tsx +81 -0
  74. package/src/chat/MessageFeedView.tsx +72 -152
  75. package/src/chat/MessageInputView.tsx +6 -2
  76. package/src/chat/MessageLayoutView.tsx +1 -1
  77. package/src/chat/MessageSelectionContextMenuView.tsx +4 -1
  78. package/src/chat/MessageTimelineView.tsx +1 -1
  79. package/src/chat/MessageView.tsx +1 -1
  80. package/src/chat/MessageVisualView.tsx +1 -1
  81. package/src/chat/ModelConfiguration.tsx +283 -0
  82. package/src/chat/ModelSelectorTrigger.tsx +63 -0
  83. package/src/chat/ModelSelectorView.tsx +1037 -223
  84. package/src/chat/NewSession.ts +1 -37
  85. package/src/chat/NewSessionPicker.tsx +3 -2
  86. package/src/chat/ProjectSelectorView.tsx +3 -2
  87. package/src/chat/ReasoningStepSlider.tsx +61 -0
  88. package/src/chat/RemoteSessionBadgeView.tsx +24 -0
  89. package/src/chat/SkillPromptAreaView.tsx +5 -19
  90. package/src/chat/TeamMemberReplyCardView.test.tsx +33 -0
  91. package/src/chat/TeamMemberReplyCardView.tsx +133 -0
  92. package/src/chat/TextBlockView.tsx +7 -770
  93. package/src/chat/TodoProgress.tsx +25 -53
  94. package/src/chat/TodoStatusBarView.tsx +14 -5
  95. package/src/chat/UserMessageView.tsx +113 -33
  96. package/src/chat/header-action-narrow.test.ts +21 -0
  97. package/src/chat/header-action-narrow.ts +38 -0
  98. package/src/chat/index.ts +33 -27
  99. package/src/chat/markdown-link.ts +7 -279
  100. package/src/chat/message-feed-fade.css +80 -0
  101. package/src/chat/message-feed-fade.test.tsx +75 -0
  102. package/src/chat/send-button.css +4 -22
  103. package/src/chat/streaming-reveal.test.ts +218 -0
  104. package/src/chat/streaming-reveal.ts +13 -0
  105. package/src/file-explorer/ConfirmDeleteDialogView.tsx +2 -1
  106. package/src/file-explorer/FileContextMenuView.tsx +44 -11
  107. package/src/file-explorer/FileExplorerSettingsView.tsx +97 -0
  108. package/src/file-explorer/FileTreeCreateRow.tsx +1 -1
  109. package/src/file-explorer/FileTreeNodeView.tsx +59 -18
  110. package/src/file-explorer/FileTreeView.tsx +236 -129
  111. package/src/file-explorer/file-tree-dom.ts +23 -0
  112. package/src/file-explorer/file-tree-rows.test.ts +74 -0
  113. package/src/file-explorer/file-tree-rows.ts +168 -0
  114. package/src/file-explorer/index.ts +17 -0
  115. package/src/file-explorer/types.ts +3 -0
  116. package/src/file-explorer/useFileTreeMarqueeSelection.ts +24 -16
  117. package/src/file-preview/FilePreviewDialogView.tsx +2 -2
  118. package/src/file-preview/FilePreviewView.tsx +12 -2
  119. package/src/file-preview/ReadonlyCodeView.tsx +46 -0
  120. package/src/file-preview/TextFileEditorView.tsx +2 -1
  121. package/src/file-preview/syntax-tokens.css +1 -1
  122. package/src/image-assets.d.ts +4 -0
  123. package/src/index.ts +1 -0
  124. package/src/knowledge/KnowledgeHowItWorksDialogView.tsx +1 -1
  125. package/src/layout/AppFrame.tsx +3 -2
  126. package/src/layout/MainContentFrame.tsx +7 -2
  127. package/src/layout/ResizeHandle.tsx +68 -17
  128. package/src/layout/SidebarDock.tsx +75 -19
  129. package/src/layout/SidebarOverlay.tsx +1 -1
  130. package/src/layout/index.ts +1 -1
  131. package/src/layout/resize-handle-axis.test.ts +51 -0
  132. package/src/live-indicators.test.ts +43 -0
  133. package/src/markdown/CodeBlock.tsx +123 -0
  134. package/src/markdown/FileLinkBadge.tsx +77 -0
  135. package/src/markdown/InlineTokenChip.tsx +68 -0
  136. package/src/markdown/MarkdownContent.tsx +418 -0
  137. package/src/markdown/MarkdownImage.tsx +41 -0
  138. package/src/markdown/MathFormula.tsx +46 -0
  139. package/src/markdown/MermaidBlock.tsx +82 -0
  140. package/src/markdown/RichCodeBlock.tsx +127 -0
  141. package/src/markdown/SvgPreview.tsx +45 -0
  142. package/src/markdown/WebsiteIcon.tsx +94 -0
  143. package/src/markdown/builtin-renderers.tsx +43 -0
  144. package/src/markdown/definition.tsx +49 -0
  145. package/src/markdown/host.tsx +18 -0
  146. package/src/markdown/image-actions.ts +29 -0
  147. package/src/markdown/index.ts +12 -0
  148. package/src/markdown/inline-tokens.ts +187 -0
  149. package/src/markdown/markdown-link.ts +279 -0
  150. package/src/markdown/math-client.ts +116 -0
  151. package/src/markdown/math-render.ts +23 -0
  152. package/src/markdown/math-syntax.ts +80 -0
  153. package/src/markdown/math.worker.ts +16 -0
  154. package/src/markdown/nodes.ts +15 -0
  155. package/src/markdown/preview-policy.test.ts +31 -0
  156. package/src/markdown/preview-policy.ts +76 -0
  157. package/src/markdown/progressive-chunks.test.ts +43 -0
  158. package/src/markdown/progressive-chunks.ts +58 -0
  159. package/src/markdown/rich-labels.ts +55 -0
  160. package/src/markdown/rich-syntax.ts +93 -0
  161. package/src/markdown/stable-blocks.test.ts +90 -0
  162. package/src/markdown/stable-blocks.ts +124 -0
  163. package/src/markdown/streaming-reveal.ts +297 -0
  164. package/src/markdown/streaming.test.ts +57 -0
  165. package/src/markdown/streaming.ts +211 -0
  166. package/src/markdown/use-render-snapshot.ts +24 -0
  167. package/src/markdown/use-rich-visibility.ts +24 -0
  168. package/src/overlays/CommandMenuRow.tsx +77 -17
  169. package/src/overlays/CommandMenuView.tsx +163 -118
  170. package/src/overlays/ConfirmDialogView.tsx +25 -20
  171. package/src/overlays/DiagnosticsExportDialogView.tsx +236 -0
  172. package/src/overlays/MagpieHandoverDialogView.tsx +217 -0
  173. package/src/overlays/ReleaseNoteMarkdown.test.tsx +24 -0
  174. package/src/overlays/ReleaseNoteMarkdown.tsx +55 -0
  175. package/src/overlays/SplashOptionRow.tsx +46 -0
  176. package/src/overlays/SplashPanel.tsx +85 -0
  177. package/src/overlays/SplashParts.tsx +217 -0
  178. package/src/overlays/UpdateCheckerView.tsx +34 -18
  179. package/src/overlays/UpdateRestartDialogView.tsx +203 -53
  180. package/src/overlays/assets/diagnostics-banner.webp +0 -0
  181. package/src/overlays/command-menu-types.ts +15 -1
  182. package/src/overlays/command-menu.css +1 -20
  183. package/src/overlays/index.ts +26 -1
  184. package/src/plugin-ui/index.ts +10 -0
  185. package/src/project/ConversationTagDotsView.tsx +1 -1
  186. package/src/project/ConversationTagEditorDialogView.tsx +4 -1
  187. package/src/project/DefaultConversationSectionView.tsx +15 -24
  188. package/src/project/DefaultSessionListView.tsx +5 -31
  189. package/src/project/DefaultSessionRowView.tsx +114 -55
  190. package/src/project/ManageSessionsSplashView.tsx +439 -0
  191. package/src/project/NewProjectDialogView.tsx +3 -10
  192. package/src/project/ProjectContextMenuView.tsx +30 -139
  193. package/src/project/ProjectDetailPageView.test.tsx +140 -0
  194. package/src/project/ProjectDetailPageView.tsx +372 -165
  195. package/src/project/ProjectGroupView.tsx +1 -1
  196. package/src/project/ProjectRowView.tsx +29 -12
  197. package/src/project/ProjectSessionsView.tsx +25 -47
  198. package/src/project/QuickScrollOverlay.tsx +1 -1
  199. package/src/project/SessionContextMenuView.tsx +15 -7
  200. package/src/project/SessionRowMoreButton.tsx +50 -0
  201. package/src/project/SessionRowView.tsx +106 -63
  202. package/src/project/SessionTitleMarquee.tsx +54 -0
  203. package/src/project/SidebarProjectDisclosure.tsx +60 -0
  204. package/src/project/SidebarProjectsSectionView.tsx +6 -1
  205. package/src/project/index.ts +12 -0
  206. package/src/project/session-row-transition.ts +9 -0
  207. package/src/project/types.ts +4 -2
  208. package/src/project/useActiveSessionAutoScroll.ts +10 -4
  209. package/src/registry.ts +0 -2
  210. package/src/scheduler/AutomationDetailPaneView.tsx +68 -0
  211. package/src/scheduler/AutomationPageView.tsx +118 -121
  212. package/src/scheduler/ExecutionHistoryView.tsx +7 -5
  213. package/src/scheduler/TaskListView.tsx +52 -201
  214. package/src/scheduler/index.ts +7 -12
  215. package/src/settings/AppshotSettingsView.tsx +0 -1
  216. package/src/settings/ArchivedProjectsSettingsView.tsx +122 -1
  217. package/src/settings/BuiltinMcpSectionView.tsx +1 -1
  218. package/src/settings/EnvironmentGitRowView.tsx +156 -0
  219. package/src/settings/EnvironmentSettingsView.tsx +25 -3
  220. package/src/settings/GeneralSettingsView.tsx +18 -24
  221. package/src/settings/ImChannelGuideDialogView.tsx +2 -2
  222. package/src/settings/ImFeishuDialogView.tsx +1 -1
  223. package/src/settings/ImLegacyImportBannerView.tsx +1 -1
  224. package/src/settings/ImLogDrawerView.tsx +2 -1
  225. package/src/settings/JsonConfigInputView.tsx +171 -0
  226. package/src/settings/LauncherSettingsView.test.tsx +95 -0
  227. package/src/settings/LauncherSettingsView.tsx +273 -0
  228. package/src/settings/ModelsFetchedModelsDrawerView.tsx +292 -0
  229. package/src/settings/ModelsProvidersSectionView.tsx +26 -23
  230. package/src/settings/MotionSelect.tsx +9 -7
  231. package/src/settings/NotificationSettingsView.tsx +79 -0
  232. package/src/settings/PermissionsSettingsView.tsx +3 -7
  233. package/src/settings/PetActionGalleryView.test.tsx +163 -0
  234. package/src/settings/PetActionGalleryView.tsx +216 -0
  235. package/src/settings/PetSettingsView.test.tsx +117 -0
  236. package/src/settings/PetSettingsView.tsx +86 -22
  237. package/src/settings/PresetProviderModelsListView.tsx +141 -24
  238. package/src/settings/PresetProviderRowView.tsx +147 -185
  239. package/src/settings/ProxySettingsSectionView.tsx +182 -0
  240. package/src/settings/QrBindDialogView.tsx +1 -1
  241. package/src/settings/RemoteMcpSectionView.tsx +1 -1
  242. package/src/settings/SettingChrome.tsx +2 -2
  243. package/src/settings/SettingsAiAssistButtonView.tsx +9 -119
  244. package/src/settings/SettingsFormFields.tsx +4 -7
  245. package/src/settings/SettingsSidebarView.tsx +64 -3
  246. package/src/settings/ShortcutRecorderView.test.tsx +108 -0
  247. package/src/settings/ShortcutRecorderView.tsx +15 -9
  248. package/src/settings/ShortcutsSettingsView.tsx +1 -5
  249. package/src/settings/SpaceEditorDialogView.tsx +158 -0
  250. package/src/settings/SpacesSettingsView.tsx +150 -0
  251. package/src/settings/WebhookEndpointListView.tsx +4 -5
  252. package/src/settings/assets/space-editor-illustration.webp +0 -0
  253. package/src/settings/index.ts +59 -68
  254. package/src/shared/ActivityStatusDot.tsx +69 -0
  255. package/src/shared/AvatarStackView.tsx +13 -13
  256. package/src/shared/BotAvatar.tsx +11 -9
  257. package/src/shared/CodeBlockCopyButton.tsx +1 -1
  258. package/src/shared/ContextMenuView.tsx +4 -11
  259. package/src/shared/MarkdownTable.tsx +2 -2
  260. package/src/shared/SegmentedControl.test.tsx +68 -0
  261. package/src/shared/SegmentedControl.tsx +10 -2
  262. package/src/shared/SyntaxHighlightedCode.tsx +0 -0
  263. package/src/shared/TabBar.outline.test.tsx +59 -0
  264. package/src/shared/TabBar.tsx +23 -18
  265. package/src/shared/VettaKbd.test.tsx +52 -0
  266. package/src/shared/VettaKbd.tsx +100 -0
  267. package/src/shared/connected-tab-outline.test.ts +2 -2
  268. package/src/shared/connected-tab-outline.ts +2 -1
  269. package/src/shared/index.ts +7 -0
  270. package/src/shared/kbd-keys.test.ts +61 -0
  271. package/src/shared/kbd-keys.ts +253 -0
  272. package/src/shared/platform.ts +9 -0
  273. package/src/shared/provider-icon/icons.ts +4 -2
  274. package/src/shared/provider-icon/index.tsx +1 -1
  275. package/src/shared/provider-icon/magpie.svg +1 -0
  276. package/src/sidebar/AddProjectMenuTriggerView.tsx +33 -24
  277. package/src/sidebar/DefaultSidebar.tsx +3 -1
  278. package/src/sidebar/MessageCenterDialogView.tsx +3 -2
  279. package/src/sidebar/MessageCenterEmptyState.tsx +1 -1
  280. package/src/sidebar/MessageCenterTabs.tsx +1 -1
  281. package/src/sidebar/MessageCenterToolbarButton.tsx +1 -1
  282. package/src/sidebar/MessageCenterTriggerView.tsx +2 -2
  283. package/src/sidebar/ProjectsPanelEmptyState.tsx +26 -7
  284. package/src/sidebar/SessionStatusIcon.tsx +16 -1
  285. package/src/sidebar/SettingsMenuThemeSection.tsx +1 -1
  286. package/src/sidebar/SettingsMenuTriggerView.test.tsx +42 -0
  287. package/src/sidebar/SettingsMenuTriggerView.tsx +29 -50
  288. package/src/sidebar/ShowMoreSessionsButton.tsx +1 -1
  289. package/src/sidebar/SidebarFilterSelectView.tsx +8 -16
  290. package/src/sidebar/SidebarNavBadgeView.tsx +1 -1
  291. package/src/sidebar/SidebarNavIcon.tsx +1 -1
  292. package/src/sidebar/SidebarNavItemButton.tsx +1 -1
  293. package/src/sidebar/SidebarNavMorePanel.tsx +19 -7
  294. package/src/sidebar/SidebarNavigation.tsx +24 -15
  295. package/src/sidebar/SidebarPanel.tsx +11 -2
  296. package/src/sidebar/SidebarSectionActionButton.test.tsx +91 -0
  297. package/src/sidebar/SidebarSectionActionButton.tsx +52 -0
  298. package/src/sidebar/SidebarSectionTriggerLabel.tsx +20 -0
  299. package/src/sidebar/SidebarTopBar.tsx +10 -7
  300. package/src/sidebar/WaitingPulseBadge.tsx +19 -0
  301. package/src/sidebar/index.ts +1 -16
  302. package/src/skills/index.ts +0 -19
  303. package/src/skills/skill-icon.tsx +4 -8
  304. package/src/styles.css +26 -6
  305. package/src/chat/DefaultSceneCarousel.tsx +0 -113
  306. package/src/chat/SceneCard.tsx +0 -138
  307. package/src/scheduler/HistoryDrawerView.tsx +0 -149
  308. package/src/scheduler/TaskFormDialogView.tsx +0 -60
  309. package/src/settings/AchievementNavigationButtonView.tsx +0 -90
  310. package/src/settings/AchievementPromotionDialogView.tsx +0 -91
  311. package/src/settings/AchievementSettingsView.tsx +0 -44
  312. package/src/settings/PetBubbleStylePreviewView.tsx +0 -44
  313. package/src/settings/QuickPanelSettingsSectionView.tsx +0 -66
  314. package/src/settings/SubscriptionActionsView.tsx +0 -63
  315. package/src/settings/SubscriptionCardsView.tsx +0 -212
  316. package/src/settings/TeamDetailView.tsx +0 -148
  317. package/src/settings/TeamDialogsView.tsx +0 -151
  318. package/src/settings/TeamListView.tsx +0 -57
  319. package/src/settings/TeamSettingsView.tsx +0 -51
  320. package/src/settings/TokenActivityChartView.tsx +0 -286
  321. package/src/settings/UsageStatsView.tsx +0 -101
  322. package/src/settings/achievements/AchievementCurtains.tsx +0 -50
  323. package/src/settings/achievements/AchievementPromotionBadge3D.tsx +0 -350
  324. package/src/settings/achievements/AchievementPromotionConfetti.tsx +0 -71
  325. package/src/settings/achievements/AchievementTitle.tsx +0 -52
  326. package/src/settings/achievements/index.ts +0 -13
  327. package/src/settings/shouldCloseEmptyApiKeyEditor.test.ts +0 -135
  328. package/src/settings/shouldCloseEmptyApiKeyEditor.ts +0 -40
  329. package/src/settings/token-activity.test.ts +0 -195
  330. package/src/settings/token-activity.ts +0 -320
  331. package/src/sidebar/AddProjectMenuItem.tsx +0 -21
  332. package/src/sidebar/AddProjectMenuPopoverView.tsx +0 -52
  333. package/src/sidebar/NotificationMessageListView.tsx +0 -136
  334. package/src/sidebar/SettingsMenuAccountSection.tsx +0 -32
  335. package/src/sidebar/SettingsMenuQuotaSection.tsx +0 -45
  336. package/src/skills/SceneCardView.tsx +0 -194
  337. package/src/skills/SkillCardView.tsx +0 -186
  338. package/src/skills/SkillDetailDialogView.tsx +0 -138
  339. package/src/skills/SkillTagGroupView.tsx +0 -56
  340. package/src/skills/SkillToggleSwitch.tsx +0 -31
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Classify markdown `href` values for chat text blocks.
3
+ *
4
+ * LLMs emit many shapes: `file://`, POSIX `/abs`, Windows `C:\…`,
5
+ * relative `./foo` / `src/a.ts`, and real `https://` URLs. Misclassifying a
6
+ * local path as a generic anchor (especially with `target="_blank"`) opens
7
+ * the system browser instead of the in-app file preview.
8
+ *
9
+ * Also: `react-markdown`'s `defaultUrlTransform` treats `C:` as an unknown
10
+ * protocol and blanks the href — Windows paths must be allowlisted via
11
+ * {@link chatUrlTransform}. Models also occasionally omit CommonMark's angle
12
+ * brackets around local destinations that contain whitespace. The normalizer
13
+ * repairs those legacy forms before parse and standardizes local destinations.
14
+ */
15
+
16
+ import { defaultUrlTransform } from "react-markdown";
17
+
18
+ export type MarkdownLinkKind =
19
+ | { type: "file"; path: string }
20
+ | { type: "url"; url: string }
21
+ | { type: "other"; href: string };
22
+
23
+ function safeDecode(raw: string): string {
24
+ try {
25
+ return decodeURIComponent(raw);
26
+ } catch {
27
+ return raw;
28
+ }
29
+ }
30
+
31
+ function toPosixSeparators(path: string): string {
32
+ return path.replace(/\\/g, "/");
33
+ }
34
+
35
+ /**
36
+ * Allow local filesystem hrefs that `defaultUrlTransform` would strip because
37
+ * it sees `C:` / `file:` as unsafe protocols. Everything else keeps the
38
+ * library default (blocks `javascript:` etc.).
39
+ */
40
+ export function chatUrlTransform(url: string): string {
41
+ // Windows drive: C:\… C:/… or rehype-encoded C:%5C…
42
+ if (/^[A-Za-z]:[\\/]/.test(url) || /^[A-Za-z]:%5[Cc]/i.test(url)) {
43
+ return url;
44
+ }
45
+ // file:// local URLs
46
+ if (/^file:/i.test(url)) {
47
+ return url;
48
+ }
49
+ return defaultUrlTransform(url);
50
+ }
51
+
52
+ interface MarkdownFence {
53
+ character: "`" | "~";
54
+ length: number;
55
+ }
56
+
57
+ const STANDARD_LINK_TITLE = /^(\S+)(\s+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\([^()]*\)))$/;
58
+
59
+ function splitStandardLinkTitle(destination: string): { path: string; title: string } {
60
+ const match = STANDARD_LINK_TITLE.exec(destination);
61
+ return match ? { path: match[1], title: match[2] } : { path: destination, title: "" };
62
+ }
63
+
64
+ function normalizeAbsoluteLocalDestination(path: string): string | null {
65
+ if (!path || /[<>\r\n]/.test(path)) return null;
66
+ if (/^\\\\[^\\]/.test(path)) {
67
+ return `file://${path.slice(2).replace(/\\/g, "/")}`;
68
+ }
69
+ if (/^file:/i.test(path)) return path.replace(/\\/g, "/");
70
+ if (/^\/?[A-Za-z]:[\\/]/.test(path)) return path.replace(/\\/g, "/");
71
+ if (path.startsWith("/") && !path.startsWith("//")) return path;
72
+ return null;
73
+ }
74
+
75
+ function normalizeBareDestination(destination: string): string | null {
76
+ const { path, title } = splitStandardLinkTitle(destination);
77
+ const normalized = normalizeAbsoluteLocalDestination(path);
78
+ return normalized ? `<${normalized}>${title}` : null;
79
+ }
80
+
81
+ function findBareDestinationEnd(line: string, start: number): number {
82
+ let parenthesesDepth = 0;
83
+ for (let index = start; index < line.length; index++) {
84
+ if (line[index] === "(") {
85
+ parenthesesDepth++;
86
+ continue;
87
+ }
88
+ if (line[index] !== ")") continue;
89
+ if (parenthesesDepth === 0) return index;
90
+ parenthesesDepth--;
91
+ }
92
+ return -1;
93
+ }
94
+
95
+ function normalizeMarkdownLine(line: string): string {
96
+ if (/^(?: {4}|\t)/.test(line)) return line;
97
+
98
+ let result = "";
99
+ let cursor = 0;
100
+ let codeDelimiterLength = 0;
101
+ for (let index = 0; index < line.length; ) {
102
+ if (line[index] === "`") {
103
+ let end = index + 1;
104
+ while (line[end] === "`") end++;
105
+ const runLength = end - index;
106
+ if (codeDelimiterLength === 0) codeDelimiterLength = runLength;
107
+ else if (runLength === codeDelimiterLength) codeDelimiterLength = 0;
108
+ index = end;
109
+ continue;
110
+ }
111
+
112
+ if (codeDelimiterLength !== 0 || line[index] !== "]" || line[index + 1] !== "(") {
113
+ index++;
114
+ continue;
115
+ }
116
+
117
+ const destinationStart = index + 2;
118
+ if (line[destinationStart] === "<") {
119
+ const angleEnd = line.indexOf(">)", destinationStart + 1);
120
+ if (angleEnd === -1) {
121
+ index++;
122
+ continue;
123
+ }
124
+ const normalized = normalizeAbsoluteLocalDestination(line.slice(destinationStart + 1, angleEnd));
125
+ if (!normalized) {
126
+ index = angleEnd + 2;
127
+ continue;
128
+ }
129
+ result += `${line.slice(cursor, destinationStart)}<${normalized}>)`;
130
+ cursor = angleEnd + 2;
131
+ index = cursor;
132
+ continue;
133
+ }
134
+
135
+ const destinationEnd = findBareDestinationEnd(line, destinationStart);
136
+ if (destinationEnd === -1) {
137
+ index++;
138
+ continue;
139
+ }
140
+ const normalized = normalizeBareDestination(line.slice(destinationStart, destinationEnd));
141
+ if (!normalized) {
142
+ index = destinationEnd + 1;
143
+ continue;
144
+ }
145
+ result += `${line.slice(cursor, destinationStart)}${normalized})`;
146
+ cursor = destinationEnd + 1;
147
+ index = cursor;
148
+ }
149
+ return result + line.slice(cursor);
150
+ }
151
+
152
+ /**
153
+ * Standardize absolute local link destinations as CommonMark angle-bracket
154
+ * destinations before parsing. This makes whitespace and balanced parentheses
155
+ * unambiguous, converts Windows separators, and repairs already persisted model
156
+ * output such as `[file](/C:/Users/name/My Files/file.md)`.
157
+ *
158
+ */
159
+ export function normalizeLocalFileLinksInMarkdown(markdown: string): string {
160
+ const parts = markdown.split(/(\r\n|\n|\r)/);
161
+ let fence: MarkdownFence | null = null;
162
+ return parts
163
+ .map((part) => {
164
+ if (part === "\n" || part === "\r" || part === "\r\n") return part;
165
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(part)?.[1];
166
+ if (marker) {
167
+ const character = marker[0] as MarkdownFence["character"];
168
+ if (!fence) fence = { character, length: marker.length };
169
+ else if (
170
+ character === fence.character &&
171
+ marker.length >= fence.length &&
172
+ part.slice(part.indexOf(marker) + marker.length).trim() === ""
173
+ ) {
174
+ fence = null;
175
+ }
176
+ return part;
177
+ }
178
+ return fence ? part : normalizeMarkdownLine(part);
179
+ })
180
+ .join("");
181
+ }
182
+
183
+ /**
184
+ * Convert a `file://` URL to an OS path (POSIX absolute or Windows drive/UNC).
185
+ * Returns null when the input is not a usable file URL.
186
+ */
187
+ export function fileUrlToPath(href: string): string | null {
188
+ try {
189
+ const url = new URL(href);
190
+ if (url.protocol !== "file:") return null;
191
+ let path = safeDecode(url.pathname);
192
+ // Windows drive: /C:/Users → C:/Users
193
+ if (/^\/[A-Za-z]:/.test(path)) {
194
+ path = path.slice(1);
195
+ }
196
+ // UNC: file://server/share/path → //server/share/path
197
+ if (url.hostname && url.hostname !== "localhost") {
198
+ const body = path.startsWith("/") ? path : `/${path}`;
199
+ path = `//${url.hostname}${body}`;
200
+ }
201
+ return toPosixSeparators(path) || null;
202
+ } catch {
203
+ const stripped = safeDecode(href.replace(/^file:\/\//i, ""));
204
+ if (!stripped) return null;
205
+ if (/^\/[A-Za-z]:/.test(stripped)) {
206
+ return toPosixSeparators(stripped.slice(1));
207
+ }
208
+ return toPosixSeparators(stripped);
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Bare names like `readme.md` should open as files; bare domains like
214
+ * `www.example.com` must not. Prefer path separators / relative prefixes;
215
+ * fall back to a conservative extension allowlist (not generic TLDs).
216
+ */
217
+ const LIKELY_FILE_EXT =
218
+ /\.(?:tsx?|jsx?|mjs|cjs|json|mdx?|txt|pdf|png|jpe?g|gif|webp|svg|html?|css|scss|less|py|rs|go|java|kt|swift|c|cc|cpp|h|hpp|cs|rb|php|sh|bash|zsh|ya?ml|toml|xml|csv|tsv|xlsx?|docx?|pptx?|zip|gz|tgz|7z|rar|mp3|mp4|wav|webm|ico|woff2?|ttf|otf|map|sql|vue|svelte|astro|wasm|log|conf|cfg|ini|plist|ipynb|rtf|lock|env)$/i;
219
+
220
+ function looksLikeRelativeFilePath(value: string): boolean {
221
+ if (/^[.]{1,2}[\\/]/.test(value)) return true;
222
+ if (/[\\/]/.test(value)) return true;
223
+ return LIKELY_FILE_EXT.test(value);
224
+ }
225
+
226
+ /**
227
+ * Classify a markdown link href into file / external URL / other.
228
+ * File paths are returned with `/` separators; relative paths are left relative
229
+ * for the host to resolve against the project cwd.
230
+ */
231
+ export function classifyMarkdownLink(href: string | undefined): MarkdownLinkKind {
232
+ if (!href) return { type: "other", href: "" };
233
+ const trimmed = href.trim();
234
+ if (!trimmed || trimmed.startsWith("#")) {
235
+ return { type: "other", href: trimmed };
236
+ }
237
+
238
+ if (/^(mailto|tel|javascript|data|blob|vetta):/i.test(trimmed)) {
239
+ return { type: "other", href: trimmed };
240
+ }
241
+
242
+ if (/^https?:\/\//i.test(trimmed)) {
243
+ return { type: "url", url: trimmed };
244
+ }
245
+
246
+ // Protocol-relative URL (//cdn.example.com/x) — not a Windows UNC path.
247
+ if (trimmed.startsWith("//") && !trimmed.startsWith("\\\\")) {
248
+ return { type: "url", url: `https:${trimmed}` };
249
+ }
250
+
251
+ if (/^file:\/\//i.test(trimmed)) {
252
+ const path = fileUrlToPath(trimmed);
253
+ if (path) return { type: "file", path };
254
+ return { type: "other", href: trimmed };
255
+ }
256
+
257
+ const decoded = safeDecode(trimmed);
258
+
259
+ // Windows drive absolute: C:\… or C:/… (after decode of %5C)
260
+ if (/^[A-Za-z]:[\\/]/.test(decoded)) {
261
+ return { type: "file", path: toPosixSeparators(decoded) };
262
+ }
263
+
264
+ // Windows UNC: \\server\share
265
+ if (decoded.startsWith("\\\\")) {
266
+ return { type: "file", path: toPosixSeparators(decoded) };
267
+ }
268
+
269
+ // POSIX absolute
270
+ if (decoded.startsWith("/")) {
271
+ return { type: "file", path: decoded };
272
+ }
273
+
274
+ if (looksLikeRelativeFilePath(decoded)) {
275
+ return { type: "file", path: toPosixSeparators(decoded) };
276
+ }
277
+
278
+ return { type: "other", href: trimmed };
279
+ }
@@ -0,0 +1,116 @@
1
+ type Listener = (html: string | null) => void;
2
+ interface Job {
3
+ id: number;
4
+ key: string;
5
+ source: string;
6
+ display: boolean;
7
+ listeners: Set<Listener>;
8
+ }
9
+
10
+ const cache = new Map<string, string | null>();
11
+ let cacheSize = 0;
12
+ const jobs = new Map<string, Job>();
13
+ let worker: Worker | null = null;
14
+ let running: Job | null = null;
15
+ let sequence = 0;
16
+ let deadline: ReturnType<typeof setTimeout> | undefined;
17
+ let idle: ReturnType<typeof setTimeout> | undefined;
18
+
19
+ function disposeWorker() {
20
+ clearTimeout(deadline);
21
+ clearTimeout(idle);
22
+ worker?.terminate();
23
+ worker = null;
24
+ }
25
+
26
+ function finish(html: string | null) {
27
+ clearTimeout(deadline);
28
+ const job = running;
29
+ if (!job) return;
30
+ running = null;
31
+ jobs.delete(job.key);
32
+ const size = job.key.length + (html?.length ?? 0);
33
+ if (size <= 1_000_000) {
34
+ while (cache.size >= 256 || cacheSize + size > 1_000_000) {
35
+ const oldest = cache.keys().next().value;
36
+ if (oldest === undefined) break;
37
+ cacheSize -= oldest.length + (cache.get(oldest)?.length ?? 0);
38
+ cache.delete(oldest);
39
+ }
40
+ cache.set(job.key, html);
41
+ cacheSize += size;
42
+ }
43
+ for (const listener of job.listeners) listener(html);
44
+ pump();
45
+ }
46
+
47
+ function pump() {
48
+ if (running) return;
49
+ const job = jobs.values().next().value;
50
+ if (!job) {
51
+ idle = setTimeout(disposeWorker, 30_000);
52
+ return;
53
+ }
54
+ clearTimeout(idle);
55
+ running = job;
56
+ try {
57
+ if (!worker) {
58
+ const instance = new Worker(new URL("./math.worker.ts", import.meta.url), { type: "module" });
59
+ worker = instance;
60
+ instance.onmessage = (event: MessageEvent<unknown>) => {
61
+ if (worker !== instance) return;
62
+ const data = event.data;
63
+ if (!data || typeof data !== "object" || !("id" in data) || !("html" in data)) return;
64
+ if (data.id !== running?.id || (data.html !== null && typeof data.html !== "string")) return;
65
+ finish(data.html);
66
+ };
67
+ instance.onerror = () => {
68
+ if (worker !== instance) return;
69
+ disposeWorker();
70
+ finish(null);
71
+ };
72
+ }
73
+ deadline = setTimeout(() => {
74
+ disposeWorker();
75
+ finish(null);
76
+ }, 2000);
77
+ worker.postMessage({ id: job.id, source: job.source, display: job.display });
78
+ } catch {
79
+ disposeWorker();
80
+ finish(null);
81
+ }
82
+ }
83
+
84
+ /** Deduplicated, serial and cancellable; detached formulas never keep queued work alive. */
85
+ export function requestFormula(source: string, display: boolean, listener: Listener): () => void {
86
+ if (source.length > 8192) {
87
+ listener(null);
88
+ return () => {};
89
+ }
90
+ const key = JSON.stringify([source, display]);
91
+ if (cache.has(key)) {
92
+ listener(cache.get(key) ?? null);
93
+ return () => {};
94
+ }
95
+ let job = jobs.get(key);
96
+ if (!job) {
97
+ if (jobs.size >= 128) {
98
+ listener(null);
99
+ return () => {};
100
+ }
101
+ job = { id: ++sequence, key, source, display, listeners: new Set() };
102
+ jobs.set(key, job);
103
+ }
104
+ job.listeners.add(listener);
105
+ pump();
106
+ return () => {
107
+ job.listeners.delete(listener);
108
+ if (job.listeners.size !== 0) return;
109
+ jobs.delete(key);
110
+ if (running === job) {
111
+ disposeWorker();
112
+ running = null;
113
+ pump();
114
+ }
115
+ };
116
+ }
@@ -0,0 +1,23 @@
1
+ import katex from "katex";
2
+
3
+ export const MAX_FORMULA_LENGTH = 8192;
4
+
5
+ /** Called only in the worker; each formula gets its own macro scope. */
6
+ export function renderFormula(source: string, displayMode: boolean): string | null {
7
+ if (source.length > MAX_FORMULA_LENGTH) return null;
8
+ try {
9
+ const html = katex.renderToString(source, {
10
+ displayMode,
11
+ output: "htmlAndMathml",
12
+ trust: false,
13
+ throwOnError: true,
14
+ strict: "ignore",
15
+ maxExpand: 500,
16
+ maxSize: 20,
17
+ macros: {},
18
+ });
19
+ return html.length <= 1_000_000 ? html : null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
@@ -0,0 +1,80 @@
1
+ import type { Extension } from "mdast-util-from-markdown";
2
+ import type { Tokenizer } from "micromark-util-types";
3
+ import type { Processor } from "unified";
4
+
5
+ declare module "micromark-util-types" {
6
+ interface TokenTypeMap {
7
+ vettaMath: "vettaMath";
8
+ }
9
+ }
10
+
11
+ const tokenize: Tokenizer = (effects, ok, nok) => {
12
+ let closing = 41;
13
+ let count = 0;
14
+ return start;
15
+ function start(code: number | null) {
16
+ effects.enter("vettaMath");
17
+ effects.consume(code);
18
+ return delimiter;
19
+ }
20
+ function delimiter(code: number | null) {
21
+ if (code !== 40 && code !== 91) return nok(code);
22
+ closing = code === 40 ? 41 : 93;
23
+ effects.consume(code);
24
+ return body;
25
+ }
26
+ function body(code: number | null): ReturnType<Tokenizer> | undefined {
27
+ if (code === null || ++count > 16_000) return nok(code);
28
+ effects.consume(code);
29
+ return code === 92 ? end : body;
30
+ }
31
+ function end(code: number | null): ReturnType<Tokenizer> | undefined {
32
+ if (code === closing) {
33
+ effects.consume(code);
34
+ effects.exit("vettaMath");
35
+ return ok;
36
+ }
37
+ if (code === 40 || code === 91) return nok(code);
38
+ // A doubled slash is TeX's line break, not a closing delimiter.
39
+ if (code === 92) {
40
+ effects.consume(code);
41
+ return body;
42
+ }
43
+ return body(code);
44
+ }
45
+ };
46
+
47
+ /** Tokenize before Markdown escaping; fenced/inline code and link destinations remain untouched. */
48
+ export function remarkMathAliases(this: Processor) {
49
+ const data = this.data();
50
+ data.micromarkExtensions ??= [];
51
+ data.micromarkExtensions.push({ text: { 92: { name: "vettaMath", tokenize } } });
52
+ const extension: Extension = {
53
+ enter: {
54
+ vettaMath(token) {
55
+ const raw = this.sliceSerialize(token);
56
+ this.enter(
57
+ {
58
+ type: "inlineMath",
59
+ value: raw.slice(2, -2),
60
+ data: {
61
+ hName: "code",
62
+ hProperties: { className: ["language-math", raw[1] === "[" ? "math-display" : "math-inline"] },
63
+ hChildren: [{ type: "text", value: raw.slice(2, -2) }],
64
+ },
65
+ },
66
+ token,
67
+ );
68
+ },
69
+ },
70
+ exit: {
71
+ vettaMath(token) {
72
+ this.exit(token);
73
+ },
74
+ },
75
+ };
76
+ data.fromMarkdownExtensions ??= [];
77
+ data.fromMarkdownExtensions.push(extension);
78
+ }
79
+
80
+ import type {} from "remark-parse";
@@ -0,0 +1,16 @@
1
+ import { renderFormula } from "./math-render";
2
+
3
+ globalThis.onmessage = (event: MessageEvent<unknown>) => {
4
+ const request = event.data;
5
+ if (
6
+ !request ||
7
+ typeof request !== "object" ||
8
+ !("id" in request) ||
9
+ !("source" in request) ||
10
+ !("display" in request)
11
+ )
12
+ return;
13
+ if (typeof request.id !== "number" || typeof request.source !== "string" || typeof request.display !== "boolean")
14
+ return;
15
+ globalThis.postMessage({ id: request.id, html: renderFormula(request.source, request.display) });
16
+ };
@@ -0,0 +1,15 @@
1
+ /** Minimal hast-like nodes for the streaming chunk rehype plugin. */
2
+ export interface HastText {
3
+ type: "text";
4
+ value: string;
5
+ }
6
+ export interface HastElement {
7
+ type: "element";
8
+ tagName: string;
9
+ properties?: Record<string, unknown>;
10
+ children: Array<HastText | HastElement>;
11
+ }
12
+ export interface HastRoot {
13
+ type: "root";
14
+ children: Array<HastText | HastElement>;
15
+ }
@@ -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
+ });
@@ -0,0 +1,76 @@
1
+ export const MAX_PREVIEW_LENGTH = 256_000;
2
+ export const MARKDOWN_PREVIEW_FRAME_NAME = "vetta-markdown-preview";
3
+
4
+ /** No same-origin, popups, forms, downloads, navigation of ancestors or host bridge. */
5
+ export function createPreviewDocument(source: string): string {
6
+ const policy = [
7
+ "default-src 'none'",
8
+ "script-src 'none'",
9
+ "style-src 'unsafe-inline'",
10
+ "img-src data: blob:",
11
+ "font-src data:",
12
+ "connect-src 'none'",
13
+ "frame-src 'none'",
14
+ "worker-src 'none'",
15
+ "object-src 'none'",
16
+ "base-uri 'none'",
17
+ "form-action 'none'",
18
+ ].join("; ");
19
+ // The trusted outer frame also restricts child navigation. A child's own CSP alone
20
+ // cannot prevent scripts assigning location or a meta refresh from navigating itself.
21
+ const document = `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${policy}"><meta name="referrer" content="no-referrer">${source}`;
22
+ const escaped = document
23
+ .replaceAll("&", "&amp;")
24
+ .replaceAll('"', "&quot;")
25
+ .replaceAll("<", "&lt;")
26
+ .replaceAll(">", "&gt;");
27
+ const outerPolicy = policy.replace("frame-src 'none'", "frame-src about:");
28
+ return `<!doctype html><meta http-equiv="Content-Security-Policy" content="${outerPolicy}"><style>html,body,iframe{margin:0;width:100%;height:100%;border:0}body{overflow:hidden}</style><iframe title="HTML" sandbox="" referrerpolicy="no-referrer" srcdoc="${escaped}"></iframe>`;
29
+ }
30
+
31
+ export function svgImageSource(source: string): string | null {
32
+ if (source.length > MAX_PREVIEW_LENGTH) return null;
33
+ // SVG image mode disables scripts and external resources, unlike inserting SVG into the host DOM.
34
+ const image = source.replace(/<svg\b([^>]*)>/i, (tag: string, attributes: string) =>
35
+ /\bxmlns\s*=/.test(attributes) ? tag : `<svg xmlns="http://www.w3.org/2000/svg"${attributes}>`,
36
+ );
37
+ try {
38
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(image)}`;
39
+ } catch {
40
+ // A partial UTF-16 pair in a streamed/model-supplied string must not crash the message tree.
41
+ return null;
42
+ }
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
+ });