@vetta-org/theme-ui 0.1.1 → 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 +733 -5
  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,93 @@
1
+ import remarkMath from "remark-math";
2
+ import { remarkMathAliases } from "./math-syntax";
3
+
4
+ interface MarkdownNode {
5
+ type: string;
6
+ value?: string;
7
+ lang?: string;
8
+ children?: MarkdownNode[];
9
+ position?: { start: { offset?: number }; end: { offset?: number } };
10
+ data?: { hName: string; hProperties: Record<string, string> };
11
+ }
12
+
13
+ /** Keep raw markup out of the host DOM. Only standalone HTML and complete SVG become previews. */
14
+ export function remarkRichMarkup() {
15
+ return (tree: MarkdownNode, file: { value: unknown }): void => {
16
+ const markdown = String(file.value);
17
+ function visit(parent: MarkdownNode) {
18
+ const children = parent.children;
19
+ if (!children) return;
20
+ for (let index = 0; index < children.length; index++) {
21
+ const node = children[index];
22
+ if (node.type === "inlineMath") {
23
+ const start = node.position?.start.offset;
24
+ const end = node.position?.end.offset;
25
+ const raw = start === undefined || end === undefined ? "" : markdown.slice(start, end);
26
+ // Single-dollar delimiters follow the common no-whitespace/no-following-digit rule.
27
+ if (
28
+ /^\$(?!\$)/.test(raw) &&
29
+ (/^\$\s|\s\$$/.test(raw) || /\d/.test(markdown[end ?? markdown.length] ?? ""))
30
+ ) {
31
+ children[index] = { type: "text", value: raw, position: node.position };
32
+ continue;
33
+ }
34
+ }
35
+ if (node.type !== "html") {
36
+ visit(node);
37
+ continue;
38
+ }
39
+ const source = node.value ?? "";
40
+ if (parent.type === "root" && /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(source)) {
41
+ const start = node.position?.start.offset;
42
+ if (start !== undefined) {
43
+ const rest = markdown.slice(start);
44
+ const closing = /<\/html\s*>/i.exec(rest);
45
+ if (closing) {
46
+ const end = start + closing.index + closing[0].length;
47
+ let count = 1;
48
+ while (
49
+ index + count < children.length &&
50
+ (children[index + count].position?.start.offset ?? end) < end
51
+ )
52
+ count++;
53
+ const through = children[index + count - 1].position?.end.offset ?? end;
54
+ children.splice(index, count, {
55
+ type: "code",
56
+ lang: "html",
57
+ value: markdown.slice(start, through),
58
+ });
59
+ continue;
60
+ }
61
+ }
62
+ }
63
+ if (/^\s*<svg[\s>]/i.test(source)) {
64
+ const start = node.position?.start.offset;
65
+ if (start === undefined) continue;
66
+ const closing = /<\/svg\s*>/i.exec(markdown.slice(start));
67
+ if (!closing) continue;
68
+ const end = start + closing.index + closing[0].length;
69
+ let count = 1;
70
+ while (index + count < children.length && (children[index + count].position?.start.offset ?? end) < end)
71
+ count++;
72
+ // Slice the source once: text inside SVG may have been parsed as Markdown,
73
+ // and rescanning an ever-growing concatenation would be quadratic.
74
+ if ((children[index + count - 1].position?.end.offset ?? 0) <= end) {
75
+ children.splice(index, count, {
76
+ type: "richSvg",
77
+ data: { hName: "vetta-svg", hProperties: { source: markdown.slice(start, end) } },
78
+ children: [],
79
+ });
80
+ }
81
+ } else if (
82
+ parent.type === "root" &&
83
+ /^\s*(?:<!doctype\s+html|<(?:html|div|section|article|main|style|table|body|head)[\s>])/i.test(source)
84
+ ) {
85
+ children[index] = { type: "code", lang: "html", value: source };
86
+ }
87
+ }
88
+ }
89
+ visit(tree);
90
+ };
91
+ }
92
+
93
+ export const richRemarkPlugins = [remarkMath, remarkMathAliases, remarkRichMarkup];
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { splitStableMarkdownBlocks } from "./stable-blocks";
3
+
4
+ describe("splitStableMarkdownBlocks", () => {
5
+ it.each(["$$\n```\nformula\n```\n$$", "<html>\n```\npage\n```\n</html>"])(
6
+ "rich blocks preserve parser context and previously frozen prefixes: %s",
7
+ (rich) => {
8
+ const prefix = "```ts\nconst x = 1;\n```\n";
9
+ const text = `${prefix}\n${rich}\nAfter`;
10
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [prefix], tail: `\n${rich}\nAfter` });
11
+ },
12
+ );
13
+ it("空文本没有已提交块", () => {
14
+ expect(splitStableMarkdownBlocks("")).toEqual({ committed: [], tail: "" });
15
+ });
16
+
17
+ it("只有一段未结束的段落全部留在 tail", () => {
18
+ expect(splitStableMarkdownBlocks("Hello there")).toEqual({
19
+ committed: [],
20
+ tail: "Hello there",
21
+ });
22
+ });
23
+
24
+ it("空行不提交段落,避免拆开松散列表和缩进代码", () => {
25
+ const text = "First paragraph.\n\nSecond";
26
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
27
+ });
28
+
29
+ it("松散有序列表整段留在 tail", () => {
30
+ const text = "1. foo\n\n2. bar\n";
31
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
32
+ });
33
+
34
+ it("闭合围栏后面没有正文时整块留在 tail", () => {
35
+ const fence = "```js\nconst a = 1;\n```";
36
+ expect(splitStableMarkdownBlocks(fence)).toEqual({ committed: [], tail: fence });
37
+ });
38
+
39
+ it("闭合围栏后面还有正文时提交围栏", () => {
40
+ const text = "```js\nconst a = 1;\n```\n\nmore";
41
+ expect(splitStableMarkdownBlocks(text)).toEqual({
42
+ committed: ["```js\nconst a = 1;\n```\n"],
43
+ tail: "\nmore",
44
+ });
45
+ });
46
+
47
+ it("未闭合围栏整段留在 tail,即使中间有空行", () => {
48
+ const text = "```js\nconst a = 1;\n\nconst b = 2;\n";
49
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
50
+ });
51
+
52
+ it("围栏闭合行后若还有非空白字符则不算闭合", () => {
53
+ const text = "```js\nconst a = 1;\n``` notclose\nstill in fence";
54
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
55
+ });
56
+
57
+ it("info string 含反引号的行不能当作开围栏", () => {
58
+ const text = "```js`oops\nnot a fence";
59
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
60
+ });
61
+
62
+ it("波浪线围栏的 info string 允许含波浪线", () => {
63
+ const text = "~~~ a~b\ncode\n~~~\n\nafter";
64
+ expect(splitStableMarkdownBlocks(text)).toEqual({
65
+ committed: ["~~~ a~b\ncode\n~~~\n"],
66
+ tail: "\nafter",
67
+ });
68
+ });
69
+
70
+ it("波浪线围栏与反引号围栏互不闭合", () => {
71
+ const text = "~~~\ncode\n```\nstill\n~~~\n\nafter";
72
+ expect(splitStableMarkdownBlocks(text)).toEqual({
73
+ committed: ["~~~\ncode\n```\nstill\n~~~\n"],
74
+ tail: "\nafter",
75
+ });
76
+ });
77
+
78
+ it("列表项里的缩进围栏不提交,避免把有序列表拆成两份文档", () => {
79
+ const text = "1. first\n ```js\n x\n ```\n2. second\n";
80
+ expect(splitStableMarkdownBlocks(text)).toEqual({ committed: [], tail: text });
81
+ });
82
+
83
+ it("CRLF 闭合行仍能提交顶层围栏", () => {
84
+ const text = "```js\r\nconst a = 1;\r\n```\r\n\r\nmore";
85
+ expect(splitStableMarkdownBlocks(text)).toEqual({
86
+ committed: ["```js\r\nconst a = 1;\r\n```\r\n"],
87
+ tail: "\r\nmore",
88
+ });
89
+ });
90
+ });
@@ -0,0 +1,124 @@
1
+ export interface StableMarkdownSplit {
2
+ readonly committed: readonly string[];
3
+ readonly tail: string;
4
+ }
5
+
6
+ interface FenceMarker {
7
+ readonly char: "`" | "~";
8
+ readonly len: number;
9
+ readonly markerEnd: number;
10
+ readonly indent: number;
11
+ }
12
+
13
+ function stripLineEnding(line: string): string {
14
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
15
+ }
16
+
17
+ function readFenceMarker(line: string): FenceMarker | null {
18
+ let index = 0;
19
+ while (index < 3 && line[index] === " ") index += 1;
20
+ const char = line[index];
21
+ if (char !== "`" && char !== "~") return null;
22
+ let len = 0;
23
+ while (line[index + len] === char) len += 1;
24
+ if (len < 3) return null;
25
+ return { char, len, indent: index, markerEnd: index + len };
26
+ }
27
+
28
+ function isFenceOpeningLine(line: string): FenceMarker | null {
29
+ const fence = readFenceMarker(line);
30
+ if (!fence) return null;
31
+ // CommonMark:只有反引号围栏的 info string 不能含反引号,波浪线围栏的 info string 可以含 `~`。
32
+ if (fence.char === "`" && line.includes("`", fence.markerEnd)) return null;
33
+ return fence;
34
+ }
35
+
36
+ function isFenceClosingLine(line: string, fenceChar: FenceMarker["char"], fenceLen: number): boolean {
37
+ const fence = readFenceMarker(line);
38
+ if (!fence || fence.char !== fenceChar || fence.len < fenceLen) return false;
39
+ for (let index = fence.markerEnd; index < line.length; index += 1) {
40
+ const char = line[index];
41
+ if (char !== " " && char !== "\t") return false;
42
+ }
43
+ return true;
44
+ }
45
+
46
+ /**
47
+ * Split append-only markdown so completed top-level fenced blocks can be frozen.
48
+ *
49
+ * Only an unindented closed code fence followed by more text is committed.
50
+ * Indented fences stay in the tail so list items that wrap a code block are not
51
+ * split into two documents (the second list would restart at 1). Blank lines
52
+ * are not terminators. Because only whole top-level fences are committed, the
53
+ * committed blocks of a prefix are a prefix of the committed blocks of any
54
+ * append-only extension, so the caller keeps the split after streaming ends
55
+ * instead of re-parsing the whole document (which would remount every node).
56
+ */
57
+ export function splitStableMarkdownBlocks(text: string): StableMarkdownSplit {
58
+ if (text.length === 0) return { committed: [], tail: "" };
59
+
60
+ const committed: string[] = [];
61
+ let start = 0;
62
+ let index = 0;
63
+ let inFence = false;
64
+ let fenceChar: FenceMarker["char"] = "`";
65
+ let fenceLen = 0;
66
+ let commitOnClose = false;
67
+ let literalEnd: RegExp | null = null;
68
+
69
+ const commitThrough = (end: number): void => {
70
+ if (end <= start || end > text.length) return;
71
+ const block = text.slice(start, end);
72
+ if (block.trim().length === 0) {
73
+ start = end;
74
+ return;
75
+ }
76
+ committed.push(block);
77
+ start = end;
78
+ };
79
+
80
+ while (index < text.length) {
81
+ const lineStart = index;
82
+ const newline = text.indexOf("\n", index);
83
+ const lineEnd = newline === -1 ? text.length : newline + 1;
84
+ const line = stripLineEnding(text.slice(lineStart, newline === -1 ? text.length : newline));
85
+
86
+ if (inFence) {
87
+ if (isFenceClosingLine(line, fenceChar, fenceLen)) {
88
+ inFence = false;
89
+ if (commitOnClose && lineEnd < text.length) commitThrough(lineEnd);
90
+ commitOnClose = false;
91
+ }
92
+ index = lineEnd;
93
+ continue;
94
+ }
95
+
96
+ // Do not freeze fence-looking text inside raw documents or display formulas.
97
+ // Track this while scanning so previously committed prefixes remain stable.
98
+ if (literalEnd) {
99
+ if (literalEnd.test(line)) literalEnd = null;
100
+ index = lineEnd;
101
+ continue;
102
+ }
103
+ const math = /^ {0,3}(\${2,})\s*$/.exec(line);
104
+ const html = /^ {0,3}<(svg|html|script|style|div|section|article|table|body|head)(?:\s|>)/i.exec(line);
105
+ if (math || html || /^ {0,3}<!doctype\s+html/i.test(line)) {
106
+ literalEnd = math
107
+ ? new RegExp(`^ {0,3}\\${"$"}{${math[1].length},}\\s*$`)
108
+ : new RegExp(`</${html?.[1] ?? "html"}\\s*>`, "i");
109
+ if (!math && literalEnd.test(line)) literalEnd = null;
110
+ index = lineEnd;
111
+ continue;
112
+ }
113
+ const opening = isFenceOpeningLine(line);
114
+ if (opening) {
115
+ inFence = true;
116
+ fenceChar = opening.char;
117
+ fenceLen = opening.len;
118
+ commitOnClose = opening.indent === 0;
119
+ }
120
+ index = lineEnd;
121
+ }
122
+
123
+ return { committed, tail: text.slice(start) };
124
+ }
@@ -0,0 +1,297 @@
1
+ /**
2
+ * 流式文本的「匀速放出」节奏。
3
+ *
4
+ * - 显示单位是片:按最近到达速率算出本 tick 该放多少字,再对齐到词边界(拉丁词不从中间切开,
5
+ * CJK 逐字即边界),快时是密而匀的流,慢时自然放慢,不再按积压成批砸出。
6
+ * - 放出由宿主的增量刷新驱动(每次新文本到达放一片),没有新文本时由 100ms 兜底 tick 收尾,
7
+ * 页面每秒的更新次数与增量刷新一致,不多出帧。
8
+ * - 未闭合的行内语法(`[链接](…)`、行内代码、加粗)先扣着不放,闭合后整体出现,
9
+ * 避免先看到原始标记再翻转成徽标;扣太久或太长就当普通文字放出。
10
+ * - 尾部未写完的词先不显示;停顿太久就不再等。
11
+ * - 分段给 rehype 用的短语切分(`splitStreamingSegments`)保持按标点切,供「最新短语略暗」使用。
12
+ */
13
+
14
+ /** 放出 tick 的兜底间隔,与宿主增量刷新同周期(100ms)。 */
15
+ export const REVEAL_TICK_MS = 100;
16
+ /** 追平系数:放出速率略高于到达速率,积压不会无限增长。 */
17
+ const CATCH_UP_RATIO = 1.15;
18
+ /** 允许的最大滞后:积压超过这么多毫秒的量时加速追平。 */
19
+ const MAX_LAG_MS = 1200;
20
+ /** 积压超过这么多字符(切回正在流式的会话)直接对齐,不追。 */
21
+ const SNAP_BACKLOG_CHARS = 1500;
22
+ /** 没有速率样本时的默认放出速率(字符/毫秒):约 60 字/秒。 */
23
+ export const DEFAULT_RATE_PER_MS = 0.06;
24
+ /** 速率下限,慢速流也保持可见的推进。 */
25
+ const MIN_RATE_PER_MS = 0.02;
26
+ /** 未闭合行内语法最多扣这么久 / 这么长,之后当普通文字放出。 */
27
+ export const HOLD_MAX_MS = 800;
28
+ const HOLD_MAX_CHARS = 240;
29
+ /** 无标点长片段的切分上限(UTF-16 code units),供 rehype 分段。 */
30
+ const MAX_PHRASE_LENGTH = 48;
31
+ /** 按上限切分时,优先在这个长度之后的最后一个空白处断开。 */
32
+ const MIN_SOFT_BREAK_LENGTH = 16;
33
+
34
+ /** 最后一个片放出后,等这么久再撤掉「最新短语略暗」的包裹类。 */
35
+ export const STREAMING_SETTLE_MS = 150;
36
+ /**
37
+ * 流还没结束、但已全部放出且这么久没有新文本时,也撤掉暗色:正文写完到回合结束事件之间常有
38
+ * 近一秒的空档,不能让末尾短语一直暗着。新文本到达时会重新挂上包裹类。
39
+ */
40
+ export const STREAMING_IDLE_SETTLE_MS = 300;
41
+ /** 尾部未完成的词超过这么久没有新内容,就不再等,直接放出,避免模型停顿时文字「卡住」。 */
42
+ export const STREAMING_STALL_FLUSH_MS = 800;
43
+
44
+ const CJK_BREAK = new Set([",", "。", ";", ":", "!", "?", "、", "…"]);
45
+ const CJK_TRAILING = new Set([",", "。", ";", ":", "!", "?", "、", "…", "”", "’", ")", "」", "』", "》", "】"]);
46
+ const LATIN_BREAK = new Set([",", ".", ";", ":", "!", "?"]);
47
+ const WHITESPACE = /\s/;
48
+
49
+ function isHighSurrogate(code: number): boolean {
50
+ return code >= 0xd800 && code <= 0xdbff;
51
+ }
52
+
53
+ /**
54
+ * 从 `from` 开始的下一个短语的结束位置;尾部还没写完时返回 null。
55
+ * `final` 表示文本不会再增长,此时末尾剩余内容也算一个完整短语。
56
+ */
57
+ export function nextPhraseEnd(text: string, from: number, final: boolean): number | null {
58
+ const length = text.length;
59
+ if (from >= length) return null;
60
+
61
+ for (let index = from; index < length; index++) {
62
+ const char = text[index] as string;
63
+ if (char === "\n") return index + 1;
64
+
65
+ if (CJK_BREAK.has(char)) {
66
+ let end = index + 1;
67
+ while (end < length && CJK_TRAILING.has(text[end] as string)) end++;
68
+ return end;
69
+ }
70
+
71
+ // 英文标点只有后面跟着空白才算断句:`3.14`、`e.g.x`、URL 里的点都不断开;
72
+ // 标点正好在末尾时还不知道后面是什么,先当作未完成。
73
+ if (LATIN_BREAK.has(char)) {
74
+ if (index + 1 < length) {
75
+ if (WHITESPACE.test(text[index + 1] as string)) return index + 1;
76
+ } else if (!final) {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ if (index + 1 - from >= MAX_PHRASE_LENGTH) {
82
+ for (let back = index; back >= from + MIN_SOFT_BREAK_LENGTH; back--) {
83
+ if (WHITESPACE.test(text[back] as string)) return back;
84
+ }
85
+ return isHighSurrogate(text.charCodeAt(index)) ? index + 2 : index + 1;
86
+ }
87
+ }
88
+
89
+ return final ? length : null;
90
+ }
91
+
92
+ /** 把一段文本切成可逐个淡入的短语;拼接结果恒等于输入,文本末尾总是结束最后一个短语。 */
93
+ export function splitStreamingSegments(value: string): string[] {
94
+ const segments: string[] = [];
95
+ for (let start = 0; start < value.length; ) {
96
+ const end = nextPhraseEnd(value, start, true) ?? value.length;
97
+ segments.push(value.slice(start, end));
98
+ start = end;
99
+ }
100
+ return segments;
101
+ }
102
+
103
+ function isWordChar(char: string | undefined): boolean {
104
+ return char !== undefined && /[\p{L}\p{N}_]/u.test(char) && !isCjk(char);
105
+ }
106
+
107
+ function isCjk(char: string): boolean {
108
+ const code = char.codePointAt(0) ?? 0;
109
+ return (
110
+ (code >= 0x3040 && code <= 0x30ff) ||
111
+ (code >= 0x3400 && code <= 0x4dbf) ||
112
+ (code >= 0x4e00 && code <= 0x9fff) ||
113
+ (code >= 0xac00 && code <= 0xd7af) ||
114
+ (code >= 0xf900 && code <= 0xfaff) ||
115
+ (code >= 0xff00 && code <= 0xffef)
116
+ );
117
+ }
118
+
119
+ /**
120
+ * 把位置对齐到词边界:不在拉丁词 / 数字中间切开,不切开代理对;CJK 逐字即边界。
121
+ * 只向后推进,最多推到文本末尾。
122
+ */
123
+ export function snapToTokenBoundary(text: string, index: number): number {
124
+ let end = Math.min(Math.max(index, 0), text.length);
125
+ if (end > 0 && isHighSurrogate(text.charCodeAt(end - 1))) end += 1;
126
+ while (end < text.length && isWordChar(text[end - 1]) && isWordChar(text[end])) end += 1;
127
+ return end;
128
+ }
129
+
130
+ /**
131
+ * Temporarily hold incomplete inline syntax on the current line. This is a
132
+ * presentation heuristic, not a Markdown parser; timeout and final flush preserve source.
133
+ */
134
+ export function holdBackUnclosedInline(text: string, end: number): number {
135
+ const lineStart = text.lastIndexOf("\n", end - 1) + 1;
136
+ let hold = end;
137
+ let backtickStart = -1;
138
+ let backtickLength = 0;
139
+ let mathStart = -1;
140
+ let mathLength = 0;
141
+ let mathCloser: string | null = null;
142
+ let strongStart = -1;
143
+ let linkStart = -1;
144
+ let linkTextClosed = false;
145
+ let destinationDepth = 0;
146
+ for (let index = lineStart; index < end; index++) {
147
+ const char = text[index];
148
+ if (char === "\\") {
149
+ const next = text[index + 1];
150
+ if (backtickStart === -1 && !linkTextClosed) {
151
+ if (mathStart !== -1 && next === mathCloser) {
152
+ mathStart = -1;
153
+ mathCloser = null;
154
+ } else if (mathStart === -1 && (next === "(" || next === "[")) {
155
+ mathStart = index;
156
+ mathLength = 0;
157
+ mathCloser = next === "(" ? ")" : "]";
158
+ }
159
+ }
160
+ index += 1;
161
+ continue;
162
+ }
163
+ if (char === "`") {
164
+ let length = 1;
165
+ while (index + length < end && text[index + length] === "`") length++;
166
+ if (backtickStart !== -1) {
167
+ if (length === backtickLength) backtickStart = -1;
168
+ } else if (mathStart === -1) {
169
+ backtickStart = index;
170
+ backtickLength = length;
171
+ }
172
+ index += length - 1;
173
+ continue;
174
+ }
175
+ if (backtickStart !== -1) continue;
176
+ if (char === "$" && !linkTextClosed) {
177
+ let length = 1;
178
+ while (index + length < end && text[index + length] === "$") length++;
179
+ if (mathStart !== -1) {
180
+ if (length === mathLength) mathStart = -1;
181
+ } else {
182
+ mathStart = index;
183
+ mathLength = length;
184
+ }
185
+ index += length - 1;
186
+ continue;
187
+ }
188
+ if (mathStart !== -1) continue;
189
+ if (char === "*" && index + 1 < end && text[index + 1] === "*") {
190
+ strongStart = strongStart === -1 ? index : -1;
191
+ index += 1;
192
+ continue;
193
+ }
194
+ if (linkStart === -1) {
195
+ if (char === "[") linkStart = index;
196
+ continue;
197
+ }
198
+ if (!linkTextClosed) {
199
+ if (char === "]") {
200
+ if (index + 1 === end) continue;
201
+ if (text[index + 1] === "(") {
202
+ linkTextClosed = true;
203
+ destinationDepth = 1;
204
+ index += 1;
205
+ } else {
206
+ // `[…]` 后面不是 `(`:不是链接,从下一个字符重新找。
207
+ linkStart = -1;
208
+ }
209
+ }
210
+ continue;
211
+ }
212
+ if (char === "(") destinationDepth++;
213
+ if (char === ")" && --destinationDepth === 0) {
214
+ linkStart = -1;
215
+ linkTextClosed = false;
216
+ }
217
+ }
218
+ // `[` 后面紧跟着文本末尾时也可能是链接开头;`]` 刚到、`(` 未到的瞬间同样先扣着。
219
+ if (linkStart !== -1 && (linkTextClosed || end - linkStart < HOLD_MAX_CHARS)) {
220
+ const start = text[linkStart - 1] === "!" ? linkStart - 1 : linkStart;
221
+ hold = Math.min(hold, start);
222
+ }
223
+ if (backtickStart !== -1) hold = Math.min(hold, backtickStart);
224
+ if (mathStart !== -1) hold = Math.min(hold, mathStart);
225
+ if (strongStart !== -1) hold = Math.min(hold, strongStart);
226
+ return hold;
227
+ }
228
+
229
+ export interface RevealPlanInput {
230
+ readonly text: string;
231
+ /** 已显示到的位置。 */
232
+ readonly revealed: number;
233
+ /** 文本不会再增长(流已结束)。 */
234
+ readonly final: boolean;
235
+ /** 最近的到达速率(字符/毫秒)。 */
236
+ readonly ratePerMs: number;
237
+ /** 距上次放出经过的毫秒数。 */
238
+ readonly elapsedMs: number;
239
+ /** 尾部停顿太久:未写完的词也放出。 */
240
+ readonly stalled: boolean;
241
+ /** 当前扣留已经持续的毫秒数;超过上限就不再扣。 */
242
+ readonly heldMs: number;
243
+ }
244
+
245
+ export interface RevealStep {
246
+ /** 本次应显示到的位置。 */
247
+ readonly end: number;
248
+ /** 本次因未闭合的行内语法而少放了内容;宿主据此计时,超时后放开。 */
249
+ readonly held: boolean;
250
+ }
251
+
252
+ /** 规划下一次放出;没有可放的内容时返回 null。 */
253
+ export function planReveal(input: RevealPlanInput): RevealStep | null {
254
+ const { text, revealed, final, stalled, heldMs } = input;
255
+ const backlog = text.length - revealed;
256
+ if (backlog <= 0) return null;
257
+ // 流已结束:剩下的一次放完。按速率再分几个 tick 只会让结尾拖成慢动作,用户看到的是「卡一下」。
258
+ if (final) return { end: text.length, held: false };
259
+
260
+ const rate = Math.max(MIN_RATE_PER_MS, input.ratePerMs);
261
+ const elapsed = Math.max(0, input.elapsedMs);
262
+ let budget: number;
263
+ if (backlog >= SNAP_BACKLOG_CHARS) {
264
+ budget = backlog;
265
+ } else {
266
+ budget = rate * elapsed * CATCH_UP_RATIO;
267
+ const maxLag = rate * MAX_LAG_MS;
268
+ if (backlog > maxLag) budget = Math.max(budget, backlog - maxLag / 2);
269
+ }
270
+ let end = snapToTokenBoundary(text, revealed + Math.max(1, Math.ceil(budget)));
271
+
272
+ // 尾部未写完的词先不显示:等它写完,或停顿太久。
273
+ if (!stalled && end === text.length && isWordChar(text[end - 1])) {
274
+ let back = end;
275
+ while (back > revealed && isWordChar(text[back - 1])) back -= 1;
276
+ end = back;
277
+ }
278
+
279
+ let held = false;
280
+ if (heldMs < HOLD_MAX_MS) {
281
+ const safe = holdBackUnclosedInline(text, end);
282
+ if (safe < end && end - safe < HOLD_MAX_CHARS) {
283
+ // The closing delimiter may already have arrived beyond this tick's character
284
+ // budget. Reveal the complete inline construct instead of timing out into raw markup.
285
+ const lookahead = text.slice(safe, safe + HOLD_MAX_CHARS).split("\n", 1)[0] ?? "";
286
+ for (let candidate = end - safe + 1; candidate <= lookahead.length; candidate++) {
287
+ if (holdBackUnclosedInline(lookahead, candidate) === candidate) {
288
+ return { end: safe + candidate, held: false };
289
+ }
290
+ }
291
+ end = Math.max(safe, revealed);
292
+ held = true;
293
+ }
294
+ }
295
+ if (end <= revealed) return held ? { end: revealed, held: true } : null;
296
+ return { end, held };
297
+ }
@@ -0,0 +1,57 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { HastElement, HastRoot, HastText } from "./nodes";
3
+ import { rehypeStreamingChunks } from "./streaming";
4
+
5
+ function text(value: string): HastText {
6
+ return { type: "text", value } as HastText;
7
+ }
8
+
9
+ function paragraph(...children: Array<HastText | HastElement>): HastElement {
10
+ return { type: "element", tagName: "p", properties: {}, children } as HastElement;
11
+ }
12
+
13
+ function chunkClasses(root: HastRoot): string[][] {
14
+ const out: string[][] = [];
15
+ const walk = (node: HastRoot | HastElement): void => {
16
+ for (const child of node.children) {
17
+ if (child.type !== "element") continue;
18
+ const className = (child.properties?.className as string[] | undefined) ?? [];
19
+ if (className.includes("streaming-chunk")) out.push(className);
20
+ walk(child);
21
+ }
22
+ };
23
+ walk(root);
24
+ return out;
25
+ }
26
+
27
+ describe("rehypeStreamingChunks", () => {
28
+ test("marks only the newest two phrases so brightness follows the reveal cadence without animation", () => {
29
+ const tree = { type: "root", children: [paragraph(text("One, two, three, four."))] } as HastRoot;
30
+ rehypeStreamingChunks()(tree);
31
+ expect(chunkClasses(tree)).toEqual([
32
+ ["streaming-chunk"],
33
+ ["streaming-chunk"],
34
+ ["streaming-chunk", "streaming-chunk-recent"],
35
+ ["streaming-chunk", "streaming-chunk-latest"],
36
+ ]);
37
+ });
38
+
39
+ test("a single phrase is the latest one and there is no recent phrase", () => {
40
+ const tree = { type: "root", children: [paragraph(text("Hello."))] } as HastRoot;
41
+ rehypeStreamingChunks()(tree);
42
+ expect(chunkClasses(tree)).toEqual([["streaming-chunk", "streaming-chunk-latest"]]);
43
+ });
44
+
45
+ test("the newest phrase is found across block boundaries", () => {
46
+ const tree = {
47
+ type: "root",
48
+ children: [paragraph(text("First, second.")), paragraph(text("Third."))],
49
+ } as HastRoot;
50
+ rehypeStreamingChunks()(tree);
51
+ expect(chunkClasses(tree)).toEqual([
52
+ ["streaming-chunk"],
53
+ ["streaming-chunk", "streaming-chunk-recent"],
54
+ ["streaming-chunk", "streaming-chunk-latest"],
55
+ ]);
56
+ });
57
+ });