@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
@@ -1,135 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { type FocusContainmentRoot, shouldCloseEmptyApiKeyEditor } from "./shouldCloseEmptyApiKeyEditor";
3
-
4
- /** 轻量 contains 替身,不依赖任何 DOM 环境。 */
5
- function makeRoot(contained: object[]): FocusContainmentRoot {
6
- const set = new Set(contained);
7
- return {
8
- contains(node: object | null): boolean {
9
- return node != null && set.has(node);
10
- },
11
- };
12
- }
13
-
14
- describe("shouldCloseEmptyApiKeyEditor", () => {
15
- const outside = { id: "outside" };
16
- const insideButton = { id: "inside-btn" };
17
- const inputEl = { id: "input" };
18
-
19
- it("closes when draft is empty and focus left the editor", () => {
20
- const root = makeRoot([inputEl, insideButton]);
21
- expect(
22
- shouldCloseEmptyApiKeyEditor({
23
- draftKey: "",
24
- saving: false,
25
- editorRoot: root,
26
- relatedTarget: outside,
27
- activeElement: outside,
28
- }),
29
- ).toBe(true);
30
- });
31
-
32
- it("treats whitespace-only draft as empty and closes", () => {
33
- const root = makeRoot([inputEl]);
34
- expect(
35
- shouldCloseEmptyApiKeyEditor({
36
- draftKey: " \t ",
37
- saving: false,
38
- editorRoot: root,
39
- relatedTarget: null,
40
- activeElement: outside,
41
- }),
42
- ).toBe(true);
43
- });
44
-
45
- it("keeps open when draft has content even if focus left", () => {
46
- const root = makeRoot([inputEl]);
47
- expect(
48
- shouldCloseEmptyApiKeyEditor({
49
- draftKey: "sk-abc",
50
- saving: false,
51
- editorRoot: root,
52
- relatedTarget: null,
53
- activeElement: outside,
54
- }),
55
- ).toBe(false);
56
- });
57
-
58
- it("keeps open while saving", () => {
59
- const root = makeRoot([inputEl]);
60
- expect(
61
- shouldCloseEmptyApiKeyEditor({
62
- draftKey: "",
63
- saving: true,
64
- editorRoot: root,
65
- relatedTarget: null,
66
- activeElement: outside,
67
- }),
68
- ).toBe(false);
69
- });
70
-
71
- it("keeps open when relatedTarget stays inside the editor actions", () => {
72
- const root = makeRoot([inputEl, insideButton]);
73
- expect(
74
- shouldCloseEmptyApiKeyEditor({
75
- draftKey: "",
76
- saving: false,
77
- editorRoot: root,
78
- relatedTarget: insideButton,
79
- activeElement: insideButton,
80
- }),
81
- ).toBe(false);
82
- });
83
-
84
- it("keeps open when relatedTarget is null but activeElement is still inside", () => {
85
- // 常见:点同行取消/复制时 relatedTarget=null,但焦点实际落到了区内按钮。
86
- const root = makeRoot([inputEl, insideButton]);
87
- expect(
88
- shouldCloseEmptyApiKeyEditor({
89
- draftKey: "",
90
- saving: false,
91
- editorRoot: root,
92
- relatedTarget: null,
93
- activeElement: insideButton,
94
- }),
95
- ).toBe(false);
96
- });
97
-
98
- it("closes when relatedTarget is null and activeElement is outside", () => {
99
- const root = makeRoot([inputEl, insideButton]);
100
- expect(
101
- shouldCloseEmptyApiKeyEditor({
102
- draftKey: "",
103
- saving: false,
104
- editorRoot: root,
105
- relatedTarget: null,
106
- activeElement: outside,
107
- }),
108
- ).toBe(true);
109
- });
110
-
111
- it("closes when relatedTarget is null and activeElement is null", () => {
112
- const root = makeRoot([inputEl]);
113
- expect(
114
- shouldCloseEmptyApiKeyEditor({
115
- draftKey: "",
116
- saving: false,
117
- editorRoot: root,
118
- relatedTarget: null,
119
- activeElement: null,
120
- }),
121
- ).toBe(true);
122
- });
123
-
124
- it("closes when editorRoot is missing (unmounted mid-blur)", () => {
125
- expect(
126
- shouldCloseEmptyApiKeyEditor({
127
- draftKey: "",
128
- saving: false,
129
- editorRoot: null,
130
- relatedTarget: null,
131
- activeElement: null,
132
- }),
133
- ).toBe(true);
134
- });
135
- });
@@ -1,40 +0,0 @@
1
- /**
2
- * 可做 contains 判定的编辑区根(浏览器里是 HTMLElement,测试里可替身)。
3
- * 不绑 DOM 全局,便于 node 单测。
4
- */
5
- export interface FocusContainmentRoot {
6
- contains(node: object | null): boolean;
7
- }
8
-
9
- /**
10
- * 预设服务商行内 API Key 编辑:空内容失焦是否应收起。
11
- *
12
- * 不用 relatedTarget 单点判定——点按钮时部分环境 relatedTarget 为 null,
13
- * 需结合 editorRoot.contains(activeElement) 判断焦点是否仍在编辑区内。
14
- */
15
- export function shouldCloseEmptyApiKeyEditor(input: {
16
- readonly draftKey: string;
17
- readonly saving: boolean;
18
- readonly editorRoot: FocusContainmentRoot | null;
19
- /** blur 的 relatedTarget;点到非 focusable 时经常是 null。 */
20
- readonly relatedTarget: object | null;
21
- /** 失焦后已落定的 activeElement(可在 microtask 里再读)。 */
22
- readonly activeElement: object | null;
23
- }): boolean {
24
- if (input.saving) return false;
25
- if (input.draftKey.trim().length > 0) return false;
26
-
27
- const root = input.editorRoot;
28
- if (!root) return true;
29
-
30
- if (input.relatedTarget != null && root.contains(input.relatedTarget)) {
31
- return false;
32
- }
33
-
34
- // relatedTarget 不可靠时,以已落定的 activeElement 为准。
35
- if (input.activeElement != null && root.contains(input.activeElement)) {
36
- return false;
37
- }
38
-
39
- return true;
40
- }
@@ -1,195 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- activityMatrixHeightPx,
4
- buildActivityColumns,
5
- buildAreaGeometry,
6
- buildHoverZones,
7
- buildSmoothPath,
8
- fitCurveColumns,
9
- ROLLING_WINDOW_DAYS,
10
- trimLeadingIdleColumns,
11
- type UsageSeriesPointLike,
12
- } from "./token-activity";
13
-
14
- function series(days: number, tokensPerDay = 100): UsageSeriesPointLike[] {
15
- return Array.from({ length: days }, (_, i) => {
16
- const d = new Date(2025, 0, 1 + i);
17
- const iso = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
18
- return { date: iso, tokens: tokensPerDay };
19
- });
20
- }
21
-
22
- describe("buildActivityColumns(rolling)", () => {
23
- it("窗口滚出后回落,不像累计那样只增不减", () => {
24
- // 第 1 天 1000,之后全 0:30 天窗口内保持 1000,第 31 天该笔用量滚出
25
- const points = series(40, 0).map((p, i) => ({ ...p, tokens: i === 0 ? 1000 : 0 }));
26
- const columns = buildActivityColumns(points, "rolling");
27
- expect(columns[0]?.tokens).toBe(1000);
28
- expect(columns[ROLLING_WINDOW_DAYS - 1]?.tokens).toBe(1000);
29
- expect(columns[ROLLING_WINDOW_DAYS]?.tokens).toBe(0);
30
- expect(columns.at(-1)?.tokens).toBe(0);
31
- });
32
-
33
- it("按自然日补齐缺失日期,稀疏数据不会被压缩成「最近 30 条记录」", () => {
34
- // 只有首尾两天有记录,间隔 60 天:窗口早已滚过首日
35
- const points: UsageSeriesPointLike[] = [
36
- { date: "2025-01-01", tokens: 500 },
37
- { date: "2025-03-02", tokens: 700 },
38
- ];
39
- const columns = buildActivityColumns(points, "rolling");
40
- expect(columns).toHaveLength(61);
41
- expect(columns.at(-1)?.tokens).toBe(700);
42
- });
43
-
44
- it("带上窗口起始日,供提示条展示区间", () => {
45
- const columns = buildActivityColumns(series(45), "rolling");
46
- expect(columns[0]?.windowStart).toBe(columns[0]?.date);
47
- const last = columns.at(-1)!;
48
- expect(last.windowStart).toBe(columns.at(-ROLLING_WINDOW_DAYS)?.date);
49
- expect(last.tokens).toBe(100 * ROLLING_WINDOW_DAYS);
50
- });
51
-
52
- it("每日与每周模式不带窗口起始日", () => {
53
- expect(buildActivityColumns(series(3), "daily")[0]?.windowStart).toBeUndefined();
54
- expect(buildActivityColumns(series(9), "weekly")[0]?.windowStart).toBeUndefined();
55
- });
56
- });
57
-
58
- describe("fitCurveColumns", () => {
59
- it("采样保留最早与最新的历史,而不是丢弃左侧", () => {
60
- const columns = buildActivityColumns(series(365), "rolling");
61
- const fitted = fitCurveColumns(columns, 100);
62
- expect(fitted).toHaveLength(100);
63
- expect(fitted[0]?.date).toBe(columns[0]?.date);
64
- expect(fitted.at(-1)?.date).toBe(columns.at(-1)?.date);
65
- expect(new Set(fitted.map((c) => c.key)).size).toBe(100);
66
- });
67
-
68
- it("列数不足容量时铺满宽度,不在左侧补空列", () => {
69
- const columns = buildActivityColumns(series(3), "rolling");
70
- const fitted = fitCurveColumns(columns, 6);
71
- expect(fitted).toHaveLength(3);
72
- expect(fitted.some((c) => c.isPad)).toBe(false);
73
- expect(fitted.at(-1)?.tokens).toBe(300);
74
- });
75
-
76
- it("容量为 1 时保留最新一列", () => {
77
- const columns = buildActivityColumns(series(5), "rolling");
78
- expect(fitCurveColumns(columns, 1)).toHaveLength(1);
79
- expect(fitCurveColumns(columns, 1)[0]?.tokens).toBe(500);
80
- expect(fitCurveColumns(columns, 0)).toEqual([]);
81
- });
82
- });
83
-
84
- describe("buildAreaGeometry", () => {
85
- it("把列映射到 100x100 viewBox 并闭合到底边", () => {
86
- const columns = buildActivityColumns(series(3), "rolling");
87
- const { points, linePath, areaPath } = buildAreaGeometry(columns, 300);
88
- expect(points.map((p) => p.x)).toEqual([0, 50, 100]);
89
- // 100 / 200 / 300 tokens → 自底向上
90
- expect(points.map((p) => Math.round(p.y))).toEqual([67, 33, 0]);
91
- expect(linePath.startsWith("M0.00")).toBe(true);
92
- expect(areaPath.endsWith("L100.00 100.00 L0.00 100.00 Z")).toBe(true);
93
- });
94
-
95
- it("点数不足 2 或无数据时不产生路径", () => {
96
- expect(buildAreaGeometry([], 100)).toEqual({ points: [], linePath: "", areaPath: "" });
97
- const one = buildAreaGeometry(buildActivityColumns(series(1), "rolling"), 100);
98
- expect(one.points).toHaveLength(1);
99
- expect(one.linePath).toBe("");
100
- });
101
-
102
- it("maxTokens 非法时不产生 NaN 或越界坐标", () => {
103
- const columns = buildActivityColumns(series(3), "rolling");
104
- const { points } = buildAreaGeometry(columns, 0);
105
- expect(points.every((p) => Number.isFinite(p.y) && p.y >= 0 && p.y <= 100)).toBe(true);
106
- });
107
- });
108
-
109
- describe("activityMatrixHeightPx", () => {
110
- it("与方块矩阵同高,保证切换模式时布局不跳动", () => {
111
- // 10 列 × 8px + 9 个 2px 间隙 = 98px
112
- expect(activityMatrixHeightPx(10 * 8 + 9 * 2, 10)).toBeCloseTo(10 * 8 + 9 * 2, 5);
113
- expect(activityMatrixHeightPx(0, 10)).toBe(0);
114
- expect(activityMatrixHeightPx(100, 0)).toBe(0);
115
- });
116
- });
117
-
118
- describe("trimLeadingIdleColumns", () => {
119
- it("裁掉首次请求之前的空白天,只保留一个 0 基线锚点", () => {
120
- const points = series(10, 0).map((p, i) => ({ ...p, tokens: i >= 6 ? 100 : 0 }));
121
- const trimmed = trimLeadingIdleColumns(buildActivityColumns(points, "rolling"));
122
- expect(trimmed).toHaveLength(5);
123
- expect(trimmed[0]?.tokens).toBe(0);
124
- expect(trimmed[1]?.tokens).toBe(100);
125
- expect(trimmed.at(-1)?.tokens).toBe(400);
126
- });
127
-
128
- it("首列即有数据时不额外裁剪", () => {
129
- const trimmed = trimLeadingIdleColumns(buildActivityColumns(series(3), "rolling"));
130
- expect(trimmed).toHaveLength(3);
131
- expect(trimmed[0]?.tokens).toBe(100);
132
- });
133
-
134
- it("全程无用量时返回空数组", () => {
135
- expect(trimLeadingIdleColumns(buildActivityColumns(series(5, 0), "rolling"))).toEqual([]);
136
- });
137
-
138
- it("重新计算月份刻度,不保留被裁掉那段的起始月", () => {
139
- const points = series(70, 0).map((p, i) => ({ ...p, tokens: i >= 40 ? 100 : 0 }));
140
- const trimmed = trimLeadingIdleColumns(buildActivityColumns(points, "rolling"));
141
- expect(trimmed[0]?.monthKey).toBe(trimmed[0]?.date.slice(0, 7));
142
- });
143
- });
144
-
145
- describe("buildSmoothPath", () => {
146
- it("用三次贝塞尔连接数据点,首尾锚在真实数据上", () => {
147
- const points = [
148
- { key: "a", x: 0, y: 100 },
149
- { key: "b", x: 50, y: 60 },
150
- { key: "c", x: 100, y: 0 },
151
- ];
152
- const d = buildSmoothPath(points);
153
- expect(d.startsWith("M0.00 100.00")).toBe(true);
154
- expect(d.split("C")).toHaveLength(3);
155
- expect(d.endsWith("100.00 0.00")).toBe(true);
156
- });
157
-
158
- it("保单调:单调递增序列的曲线不会向下过冲", () => {
159
- const columns = buildActivityColumns(
160
- series(12, 0).map((p, i) => ({ ...p, tokens: i === 8 ? 5000 : 10 })),
161
- "rolling",
162
- );
163
- const { points, linePath } = buildAreaGeometry(columns, 5110);
164
- // 采样贝塞尔上的控制点纵坐标,均不得低于(y 值不得大于)起点
165
- const ys = linePath
166
- .split(/[MC]/)
167
- .filter(Boolean)
168
- .flatMap((seg) => seg.trim().split(/\s+/).map(Number))
169
- .filter((_, i) => i % 2 === 1);
170
- expect(Math.max(...ys)).toBeLessThanOrEqual(points[0]!.y + 0.01);
171
- });
172
-
173
- it("点数不足 2 时返回空串", () => {
174
- expect(buildSmoothPath([])).toBe("");
175
- expect(buildSmoothPath([{ key: "a", x: 0, y: 0 }])).toBe("");
176
- });
177
- });
178
-
179
- describe("buildHoverZones", () => {
180
- it("命中区以数据点为中心,延伸到相邻点的中点并铺满宽度", () => {
181
- const points = [
182
- { key: "a", x: 0, y: 0 },
183
- { key: "b", x: 50, y: 0 },
184
- { key: "c", x: 100, y: 0 },
185
- ];
186
- const zones = buildHoverZones(points);
187
- expect(zones.map((z) => z.left)).toEqual([0, 25, 75]);
188
- expect(zones.reduce((sum, z) => sum + z.width, 0)).toBeCloseTo(100, 5);
189
- });
190
-
191
- it("单点时铺满整宽,空输入返回空数组", () => {
192
- expect(buildHoverZones([{ key: "a", x: 0, y: 0 }])).toEqual([{ key: "a", left: 0, width: 100 }]);
193
- expect(buildHoverZones([])).toEqual([]);
194
- });
195
- });
@@ -1,320 +0,0 @@
1
- export type TokenActivityMode = "daily" | "weekly" | "rolling";
2
-
3
- export interface UsageSeriesPointLike {
4
- date: string;
5
- tokens: number;
6
- }
7
-
8
- export interface ActivityColumn {
9
- key: string;
10
- date: string;
11
- endDate: string;
12
- tokens: number;
13
- /** Month axis label for first column of each month; null otherwise */
14
- monthKey: string | null;
15
- /** Left-side filler when history is shorter than the visible capacity */
16
- isPad?: boolean;
17
- /** 滚动窗口的起始日;仅 rolling 模式有值,供提示条展示区间 */
18
- windowStart?: string;
19
- }
20
-
21
- export const TOKEN_ACTIVITY_MAX_ROWS = 10;
22
- /** 滚动窗口跨度(自然日)。 */
23
- export const ROLLING_WINDOW_DAYS = 30;
24
- /** Preferred square size used only to decide how many columns fit the width. */
25
- export const TOKEN_ACTIVITY_TARGET_CELL_PX = 8;
26
- export const TOKEN_ACTIVITY_GAP_PX = 2;
27
-
28
- function parseLocalDate(iso: string): Date {
29
- const [y, m, d] = iso.split("-").map(Number);
30
- return new Date(y!, m! - 1, d!);
31
- }
32
-
33
- function formatYmd(d: Date): string {
34
- const y = d.getFullYear();
35
- const m = String(d.getMonth() + 1).padStart(2, "0");
36
- const day = String(d.getDate()).padStart(2, "0");
37
- return `${y}-${m}-${day}`;
38
- }
39
-
40
- function addDays(iso: string, delta: number): string {
41
- const d = parseLocalDate(iso);
42
- d.setDate(d.getDate() + delta);
43
- return formatYmd(d);
44
- }
45
-
46
- /** Monday-start week key (YYYY-MM-DD of week start) */
47
- function weekStartKey(iso: string): string {
48
- const d = parseLocalDate(iso);
49
- const day = d.getDay();
50
- const diff = day === 0 ? -6 : 1 - day;
51
- d.setDate(d.getDate() + diff);
52
- return formatYmd(d);
53
- }
54
-
55
- function withMonthKeys(columns: ActivityColumn[]): ActivityColumn[] {
56
- let lastMonth = "";
57
- return columns.map((c) => {
58
- if (!c.date) return { ...c, monthKey: null };
59
- const m = c.date.slice(0, 7);
60
- const monthKey = m !== lastMonth ? m : null;
61
- lastMonth = m;
62
- return { ...c, monthKey };
63
- });
64
- }
65
-
66
- /**
67
- * 滚动窗口按自然日计量,序列里缺失的日期必须当作 0 参与进出窗,
68
- * 否则「过去 30 天」会在数据稀疏时退化成「最近 30 个有记录的日子」。
69
- */
70
- function densifyDaily(points: UsageSeriesPointLike[]): { date: string; tokens: number }[] {
71
- const totals = new Map<string, number>();
72
- for (const p of points) totals.set(p.date, (totals.get(p.date) ?? 0) + p.tokens);
73
- const dates = [...totals.keys()].sort((a, b) => a.localeCompare(b));
74
- const last = dates[dates.length - 1]!;
75
- const out: { date: string; tokens: number }[] = [];
76
- for (let cur = dates[0]!; cur <= last; cur = addDays(cur, 1)) {
77
- out.push({ date: cur, tokens: totals.get(cur) ?? 0 });
78
- }
79
- return out;
80
- }
81
-
82
- export function buildActivityColumns(points: UsageSeriesPointLike[], mode: TokenActivityMode): ActivityColumn[] {
83
- if (points.length === 0) return [];
84
-
85
- let base: { date: string; endDate: string; tokens: number; windowStart?: string }[];
86
-
87
- if (mode === "rolling") {
88
- const daily = densifyDaily(points);
89
- let sum = 0;
90
- base = daily.map((p, i) => {
91
- sum += p.tokens;
92
- const expired = i - ROLLING_WINDOW_DAYS;
93
- if (expired >= 0) sum -= daily[expired]!.tokens;
94
- return {
95
- date: p.date,
96
- endDate: p.date,
97
- tokens: sum,
98
- windowStart: daily[Math.max(0, i - ROLLING_WINDOW_DAYS + 1)]!.date,
99
- };
100
- });
101
- } else if (mode === "weekly") {
102
- const map = new Map<string, { date: string; endDate: string; tokens: number }>();
103
- for (const p of points) {
104
- const start = weekStartKey(p.date);
105
- const existing = map.get(start);
106
- if (existing) {
107
- existing.tokens += p.tokens;
108
- if (p.date > existing.endDate) existing.endDate = p.date;
109
- } else {
110
- map.set(start, { date: start, endDate: p.date, tokens: p.tokens });
111
- }
112
- }
113
- base = [...map.values()].sort((a, b) => a.date.localeCompare(b.date));
114
- } else {
115
- base = points.map((p) => ({ date: p.date, endDate: p.date, tokens: p.tokens }));
116
- }
117
-
118
- return withMonthKeys(
119
- base.map((p) => ({
120
- key: p.date,
121
- date: p.date,
122
- endDate: p.endDate,
123
- tokens: p.tokens,
124
- monthKey: null,
125
- ...(p.windowStart ? { windowStart: p.windowStart } : {}),
126
- })),
127
- );
128
- }
129
-
130
- /**
131
- * Fit columns to a fixed capacity so the chart exactly fills the container:
132
- * - too many → drop oldest (left)
133
- * - too few → pad empty columns on the left
134
- */
135
- export function fitActivityColumns(columns: ActivityColumn[], capacity: number): ActivityColumn[] {
136
- if (capacity <= 0) return [];
137
- if (columns.length >= capacity) {
138
- return withMonthKeys(columns.slice(columns.length - capacity));
139
- }
140
- const pad = capacity - columns.length;
141
- const empties: ActivityColumn[] = Array.from({ length: pad }, (_, i) => ({
142
- key: `__pad-${i}`,
143
- date: "",
144
- endDate: "",
145
- tokens: 0,
146
- monthKey: null,
147
- isPad: true,
148
- }));
149
- return withMonthKeys([...empties, ...columns]);
150
- }
151
-
152
- export function columnCapacity(
153
- widthPx: number,
154
- cellPx = TOKEN_ACTIVITY_TARGET_CELL_PX,
155
- gapPx = TOKEN_ACTIVITY_GAP_PX,
156
- ): number {
157
- if (widthPx <= 0) return 0;
158
- return Math.max(1, Math.floor((widthPx + gapPx) / (cellPx + gapPx)));
159
- }
160
-
161
- export function activityBlockCount(tokens: number, maxTokens: number, maxRows = TOKEN_ACTIVITY_MAX_ROWS): number {
162
- if (tokens <= 0 || maxTokens <= 0) return 0;
163
- return Math.max(1, Math.round((tokens / maxTokens) * maxRows));
164
- }
165
-
166
- /** Discrete intensity levels (excluding empty). Higher = more tokens. */
167
- export const TOKEN_ACTIVITY_INTENSITY_LEVELS = 4;
168
-
169
- /**
170
- * Map a token amount to 0..levels (0 = empty, 1 light … levels darkest).
171
- * Relative to the max in the visible window.
172
- */
173
- export function activityIntensityLevel(
174
- tokens: number,
175
- maxTokens: number,
176
- levels = TOKEN_ACTIVITY_INTENSITY_LEVELS,
177
- ): number {
178
- if (tokens <= 0 || maxTokens <= 0) return 0;
179
- return Math.min(levels, Math.max(1, Math.ceil((tokens / maxTokens) * levels)));
180
- }
181
-
182
- export function formatTokenCount(n: number): string {
183
- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
184
- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
185
- return n.toLocaleString();
186
- }
187
-
188
- /**
189
- * 曲线只关心「有数据之后」的部分:服务端固定返回一整年,首次请求之前全是 0,
190
- * 补在左边只会画出一条无信息的平线。保留紧邻的最后一个空档作为 0 基线锚点,
191
- * 让曲线从底部起笔而不是凭空出现在半空。
192
- */
193
- export function trimLeadingIdleColumns(columns: ActivityColumn[]): ActivityColumn[] {
194
- const first = columns.findIndex((c) => !c.isPad && c.tokens > 0);
195
- if (first < 0) return [];
196
- return withMonthKeys(columns.slice(Math.max(0, first - 1)));
197
- }
198
-
199
- /**
200
- * 滚动窗口是逐日平滑变化的序列,用方块矩阵只会画成一片高度相近的柱子,
201
- * 因此改用面积曲线。曲线不需要一天一列,超出容量时按等距采样降采样;
202
- * 列数少于容量时直接铺满宽度,不像矩阵那样在左侧补空列。
203
- */
204
- export function fitCurveColumns(columns: ActivityColumn[], capacity: number): ActivityColumn[] {
205
- if (capacity <= 0) return [];
206
- if (columns.length <= capacity) return columns;
207
- if (capacity === 1) return withMonthKeys([columns[columns.length - 1]!]);
208
- const sampled = Array.from({ length: capacity }, (_, i) => {
209
- const idx = Math.round((i * (columns.length - 1)) / (capacity - 1));
210
- return columns[idx]!;
211
- });
212
- return withMonthKeys(sampled);
213
- }
214
-
215
- export interface AreaGeometryPoint {
216
- key: string;
217
- /** 0..100,viewBox 内的水平位置 */
218
- x: number;
219
- /** 0..100,viewBox 内的垂直位置,0 在顶部 */
220
- y: number;
221
- }
222
-
223
- export interface AreaGeometry {
224
- points: AreaGeometryPoint[];
225
- /** 平滑折线路径;点数不足 2 时为空串 */
226
- linePath: string;
227
- /** 闭合到底边的填充路径;点数不足 2 时为空串 */
228
- areaPath: string;
229
- }
230
-
231
- const round = (v: number): string => (Math.round(v * 100) / 100).toFixed(2);
232
-
233
- /**
234
- * Fritsch–Carlson 单调三次插值的切线。普通 Catmull-Rom 会在陡升/陡降段前后过冲,
235
- * 画出数据里并不存在的假回落或假反弹,这里必须用保单调的版本。
236
- */
237
- function monotoneTangents(points: AreaGeometryPoint[]): number[] {
238
- const n = points.length;
239
- const slopes: number[] = [];
240
- for (let i = 0; i < n - 1; i++) {
241
- const dx = points[i + 1]!.x - points[i]!.x;
242
- slopes.push(dx === 0 ? 0 : (points[i + 1]!.y - points[i]!.y) / dx);
243
- }
244
- const m = points.map((_, i) => {
245
- if (i === 0) return slopes[0] ?? 0;
246
- if (i === n - 1) return slopes[n - 2] ?? 0;
247
- return ((slopes[i - 1] ?? 0) + (slopes[i] ?? 0)) / 2;
248
- });
249
- for (let i = 0; i < n - 1; i++) {
250
- const d = slopes[i]!;
251
- if (d === 0) {
252
- m[i] = 0;
253
- m[i + 1] = 0;
254
- continue;
255
- }
256
- const a = m[i]! / d;
257
- const b = m[i + 1]! / d;
258
- const sum = a * a + b * b;
259
- if (sum > 9) {
260
- const t = 3 / Math.sqrt(sum);
261
- m[i] = t * a * d;
262
- m[i + 1] = t * b * d;
263
- }
264
- }
265
- return m;
266
- }
267
-
268
- /** 把数据点连成保单调的三次贝塞尔路径。 */
269
- export function buildSmoothPath(points: AreaGeometryPoint[]): string {
270
- if (points.length < 2) return "";
271
- const m = monotoneTangents(points);
272
- let d = `M${round(points[0]!.x)} ${round(points[0]!.y)}`;
273
- for (let i = 0; i < points.length - 1; i++) {
274
- const p0 = points[i]!;
275
- const p1 = points[i + 1]!;
276
- const dx = (p1.x - p0.x) / 3;
277
- d += ` C${round(p0.x + dx)} ${round(p0.y + m[i]! * dx)} ${round(p1.x - dx)} ${round(p1.y - m[i + 1]! * dx)} ${round(p1.x)} ${round(p1.y)}`;
278
- }
279
- return d;
280
- }
281
-
282
- /** 悬停命中区:以每个数据点为中心、延伸到与相邻点的中点,保证指针位置和圆点落在同一列。 */
283
- export function buildHoverZones(points: AreaGeometryPoint[]): Array<{ key: string; left: number; width: number }> {
284
- const n = points.length;
285
- if (n === 0) return [];
286
- if (n === 1) return [{ key: points[0]!.key, left: 0, width: 100 }];
287
- return points.map((p, i) => {
288
- const left = i === 0 ? 0 : (points[i - 1]!.x + p.x) / 2;
289
- const right = i === n - 1 ? 100 : (p.x + points[i + 1]!.x) / 2;
290
- return { key: p.key, left, width: right - left };
291
- });
292
- }
293
-
294
- /** 把列序列映射成 100x100 viewBox 内的面积曲线几何,供 SVG 以 `preserveAspectRatio="none"` 拉伸。 */
295
- export function buildAreaGeometry(columns: ActivityColumn[], maxTokens: number): AreaGeometry {
296
- const n = columns.length;
297
- if (n === 0) return { points: [], linePath: "", areaPath: "" };
298
- const max = maxTokens > 0 ? maxTokens : 1;
299
- const points = columns.map((col, i) => ({
300
- key: col.key,
301
- x: n === 1 ? 0 : (i / (n - 1)) * 100,
302
- y: 100 - Math.min(100, Math.max(0, (col.tokens / max) * 100)),
303
- }));
304
- const linePath = buildSmoothPath(points);
305
- const areaPath = linePath ? `${linePath} L100.00 100.00 L0.00 100.00 Z` : "";
306
- return { points, linePath, areaPath };
307
- }
308
-
309
- /** 方块矩阵的实际像素高度,曲线模式复用它以避免切换 tab 时高度跳动。 */
310
- export function activityMatrixHeightPx(
311
- widthPx: number,
312
- capacity: number,
313
- gapPx = TOKEN_ACTIVITY_GAP_PX,
314
- rows = TOKEN_ACTIVITY_MAX_ROWS,
315
- ): number {
316
- if (widthPx <= 0 || capacity <= 0) return 0;
317
- const cell = (widthPx - (capacity - 1) * gapPx) / capacity;
318
- if (cell <= 0) return 0;
319
- return rows * cell + (rows - 1) * gapPx;
320
- }