@deepseek-ai/dsh-experimental-client-ui-forge 0.2.2-alpha.3 → 0.2.2-rc.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 (272) hide show
  1. package/README.i18n.yaml +8 -8
  2. package/README.md +41 -14
  3. package/README.zh.md +40 -13
  4. package/lib/client.js +13 -11800
  5. package/lib/client.js.map +1 -0
  6. package/lib/index.js +1340 -115
  7. package/lib/typert.host.js +1715 -212
  8. package/lib/typert.remote-client.d.ts +42 -5
  9. package/lib/typert.remote-client.d.ts.map +1 -0
  10. package/lib/typert.remote-client.js +1523 -244
  11. package/lib/types/client/ActionToast.d.ts.map +1 -0
  12. package/lib/types/client/ActionToast.js.map +1 -0
  13. package/lib/types/client/BaseMenu.d.ts +30 -0
  14. package/lib/types/client/BaseMenu.d.ts.map +1 -0
  15. package/lib/types/client/BaseMenu.js.map +1 -0
  16. package/lib/types/client/ChangeRequestCard.d.ts +9 -5
  17. package/lib/types/client/ChangeRequestCard.d.ts.map +1 -0
  18. package/lib/types/client/ChangeRequestCard.js.map +1 -0
  19. package/lib/types/client/ChangeRequestOverview.d.ts +124 -0
  20. package/lib/types/client/ChangeRequestOverview.d.ts.map +1 -0
  21. package/lib/types/client/ChangeRequestOverview.js.map +1 -0
  22. package/lib/types/client/ChangedFiles.d.ts +2 -0
  23. package/lib/types/client/ChangedFiles.d.ts.map +1 -0
  24. package/lib/types/client/ChangedFiles.js.map +1 -0
  25. package/lib/types/client/ChangesTab.d.ts +30 -5
  26. package/lib/types/client/ChangesTab.d.ts.map +1 -0
  27. package/lib/types/client/ChangesTab.js.map +1 -0
  28. package/lib/types/client/ChangesTabTitle.d.ts.map +1 -0
  29. package/lib/types/client/ChangesTabTitle.js.map +1 -0
  30. package/lib/types/client/CommitMenu.d.ts +41 -0
  31. package/lib/types/client/CommitMenu.d.ts.map +1 -0
  32. package/lib/types/client/CommitMenu.js.map +1 -0
  33. package/lib/types/client/DiffFile.d.ts +47 -15
  34. package/lib/types/client/DiffFile.d.ts.map +1 -0
  35. package/lib/types/client/DiffFile.js.map +1 -0
  36. package/lib/types/client/FileLabel.d.ts.map +1 -0
  37. package/lib/types/client/FileLabel.js.map +1 -0
  38. package/lib/types/client/FileTreePane.d.ts +4 -2
  39. package/lib/types/client/FileTreePane.d.ts.map +1 -0
  40. package/lib/types/client/FileTreePane.js.map +1 -0
  41. package/lib/types/client/ForgeTab.d.ts +9 -1
  42. package/lib/types/client/ForgeTab.d.ts.map +1 -0
  43. package/lib/types/client/ForgeTab.js.map +1 -0
  44. package/lib/types/client/ForgeTabTitle.d.ts.map +1 -0
  45. package/lib/types/client/ForgeTabTitle.js.map +1 -0
  46. package/lib/types/client/HeaderButton.d.ts.map +1 -0
  47. package/lib/types/client/HeaderButton.js.map +1 -0
  48. package/lib/types/client/LocalChangesCard.d.ts.map +1 -0
  49. package/lib/types/client/LocalChangesCard.js.map +1 -0
  50. package/lib/types/client/RefreshGlyph.d.ts.map +1 -0
  51. package/lib/types/client/RefreshGlyph.js.map +1 -0
  52. package/lib/types/client/ReviewComposer.d.ts +20 -6
  53. package/lib/types/client/ReviewComposer.d.ts.map +1 -0
  54. package/lib/types/client/ReviewComposer.js.map +1 -0
  55. package/lib/types/client/ReviewControls.d.ts +79 -0
  56. package/lib/types/client/ReviewControls.d.ts.map +1 -0
  57. package/lib/types/client/ReviewControls.js.map +1 -0
  58. package/lib/types/client/ReviewThread.d.ts +4 -4
  59. package/lib/types/client/ReviewThread.d.ts.map +1 -0
  60. package/lib/types/client/ReviewThread.js.map +1 -0
  61. package/lib/types/client/ReviewThreads.d.ts +108 -0
  62. package/lib/types/client/ReviewThreads.d.ts.map +1 -0
  63. package/lib/types/client/ReviewThreads.js.map +1 -0
  64. package/lib/types/client/SessionHoverForge.d.ts.map +1 -0
  65. package/lib/types/client/SessionHoverForge.js.map +1 -0
  66. package/lib/types/client/SessionRowForge.d.ts +1 -1
  67. package/lib/types/client/SessionRowForge.d.ts.map +1 -0
  68. package/lib/types/client/SessionRowForge.js.map +1 -0
  69. package/lib/types/client/SubmitReview.d.ts +12 -4
  70. package/lib/types/client/SubmitReview.d.ts.map +1 -0
  71. package/lib/types/client/SubmitReview.js.map +1 -0
  72. package/lib/types/client/ThreadList.d.ts +43 -0
  73. package/lib/types/client/ThreadList.d.ts.map +1 -0
  74. package/lib/types/client/ThreadList.js.map +1 -0
  75. package/lib/types/client/ViewOptionsMenu.d.ts +31 -0
  76. package/lib/types/client/ViewOptionsMenu.d.ts.map +1 -0
  77. package/lib/types/client/ViewOptionsMenu.js.map +1 -0
  78. package/lib/types/client/WorktreeProgress.d.ts.map +1 -0
  79. package/lib/types/client/WorktreeProgress.js.map +1 -0
  80. package/lib/types/client/WorktreeSettings.d.ts +12 -0
  81. package/lib/types/client/WorktreeSettings.d.ts.map +1 -0
  82. package/lib/types/client/WorktreeSettings.js.map +1 -0
  83. package/lib/types/client/WorktreeToggle.d.ts.map +1 -0
  84. package/lib/types/client/WorktreeToggle.js.map +1 -0
  85. package/lib/types/client/changes-address.d.ts.map +1 -0
  86. package/lib/types/client/changes-address.js.map +1 -0
  87. package/lib/types/client/changes-store.d.ts +20 -5
  88. package/lib/types/client/changes-store.d.ts.map +1 -0
  89. package/lib/types/client/changes-store.js.map +1 -0
  90. package/lib/types/client/checkout.d.ts.map +1 -0
  91. package/lib/types/client/checkout.js.map +1 -0
  92. package/lib/types/client/code-selection.d.ts.map +1 -0
  93. package/lib/types/client/code-selection.js.map +1 -0
  94. package/lib/types/client/diff-rows.d.ts.map +1 -0
  95. package/lib/types/client/diff-rows.js.map +1 -0
  96. package/lib/types/client/file-tree.d.ts.map +1 -0
  97. package/lib/types/client/file-tree.js.map +1 -0
  98. package/lib/types/client/format.d.ts.map +1 -0
  99. package/lib/types/client/format.js.map +1 -0
  100. package/lib/types/client/glyphs.d.ts +4 -2
  101. package/lib/types/client/glyphs.d.ts.map +1 -0
  102. package/lib/types/client/glyphs.js.map +1 -0
  103. package/lib/types/client/host-viewed.d.ts +84 -0
  104. package/lib/types/client/host-viewed.d.ts.map +1 -0
  105. package/lib/types/client/host-viewed.js.map +1 -0
  106. package/lib/types/client/index.d.ts.map +1 -0
  107. package/lib/types/client/index.js.map +1 -0
  108. package/lib/types/client/locales.d.ts +175 -3
  109. package/lib/types/client/locales.d.ts.map +1 -0
  110. package/lib/types/client/locales.js.map +1 -0
  111. package/lib/types/client/menu-search.d.ts +10 -0
  112. package/lib/types/client/menu-search.d.ts.map +1 -0
  113. package/lib/types/client/menu-search.js.map +1 -0
  114. package/lib/types/client/mount.d.ts +4 -0
  115. package/lib/types/client/mount.d.ts.map +1 -0
  116. package/lib/types/client/mount.js.map +1 -0
  117. package/lib/types/client/review-queue.d.ts +5 -8
  118. package/lib/types/client/review-queue.d.ts.map +1 -0
  119. package/lib/types/client/review-queue.js.map +1 -0
  120. package/lib/types/client/review-threads.d.ts +108 -0
  121. package/lib/types/client/review-threads.d.ts.map +1 -0
  122. package/lib/types/client/review-threads.js.map +1 -0
  123. package/lib/types/client/review.d.ts +31 -4
  124. package/lib/types/client/review.d.ts.map +1 -0
  125. package/lib/types/client/review.js.map +1 -0
  126. package/lib/types/client/section-reach.d.ts +26 -0
  127. package/lib/types/client/section-reach.d.ts.map +1 -0
  128. package/lib/types/client/section-reach.js.map +1 -0
  129. package/lib/types/client/session-list.d.ts.map +1 -0
  130. package/lib/types/client/session-list.js.map +1 -0
  131. package/lib/types/client/source.d.ts.map +1 -0
  132. package/lib/types/client/source.js.map +1 -0
  133. package/lib/types/client/status.d.ts.map +1 -0
  134. package/lib/types/client/status.js.map +1 -0
  135. package/lib/types/client/thread-state.d.ts +68 -0
  136. package/lib/types/client/thread-state.d.ts.map +1 -0
  137. package/lib/types/client/thread-state.js.map +1 -0
  138. package/lib/types/client/toolbar-fold.d.ts +19 -0
  139. package/lib/types/client/toolbar-fold.d.ts.map +1 -0
  140. package/lib/types/client/toolbar-fold.js.map +1 -0
  141. package/lib/types/client/viewed-files.d.ts +70 -0
  142. package/lib/types/client/viewed-files.d.ts.map +1 -0
  143. package/lib/types/client/viewed-files.js.map +1 -0
  144. package/lib/types/client/worktree-settings-form.d.ts +32 -0
  145. package/lib/types/client/worktree-settings-form.d.ts.map +1 -0
  146. package/lib/types/client/worktree-settings-form.js.map +1 -0
  147. package/lib/types/commit-range.d.ts +17 -0
  148. package/lib/types/commit-range.d.ts.map +1 -0
  149. package/lib/types/commit-range.js.map +1 -0
  150. package/lib/types/diff.d.ts +10 -2
  151. package/lib/types/diff.d.ts.map +1 -0
  152. package/lib/types/diff.js.map +1 -0
  153. package/lib/types/git.d.ts.map +1 -0
  154. package/lib/types/git.js.map +1 -0
  155. package/lib/types/index.d.ts +194 -14
  156. package/lib/types/index.d.ts.map +1 -0
  157. package/lib/types/index.js.map +1 -0
  158. package/lib/types/layers.d.ts +66 -0
  159. package/lib/types/layers.d.ts.map +1 -0
  160. package/lib/types/layers.js.map +1 -0
  161. package/lib/types/local-diff.d.ts +54 -6
  162. package/lib/types/local-diff.d.ts.map +1 -0
  163. package/lib/types/local-diff.js.map +1 -0
  164. package/lib/types/panel.d.ts.map +1 -0
  165. package/lib/types/panel.js.map +1 -0
  166. package/lib/types/parse.d.ts +16 -0
  167. package/lib/types/parse.d.ts.map +1 -0
  168. package/lib/types/parse.js.map +1 -0
  169. package/lib/types/patch-cache.d.ts +12 -7
  170. package/lib/types/patch-cache.d.ts.map +1 -0
  171. package/lib/types/patch-cache.js.map +1 -0
  172. package/lib/types/review-cache.d.ts +54 -0
  173. package/lib/types/review-cache.d.ts.map +1 -0
  174. package/lib/types/review-cache.js.map +1 -0
  175. package/lib/types/states.d.ts.map +1 -0
  176. package/lib/types/states.js.map +1 -0
  177. package/lib/types/types.d.ts +113 -11
  178. package/lib/types/types.d.ts.map +1 -0
  179. package/lib/types/types.js.map +1 -0
  180. package/lib/types/wildmatch.d.ts +14 -0
  181. package/lib/types/wildmatch.d.ts.map +1 -0
  182. package/lib/types/wildmatch.js.map +1 -0
  183. package/lib/types/worktree.d.ts +8 -6
  184. package/lib/types/worktree.d.ts.map +1 -0
  185. package/lib/types/worktree.js.map +1 -0
  186. package/package.json +59 -49
  187. package/src/client/ActionToast.tsx +38 -0
  188. package/src/client/BaseMenu.module.css +153 -0
  189. package/src/client/BaseMenu.tsx +180 -0
  190. package/src/client/ChangeRequestCard.tsx +439 -0
  191. package/src/client/ChangeRequestOverview.module.css +196 -0
  192. package/src/client/ChangeRequestOverview.tsx +620 -0
  193. package/src/client/ChangedFiles.module.css +26 -0
  194. package/src/client/ChangedFiles.tsx +144 -0
  195. package/src/client/ChangesTab.module.css +984 -0
  196. package/src/client/ChangesTab.tsx +1288 -0
  197. package/src/client/ChangesTabTitle.tsx +28 -0
  198. package/src/client/CommitMenu.module.css +139 -0
  199. package/src/client/CommitMenu.tsx +186 -0
  200. package/src/client/DiffFile.tsx +621 -0
  201. package/src/client/FileLabel.module.css +53 -0
  202. package/src/client/FileLabel.tsx +66 -0
  203. package/src/client/FileTreePane.module.css +10 -0
  204. package/src/client/FileTreePane.tsx +79 -0
  205. package/src/client/ForgeTab.module.css +627 -0
  206. package/src/client/ForgeTab.tsx +263 -0
  207. package/src/client/ForgeTabTitle.tsx +21 -0
  208. package/src/client/HeaderButton.module.css +29 -0
  209. package/src/client/HeaderButton.tsx +68 -0
  210. package/src/client/LocalChangesCard.tsx +83 -0
  211. package/src/client/RefreshGlyph.module.css +22 -0
  212. package/src/client/RefreshGlyph.tsx +35 -0
  213. package/src/client/ReviewComposer.module.css +37 -0
  214. package/src/client/ReviewComposer.tsx +128 -0
  215. package/src/client/ReviewControls.module.css +162 -0
  216. package/src/client/ReviewControls.tsx +191 -0
  217. package/src/client/ReviewThread.tsx +96 -0
  218. package/src/client/ReviewThreads.module.css +326 -0
  219. package/src/client/ReviewThreads.tsx +443 -0
  220. package/src/client/SessionHoverForge.tsx +72 -0
  221. package/src/client/SessionList.module.css +85 -0
  222. package/src/client/SessionRowForge.tsx +86 -0
  223. package/src/client/SubmitReview.module.css +26 -0
  224. package/src/client/SubmitReview.tsx +95 -0
  225. package/src/client/ThreadList.module.css +218 -0
  226. package/src/client/ThreadList.tsx +165 -0
  227. package/src/client/ViewOptionsMenu.tsx +79 -0
  228. package/src/client/WorktreeProgress.module.css +226 -0
  229. package/src/client/WorktreeProgress.tsx +280 -0
  230. package/src/client/WorktreeSettings.module.css +29 -0
  231. package/src/client/WorktreeSettings.tsx +42 -0
  232. package/src/client/WorktreeToggle.module.css +132 -0
  233. package/src/client/WorktreeToggle.tsx +165 -0
  234. package/src/client/changes-address.ts +110 -0
  235. package/src/client/changes-store.ts +155 -0
  236. package/src/client/checkout.ts +75 -0
  237. package/src/client/code-selection.ts +53 -0
  238. package/src/client/diff-rows.ts +199 -0
  239. package/src/client/file-tree.ts +86 -0
  240. package/src/client/format.ts +37 -0
  241. package/src/client/glyphs.tsx +151 -0
  242. package/src/client/host-viewed.ts +195 -0
  243. package/src/client/index.ts +31 -0
  244. package/src/client/locales.ts +3446 -0
  245. package/src/client/menu-search.ts +16 -0
  246. package/src/client/mount.ts +439 -0
  247. package/src/client/review-queue.ts +256 -0
  248. package/src/client/review-threads.ts +204 -0
  249. package/src/client/review.ts +120 -0
  250. package/src/client/section-reach.ts +61 -0
  251. package/src/client/session-list.ts +79 -0
  252. package/src/client/source.ts +274 -0
  253. package/src/client/status.ts +171 -0
  254. package/src/client/thread-state.ts +127 -0
  255. package/src/client/toolbar-fold.ts +70 -0
  256. package/src/client/viewed-files.ts +178 -0
  257. package/src/client/worktree-settings-form.ts +43 -0
  258. package/src/commit-range.ts +27 -0
  259. package/src/css-modules.d.ts +5 -0
  260. package/src/diff.ts +162 -0
  261. package/src/git.ts +293 -0
  262. package/src/index.ts +1162 -0
  263. package/src/layers.ts +163 -0
  264. package/src/local-diff.ts +438 -0
  265. package/src/panel.ts +422 -0
  266. package/src/parse.ts +137 -0
  267. package/src/patch-cache.ts +73 -0
  268. package/src/review-cache.ts +98 -0
  269. package/src/states.ts +350 -0
  270. package/src/types.ts +504 -0
  271. package/src/wildmatch.ts +121 -0
  272. package/src/worktree.ts +576 -0
@@ -0,0 +1,1288 @@
1
+ /**
2
+ * Body of the changes tab: the local changes of the Session's checkout in a
3
+ * chosen scope, or the changes of one of its change requests, as one list of
4
+ * file sections under a toolbar that jumps between files and switches the
5
+ * layout. The view reads the changes when it opens, on each navigation, on
6
+ * refresh, and when the change request's head or the checkout's `branch`
7
+ * scope summary changes; a read keeps the previous changes on screen until it settles.
8
+ * File sections receive values that keep their identity across renders, so a
9
+ * render of the view redraws only the sections whose own values changed, and
10
+ * an expanded file draws its lines once its section comes near the scrollport.
11
+ */
12
+
13
+ import {
14
+ useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent,
15
+ type ReactNode,
16
+ } from 'react'
17
+ import clsx from 'clsx'
18
+ import {
19
+ Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular,
20
+ IconInfoOutlineRegular, IconListPenOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular,
21
+ IconWrapFillRegular,
22
+ Menu, StateDot, Tooltip,
23
+ type MenuEntry,
24
+ } from '@deepseek-ai/dsh-client-ui-primitives'
25
+ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
26
+ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
27
+ import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
28
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
29
+ import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
30
+ import type {
31
+ ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff,
32
+ ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState,
33
+ } from '../types.ts'
34
+ import type {
35
+ ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult,
36
+ ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest,
37
+ } from '@deepseek-ai/dsh-experimental-forge/types'
38
+ import { sameReviewSource, type ReviewQueue } from './review-queue.ts'
39
+ import { ReviewThread, useFileReview } from './ReviewThread.tsx'
40
+ import type { ReviewActions } from './ReviewComposer.tsx'
41
+ import { SubmitReview } from './SubmitReview.tsx'
42
+ import type { ReviewSelection, ReviewSource } from './review.ts'
43
+ import { BaseMenu } from './BaseMenu.tsx'
44
+ import { parseChangesAddress, type ChangesSource } from './changes-address.ts'
45
+ import type { ChangesLens, createChangesStore } from './changes-store.ts'
46
+ import { CommitMenu } from './CommitMenu.tsx'
47
+ import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx'
48
+ import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts'
49
+ import { hostViewedOf, useHostViewed, type HostViewed } from './host-viewed.ts'
50
+ import { Counts, DiffFile, type DiffFileAction, type DiffFileHandlers } from './DiffFile.tsx'
51
+ import { SectionReach } from './section-reach.ts'
52
+ import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx'
53
+ import { changedFileTree, filesInTreeOrder } from './file-tree.ts'
54
+ import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx'
55
+ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts'
56
+ import { ChangeRequestGlyph } from './glyphs.tsx'
57
+ import type { ForgePanelKey, NS } from './locales.ts'
58
+ import { RefreshGlyph } from './RefreshGlyph.tsx'
59
+ import { ViewOptionsMenu } from './ViewOptionsMenu.tsx'
60
+ import { observeToolbarFold } from './toolbar-fold.ts'
61
+ import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx'
62
+ import { inFileOrder, type ThreadFilter } from './review-threads.ts'
63
+ import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts'
64
+ import { ThreadList } from './ThreadList.tsx'
65
+ import type { PanelSnapshot } from './source.ts'
66
+ import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf } from './status.ts'
67
+ import css from './ChangesTab.module.css'
68
+
69
+ type Translate = PropsLocale<typeof NS>['t']
70
+
71
+ /** Kind of a local scope. */
72
+ type ScopeKind = ForgeLocalScope['kind']
73
+
74
+ /** A file the view scrolls to once, and the thread card it centers there with whether that card takes the focus. */
75
+ interface Wanted {
76
+ readonly path: string
77
+ readonly center: { readonly id: ForgeThreadId; readonly focus: boolean } | null
78
+ }
79
+
80
+ /** Business face of the changes tab body. */
81
+ export interface ChangesTabInjected {
82
+ /** Append a frozen comment to the main input without submitting it. */
83
+ readonly addReviewToInput: (selection: ReviewSelection) => boolean
84
+ /** Records retained across Session switches and cleared when this tab occurrence closes. */
85
+ readonly reviewQueue: (tab: Pick<SidebarRightTabInfo['tab'], 'id' | 'signal'>) => ReviewQueue
86
+ /** Publish one comment or a completed review; never retries mutations. */
87
+ readonly submitReview: (url: string, request: ForgeReviewRequest) => Promise<RemoteResult<ForgeReviewResult>>
88
+ /** Panel source while visible; the renderer releases the subscription for an inactive key. */
89
+ readonly keyedHooks: { readonly panel: (visibility: string) => HostObservable<PanelSnapshot> | undefined }
90
+ /** Open the panel stream again after it ended. */
91
+ readonly reconnect: () => void
92
+ /** Read the local changes of one scope; `signal` aborts the read. */
93
+ readonly localDiff: (scope: ForgeLocalScope, signal: AbortSignal) => Promise<RemoteResult<ForgeLocalDiff>>
94
+ /** Read the branches the `branch` scope can compare with, whose names contain `query`; `signal` aborts the read. */
95
+ readonly diffBases: (query: string, signal: AbortSignal) => Promise<RemoteResult<ForgeBaseBranches>>
96
+ /** Read the new side of one file in a local scope. */
97
+ readonly localText: (scope: ForgeLocalScope, path: string) => Promise<RemoteResult<string>>
98
+ /** List the commits of the `branch` scope compared with `base`, or with the automatic fork point for null; `signal` aborts the read. */
99
+ readonly localCommits: (base: string | null, signal: AbortSignal) => Promise<RemoteResult<ForgeLocalCommits>>
100
+ /** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */
101
+ readonly changeRequestDiff: (
102
+ url: string, commits: ForgeCommitRange | null, signal: AbortSignal,
103
+ ) => Promise<RemoteResult<ForgeChangeRequestDiff>>
104
+ /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */
105
+ readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise<RemoteResult<ForgeCommitList | null>>
106
+ /** The Session's viewed marks, kept in the browser for local changes, chosen commits, and hosts that keep none. */
107
+ readonly viewedFiles: ViewedFiles
108
+ /**
109
+ * Read the signed-in user's viewed marks on a change request's files at `headSha`, or null when its provider keeps
110
+ * none; `signal` aborts the read.
111
+ */
112
+ readonly changeRequestViewed: (url: string, headSha: string, signal: AbortSignal) => Promise<RemoteResult<ForgeViewedFiles | null>>
113
+ /** Set or clear the signed-in user's viewed mark on one file of a change request. */
114
+ readonly setFileViewed: (url: string, request: ForgeViewedRequest) => Promise<RemoteResult<void>>
115
+ /** Read one file of a change request at a commit. */
116
+ readonly changeRequestText: (url: string, commit: string, path: string) => Promise<RemoteResult<string>>
117
+ /** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */
118
+ readonly changeRequestReview: (
119
+ url: string, headSha: string, fresh: boolean, signal: AbortSignal,
120
+ ) => Promise<RemoteResult<ForgeReviewData>>
121
+ /** Write to the review threads or the pending review of a change request; never retries a write. */
122
+ readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise<RemoteResult<ForgeReviewWriteResult>>
123
+ /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */
124
+ readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean
125
+ /** Open a URL outside the app. */
126
+ readonly openLink: (url: string) => void
127
+ /** Copy a path to the clipboard and report the outcome. */
128
+ readonly copyPath: (path: string) => void
129
+ /** Ask the Session's Agent to create a change request for its changes, reporting the outcome. */
130
+ readonly createChangeRequest: () => void
131
+ /** Show a failure notice. */
132
+ readonly report: (key: ForgePanelKey, params?: Readonly<Record<string, string>>) => void
133
+ }
134
+
135
+ /** Full props of the changes tab body. */
136
+ export type ChangesTabProps =
137
+ Pick<PropsRuntime<'sidebar.right.pane.tab'>, 'useTabInfo' | 'sessionId'>
138
+ & PropsStore<ReturnType<typeof createChangesStore>>
139
+ & InjectFace<ChangesTabInjected>
140
+ & PropsLocale<typeof NS>
141
+
142
+ /** Changes of either source as the view draws them. */
143
+ type ChangesData =
144
+ | {
145
+ readonly kind: 'local'
146
+ readonly files: readonly ForgeDiffFile[]
147
+ /** Scope the files were read in. */
148
+ readonly scope: ForgeLocalScope
149
+ /** Name of what the `branch` scope compared with; null for other scopes. */
150
+ readonly base: string | null
151
+ /** Untracked files left out. */
152
+ readonly omitted: number
153
+ }
154
+ | {
155
+ readonly kind: 'change'
156
+ readonly files: readonly ForgeDiffFile[]
157
+ /** Binding URL of the change request. */
158
+ readonly url: string
159
+ /** Commit the files end at, the head or the last chosen commit, which supplies unchanged lines. */
160
+ readonly headSha: string
161
+ /** Commits the files cover, or null for the whole change request. */
162
+ readonly commits: ForgeCommitRange | null
163
+ /** Commits the checkout's branch has beyond the head, or null. */
164
+ readonly localAhead: number | null
165
+ /** Web page of each file at the head. */
166
+ readonly fileUrls: Readonly<Record<string, string>>
167
+ /** The code host's viewed marks of the whole change request, or null when the browser keeps the marks. */
168
+ readonly viewed: HostViewed | null
169
+ }
170
+
171
+ /** Why the code host did not take a review write, and whether it may have applied it. */
172
+ interface WriteRefusal {
173
+ readonly message: string
174
+ readonly unknown: boolean
175
+ }
176
+
177
+ /** Unchanged lines read for one loaded diff: each file's new side and its expanded gaps. */
178
+ interface Expansion {
179
+ readonly data: ChangesData | null
180
+ readonly texts: Readonly<Record<string, readonly string[] | 'loading'>>
181
+ readonly open: Readonly<Record<string, ReadonlySet<number>>>
182
+ }
183
+
184
+ /** Files whose hunks draw more lines show the large-file notice until revealed. */
185
+ const LARGE_FILE_LINES = 1000
186
+
187
+ /** Lines the files above may change before a file starts collapsed. */
188
+ const OPEN_LINES = 5000
189
+
190
+ const NO_GAPS: ReadonlySet<number> = new Set()
191
+
192
+ const SCOPE_LABEL: Record<ScopeKind, ForgePanelKey> = {
193
+ branch: 'diff.scope.branch',
194
+ uncommitted: 'diff.scope.uncommitted',
195
+ unstaged: 'diff.scope.unstaged',
196
+ staged: 'diff.scope.staged',
197
+ }
198
+
199
+ const SCOPE_NOTE: Record<Exclude<ScopeKind, 'branch'>, ForgePanelKey> = {
200
+ uncommitted: 'diff.scopeNote.uncommitted',
201
+ unstaged: 'diff.scopeNote.unstaged',
202
+ staged: 'diff.scopeNote.staged',
203
+ }
204
+
205
+ /** Failures with their own message; any other failure offers a retry. */
206
+ const FAILURE: Partial<Record<string, ForgePanelKey>> = {
207
+ 'forgePanel/not-a-checkout': 'checkout.none',
208
+ 'forgePanel/no-fork-point': 'diff.noForkPoint',
209
+ 'forgePanel/diff-too-large': 'diff.tooLarge',
210
+ 'forgePanel/filter-config-failed': 'diff.filterConfigFailed',
211
+ 'forgePanel/commits-missing': 'commits.missing',
212
+ 'forgePanel/commits-not-linear': 'commits.notLinear',
213
+ }
214
+
215
+ /** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */
216
+ const BASE_FAILURE: Partial<Record<string, ForgePanelKey>> = {
217
+ 'forgePanel/base-missing': 'diff.baseMissing',
218
+ 'forgePanel/no-fork-point': 'diff.baseUnrelated',
219
+ }
220
+
221
+ /**
222
+ * Explain a failure of the `branch` scope that its chosen base branch caused.
223
+ * @param failed - code of the failed read, or null.
224
+ * @param base - branch the read compared with, or null for the automatic fork point and other scopes.
225
+ * @param t - forge panel copy.
226
+ * @returns the message naming the branch, or undefined for another failure or without a chosen branch.
227
+ */
228
+ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: Translate): string | undefined {
229
+ const key = failed === null ? undefined : BASE_FAILURE[failed]
230
+ return key === undefined || base === null ? undefined : t(key, { base: base.name })
231
+ }
232
+
233
+ /**
234
+ * Read the changes a view shows. The whole change request also reads the host's viewed marks at the head of the latest
235
+ * status, beside the diff; marks read at another head refuse the read as the diff refuses a moved head.
236
+ * @param source - local changes or a change request.
237
+ * @param scope - local scope to read.
238
+ * @param commits - chosen commits of a change request, or null for all of it.
239
+ * @param head - head commit of the change request's latest status, or null.
240
+ * @param reads - the Remote reads.
241
+ * @param signal - cancellation of the reads.
242
+ * @returns the changes, or why they could not be read.
243
+ */
244
+ async function readChanges(
245
+ source: ChangesSource,
246
+ scope: ForgeLocalScope,
247
+ commits: ForgeCommitRange | null,
248
+ head: string | null,
249
+ reads: Pick<ChangesTabInjected, 'localDiff' | 'changeRequestDiff' | 'changeRequestViewed'>,
250
+ signal: AbortSignal,
251
+ ): Promise<RemoteResult<ChangesData>> {
252
+ if (source.kind === 'local') {
253
+ const result = await reads.localDiff(scope, signal)
254
+ if (!result.ok) return result
255
+ const { files, base, omitted } = result.value
256
+ return { ok: true, value: { kind: 'local', files, scope, base, omitted } }
257
+ }
258
+ const [result, marks] = await Promise.all([
259
+ reads.changeRequestDiff(source.url, commits, signal),
260
+ commits === null && head !== null && head !== '' ? reads.changeRequestViewed(source.url, head, signal) : Promise.resolve(null),
261
+ ])
262
+ if (!result.ok) return result
263
+ if (marks !== null && !marks.ok && marks.error.code === 'forgePanel/stale-head') return marks
264
+ const { files, headSha, localAhead, fileUrls } = result.value
265
+ const viewed = hostViewedOf(marks, headSha)
266
+ return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls, viewed } }
267
+ }
268
+
269
+ /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */
270
+ function baseRefOf(scope: ForgeLocalScope): string | null {
271
+ return scope.kind === 'branch' ? scope.base : null
272
+ }
273
+
274
+ /** The commits a local scope shows, or null for all of them and for scopes other than `branch`. */
275
+ function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null {
276
+ return scope.kind === 'branch' ? scope.commits : null
277
+ }
278
+
279
+ /** The source review comments on loaded changes record: the change request head, or the local scope with its base. */
280
+ function reviewSourceOf(data: ChangesData): ReviewSource {
281
+ return data.kind === 'local'
282
+ ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope) }
283
+ : { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits }
284
+ }
285
+
286
+ /**
287
+ * Identity of a diff source for viewed marks: the change request or local scope with its base ref and chosen commits.
288
+ * A change request's marks stay across head commits, so a file whose change a new push altered reads as changed.
289
+ */
290
+ function viewedSourceOf(source: ReviewSource): string {
291
+ return JSON.stringify(source.kind === 'local'
292
+ ? ['local', source.scope, source.baseRef, source.commits]
293
+ : ['change', source.url, source.commits])
294
+ }
295
+
296
+ /**
297
+ * The files that start expanded: every file not marked viewed until those above it change more than {@link OPEN_LINES} lines.
298
+ * @param files - every file in display order.
299
+ * @param marks - the viewed marks when the files loaded.
300
+ * @returns the paths of the expanded files.
301
+ */
302
+ function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): ReadonlySet<string> {
303
+ const open = new Set<string>()
304
+ let above = 0
305
+ for (const file of files) {
306
+ if (above > OPEN_LINES) break
307
+ if (viewedStateOf(marks, file.path, file.digest) === 'viewed') continue
308
+ open.add(file.path)
309
+ above += drawnLines(file)
310
+ }
311
+ return open
312
+ }
313
+
314
+ /** Whether a file shows under a lens while test files hide or not. */
315
+ function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean {
316
+ return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens)
317
+ }
318
+
319
+ /** What a rename badge names: the old file name, or the old path when only the directory changed. */
320
+ function renamedFrom(previous: string, path: string): string {
321
+ const name = pathPartsOf(previous).name
322
+ return name === pathPartsOf(path).name ? previous : name
323
+ }
324
+
325
+ /** The hover text of a file's path: both paths of a renamed file, else the path. */
326
+ function pathTooltipOf(file: ForgeDiffFile, t: Translate): string {
327
+ return file.status === 'renamed' && file.previousPath !== null ? t('diff.renamedPath', { from: file.previousPath, path: file.path }) : file.path
328
+ }
329
+
330
+ /** The badge after a path: how the file changed, and whether a branch view's file is untracked. */
331
+ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string {
332
+ const parts: string[] = []
333
+ if (file.status === 'added') parts.push(t('diff.newFile'))
334
+ else if (file.status === 'deleted') parts.push(t('diff.deletedFile'))
335
+ else if (file.status === 'renamed' && file.previousPath !== null) parts.push(t('diff.renamed', { from: renamedFrom(file.previousPath, file.path) }))
336
+ if (file.untracked && data.kind === 'local' && data.scope.kind === 'branch') parts.push(t('diff.badgeUncommitted'))
337
+ return parts.join(' · ')
338
+ }
339
+
340
+ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: {
341
+ readonly url: string
342
+ readonly entry: ForgePanelChangeRequest | undefined
343
+ /** Commit picker left of the review button. */
344
+ readonly commitMenu: ReactNode
345
+ readonly reviewCount: number
346
+ readonly reviewDisabled: boolean
347
+ readonly onReview: () => void
348
+ readonly openLink: (url: string) => void
349
+ readonly t: Translate
350
+ }): ReactNode {
351
+ const snapshot = entry?.snapshot ?? null
352
+ const number = numberOf(entry ?? { ref: null, url })
353
+ const tone = toneOf(snapshot)
354
+ const href = snapshot === null ? url : snapshot.url
355
+ return (
356
+ <div className={css.header}>
357
+ <ChangeRequestGlyph tone={tone} label={t('change.stateAria', { state: t(TONE_LABEL[tone]) })} />
358
+ <span className={css.headerTitle}>{snapshot === null ? url : snapshot.title}</span>
359
+ {number !== null && <span className={css.headerNumber}>{t('change.number', { number })}</span>}
360
+ <span className={css.headerEnd}>
361
+ {commitMenu}
362
+ <Button size="sm" variant="outline" className={css.headerAction} disabled={reviewDisabled} onClick={onReview}>
363
+ {t('review.submit')}{reviewCount > 0 ? ` (${reviewCount})` : ''}
364
+ </Button>
365
+ </span>
366
+ <Tooltip label={t('change.view')} side="bottom">
367
+ <button type="button" className={css.tool} aria-label={t('change.view')} onClick={() => { openLink(href) }}>
368
+ <IconRightUpOutlineRegular size={14} />
369
+ </button>
370
+ </Tooltip>
371
+ </div>
372
+ )
373
+ }
374
+
375
+ /**
376
+ * The local view's header: for the `branch` scope, the checked-out branch, the base branch picker, and a note
377
+ * that uncommitted changes count; for another scope, what it compares.
378
+ */
379
+ function LocalHeader({ state, scope, base, missing, visible, diffBases, choose, commitMenu, createChangeRequest, t }: {
380
+ readonly state: ForgePanelState | null
381
+ /** Commit picker of the `branch` scope, left of the create button. */
382
+ readonly commitMenu: ReactNode
383
+ readonly scope: ScopeKind
384
+ readonly base: ForgeBaseBranch | null
385
+ /** Whether the chosen base branch no longer exists. */
386
+ readonly missing: boolean
387
+ readonly visible: boolean
388
+ readonly diffBases: ChangesTabInjected['diffBases']
389
+ readonly choose: (base: ForgeBaseBranch | null) => void
390
+ readonly createChangeRequest: () => void
391
+ readonly t: Translate
392
+ }): ReactNode {
393
+ const creatable = state !== null && state.repository !== null && openChangeRequestOf(state) === undefined
394
+ const checkout = state?.checkout.state === 'ready' ? state.checkout.checkout : null
395
+ const head = checkout?.branch ?? checkout?.commit ?? 'HEAD'
396
+ return (
397
+ <div className={css.header}>
398
+ {scope === 'branch' ? <>
399
+ <span className={css.headerIcon}><IconBranchOutlineRegular size={15} /></span>
400
+ <Tooltip label={head} side="bottom">
401
+ <span className={css.headerHead} tabIndex={0} data-forge-head="">{head}</span>
402
+ </Tooltip>
403
+ <span className={css.headerArrow} aria-hidden="true">→</span>
404
+ <BaseMenu chosen={base} label={base?.name ?? state?.local?.base ?? t('diff.base.automatic')} missing={missing}
405
+ visible={visible} list={diffBases} choose={choose} t={t} />
406
+ <span className={clsx(css.headerNote, css.headerSuffix)}>{t('diff.base.uncommitted')}</span>
407
+ </> : <>
408
+ <span className={css.headerIcon}><IconListPenOutlineRegular size={15} /></span>
409
+ <span className={css.headerNote}>{t(SCOPE_NOTE[scope])}</span>
410
+ </>}
411
+ {(scope === 'branch' || creatable) && <span className={css.headerEnd}>
412
+ {scope === 'branch' && commitMenu}
413
+ {creatable && <Button size="sm" variant="outline" className={css.headerAction} onClick={createChangeRequest}>{t('changes.local.create')}</Button>}
414
+ </span>}
415
+ </div>
416
+ )
417
+ }
418
+
419
+ function ScopeMenu({ scope, choose, t }: {
420
+ readonly scope: ScopeKind
421
+ readonly choose: (scope: ScopeKind) => void
422
+ readonly t: Translate
423
+ }): ReactNode {
424
+ const [open, setOpen] = useState(false)
425
+ const items: MenuEntry[] = [
426
+ { id: 'uncommitted', label: t(SCOPE_LABEL.uncommitted) },
427
+ { id: 'unstaged', label: t(SCOPE_LABEL.unstaged) },
428
+ { id: 'staged', label: t(SCOPE_LABEL.staged) },
429
+ { type: 'separator', id: 'separator' },
430
+ { id: 'branch', label: t(SCOPE_LABEL.branch) },
431
+ ]
432
+ return (
433
+ <Menu
434
+ open={open}
435
+ portal
436
+ align="start"
437
+ dense
438
+ autoFocus
439
+ selectedId={scope}
440
+ items={items}
441
+ onClose={() => { setOpen(false) }}
442
+ onSelect={(id) => {
443
+ setOpen(false)
444
+ choose(id as ScopeKind)
445
+ }}
446
+ anchor={(
447
+ <button type="button" className={css.select} aria-haspopup="menu" aria-expanded={open} data-forge-scope={scope}
448
+ onClick={() => { setOpen(value => !value) }}>
449
+ {t(SCOPE_LABEL[scope])}
450
+ <IconChevronDownOutlineRegular size={12} />
451
+ </button>
452
+ )}
453
+ />
454
+ )
455
+ }
456
+
457
+ function Notice({ children, action }: { readonly children: ReactNode; readonly action?: ReactNode }): ReactNode {
458
+ return (
459
+ <div className={css.notice} role="status">
460
+ <IconInfoOutlineRegular size={14} />
461
+ <span>{children}</span>
462
+ {action}
463
+ </div>
464
+ )
465
+ }
466
+
467
+
468
+ function OrphanReviews({ path, actions, t }: PropsLocale<typeof NS> & {
469
+ readonly path: string
470
+ readonly actions: ReviewActions
471
+ }): ReactNode {
472
+ const state = useFileReview(actions, path)
473
+ return <section className={css.reviewFile} data-forge-review-file={path}>
474
+ <h3>{path}</h3>
475
+ {state.threads.map(thread => <ReviewThread key={thread.key} thread={thread}
476
+ actions={actions} locked={state.locked} outdated t={t} />)}
477
+ </section>
478
+ }
479
+
480
+ /**
481
+ * Render the changes tab of one Session.
482
+ * @param props - tab information, the tab's choices, the panel snapshot hook, reads and actions, and copy.
483
+ * @returns the view body.
484
+ */
485
+ export function ChangesTab({
486
+ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff,
487
+ changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed,
488
+ openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t,
489
+ }: ChangesTabProps): ReactNode {
490
+ const { tab } = useTabInfo()
491
+ const { navigation, signal } = tab
492
+ const target = useMemo(() => parseChangesAddress(tab.contentId), [tab.contentId])
493
+ if (target === undefined) throw new Error(`forge-panel: not a changes address "${tab.contentId}"`)
494
+ const source = target.source
495
+ const queue = reviewQueue(tab)
496
+ useSyncExternalStore(queue.subscribe, queue.getStatus)
497
+ const reviewState = queue.getSnapshot()
498
+ const [reviewOpen, setReviewOpen] = useState(false)
499
+ const [reviewBusy, setReviewBusy] = useState(false)
500
+ useEffect(() => { if (!tab.visible) setReviewOpen(false) }, [tab.visible])
501
+ const reviewRunning = useRef(false)
502
+ const [reviewError, setReviewError] = useState<string | null>(null)
503
+ const publishReview = async (
504
+ url: string, request: ForgeReviewRequest, complete: (url: string) => boolean,
505
+ ): Promise<string | undefined> => {
506
+ if (reviewRunning.current || !queue.begin(request)) return t('review.saveFailed')
507
+ reviewRunning.current = true
508
+ setReviewBusy(true)
509
+ setReviewError(null)
510
+ try {
511
+ const response = await submitReview(url, request)
512
+ if (!response.ok || (!response.value.ok && response.value.code === 'unknown')) {
513
+ setReviewError(t('review.unknown'))
514
+ return t('review.unknown')
515
+ }
516
+ const result = response.value
517
+ if (!result.ok) {
518
+ queue.finish(false)
519
+ const message = result.code === 'stale' ? t('review.stale') : result.code === 'unsupported'
520
+ ? t('review.unsupported') : t('review.failed', { message: result.message })
521
+ setReviewError(message)
522
+ return message
523
+ }
524
+ if (!complete(result.url)) return t('review.unknown')
525
+ report(request.kind === 'review' ? 'review.submitted' : 'review.published')
526
+ if (request.kind === 'review') setReviewOpen(false)
527
+ return undefined
528
+ } catch (_error) {
529
+ setReviewError(t('review.unknown'))
530
+ return t('review.unknown')
531
+ } finally {
532
+ reviewRunning.current = false
533
+ setReviewBusy(false)
534
+ }
535
+ }
536
+ // Every write that may have changed the threads reads them again; writes run one at a time, so a write that starts a
537
+ // pending review settles before the next write looks for one.
538
+ const [reviewRevision, setReviewRevision] = useState(0)
539
+ const writing = useRef<Promise<unknown>>(Promise.resolve())
540
+ /**
541
+ * Send one write after the earlier ones.
542
+ * @returns undefined once the host took it, else its message and whether its outcome is unknown.
543
+ */
544
+ const sendWrite = (url: string, write: ForgeReviewWrite): Promise<WriteRefusal | undefined> => {
545
+ const run = async (): Promise<WriteRefusal | undefined> => {
546
+ const response = await changeRequestReviewWrite(url, write)
547
+ if (!response.ok) {
548
+ if (response.error.code === 'forgePanel/not-bound') {
549
+ return { message: t('thread.writeFailed', { message: response.error.message }), unknown: false }
550
+ }
551
+ setReviewRevision(value => value + 1)
552
+ return { message: t('thread.writeUnknown'), unknown: true }
553
+ }
554
+ const result = response.value
555
+ if (result.ok) {
556
+ setReviewRevision(value => value + 1)
557
+ return undefined
558
+ }
559
+ switch (result.code) {
560
+ case 'unsupported': return { message: t('thread.writeUnsupported'), unknown: false }
561
+ case 'failed':
562
+ setReviewRevision(value => value + 1)
563
+ return { message: t('thread.writeFailed', { message: result.message }), unknown: false }
564
+ case 'stale': return { message: t('thread.writeStale'), unknown: false }
565
+ case 'unknown':
566
+ setReviewRevision(value => value + 1)
567
+ return { message: t('thread.writeUnknown'), unknown: true }
568
+ /* v8 ignore next -- closed ForgeReviewWriteResult code union exhaustiveness guard */
569
+ default: return assertNever(result.code, 'ForgeReviewWriteResult.code')
570
+ }
571
+ }
572
+ const next = writing.current.then(run, run)
573
+ writing.current = next
574
+ return next
575
+ }
576
+ const writeReview = async (url: string, write: ForgeReviewWrite): Promise<string | undefined> => (await sendWrite(url, write))?.message
577
+ const choices = useStore(store => store.byTab[tab.id])
578
+ const [wanted, setWanted] = useState<Wanted | null>(null)
579
+ const [treeState, setTreeState] = useState<ChangedFilesState>({ query: '', collapsed: {}, selected: null })
580
+ const [treePosition, setTreePosition] = useState<FileTreePosition>('left')
581
+ const [treeWidth, setTreeWidth] = useState(0)
582
+ const treeId = useId()
583
+ const [chosen, setChosen] = useState<Readonly<Record<string, boolean>>>({})
584
+ // Each navigation applies once; its file, if it names one, opens and scrolls into view.
585
+ useEffect(() => {
586
+ if (choices?.navigated === navigation.revision) return
587
+ actions.navigated(tab.id, navigation.revision)
588
+ const path = navigation.params?.path
589
+ if (path === undefined) return
590
+ setTreeState(value => ({ ...value, selected: path }))
591
+ setChosen(value => ({ ...value, [path]: true }))
592
+ setWanted({ path, center: null })
593
+ }, [choices, navigation.revision, navigation.params, actions, tab.id])
594
+ // The tab's choices end with its record.
595
+ useEffect(() => {
596
+ const unmounted = new AbortController()
597
+ signal.addEventListener('abort', () => { actions.forget(tab.id) }, { once: true, signal: unmounted.signal })
598
+ return () => { unmounted.abort() }
599
+ }, [signal, actions, tab.id])
600
+ const [attempt, setAttempt] = useState(0)
601
+ useEffect(() => tab.actions.bindCommands({ refresh: () => { setAttempt(value => value + 1) } }), [tab.actions])
602
+ const snapshot = usePanel(tab.visible ? 'visible' : 'inactive')
603
+ const state = snapshot?.state ?? null
604
+ const scope = choices?.scope ?? 'branch'
605
+ const base = choices?.base ?? null
606
+ const chosenCommits = choices?.commits ?? null
607
+ const lens = choices?.lens ?? 'all'
608
+ const hideTests = choices?.hideTests ?? false
609
+ const localScope = useMemo((): ForgeLocalScope => scope === 'branch'
610
+ ? { kind: 'branch', base: base?.ref ?? null, commits: chosenCommits } : { kind: scope }, [scope, base, chosenCommits])
611
+ const changeCommits = source.kind === 'change' ? chosenCommits : null
612
+ const changeUrlOf = source.kind === 'change' ? source.url : ''
613
+ const listChangeCommits = useCallback(
614
+ (signal: AbortSignal) => changeRequestCommits(changeUrlOf, signal), [changeRequestCommits, changeUrlOf],
615
+ )
616
+ const baseRef = base?.ref ?? null
617
+ const listLocalCommits = useCallback((signal: AbortSignal) => localCommits(baseRef, signal), [localCommits, baseRef])
618
+ const split = choices?.split ?? true
619
+ const wrap = choices?.wrap ?? true
620
+ const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined
621
+ // A read starts once the panel state arrives and again when what it describes moves. A change request's read
622
+ // also waits for its first status, which names the head, unless no provider serves it or its first poll failed.
623
+ const pending = entry !== undefined && entry.ref !== null && entry.update === null
624
+ const head = entry?.snapshot?.headSha ?? (pending ? null : '')
625
+ const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head
626
+ const headCommit = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.commit : null
627
+ // The commits change with the head of a change request, with the local HEAD, branch, or base, and on a refresh.
628
+ const commitsVersion = `${attempt}\n${source.kind === 'local'
629
+ ? `${baseRef ?? ''}\n${headCommit ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? ''}`
630
+ const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}`
631
+ const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null)
632
+ const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null)
633
+ // Names the read the inputs ask for; it is in flight until `finished` matches it.
634
+ const read = version === null ? null : `${dataKey}\n${navigation.revision}\n${attempt}\n${version}`
635
+ const [finished, setFinished] = useState<string | null>(null)
636
+ // A change request read refused because the head moved past its status stays in flight until a status later than
637
+ // the one the read started with arrives; one that arrived during the read starts the next read at once.
638
+ const statusAt = entry?.update?.fetchedAt ?? null
639
+ const latestStatusAt = useRef(statusAt)
640
+ useEffect(() => { latestStatusAt.current = statusAt }, [statusAt])
641
+ const [refused, setRefused] = useState<{ readonly read: string; readonly statusAt: number | null } | null>(null)
642
+ const waiting = refused !== null && refused.read === read && refused.statusAt === statusAt
643
+ useEffect(() => {
644
+ if (!tab.visible || read === null || read === finished || waiting) return
645
+ const controller = new AbortController()
646
+ const readAt = latestStatusAt.current
647
+ void readChanges(source, localScope, changeCommits, head, { localDiff, changeRequestDiff, changeRequestViewed }, controller.signal)
648
+ .then((result) => {
649
+ if (controller.signal.aborted) return
650
+ if (!result.ok && result.error.code === 'forgePanel/stale-head') {
651
+ setRefused({ read, statusAt: readAt })
652
+ setFailure(null)
653
+ return
654
+ }
655
+ setFinished(read)
656
+ if (result.ok) {
657
+ setLoaded({ key: dataKey, data: result.value })
658
+ setFailure(null)
659
+ } else {
660
+ setFailure({ key: dataKey, code: result.error.code })
661
+ }
662
+ })
663
+ return () => { controller.abort() }
664
+ }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, head, dataKey, localDiff, changeRequestDiff,
665
+ changeRequestViewed])
666
+ const data = loaded !== null && loaded.key === dataKey ? loaded.data : null
667
+ // Threads show only while they were read at the head of the latest status and, for the whole change request, at
668
+ // the head the shown diff was read at, so their positions number the shown files.
669
+ const prHead = entry?.snapshot?.headSha ?? null
670
+ const prAuthor = entry?.snapshot?.author ?? null
671
+ const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead,
672
+ updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision, read: changeRequestReview })
673
+ const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead
674
+ && (data.commits !== null || data.headSha === prHead) ? threadRead.review : null
675
+ const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null)
676
+ const [threadList, setThreadList] = useState<{
677
+ readonly open: boolean
678
+ readonly filter: ThreadFilter
679
+ /** Whether the reader just opened the list and it has not taken the focus yet. */
680
+ readonly claim: boolean
681
+ }>({ open: false, filter: 'unresolved', claim: false })
682
+ const threadsToggle = useRef<HTMLButtonElement>(null)
683
+ const [focus, setFocus] = useState<ThreadFocus | null>(null)
684
+ const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data])
685
+ const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests])
686
+ const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item,
687
+ allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record<ChangesLens, number>, [allFiles, hideTests])
688
+ const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data])
689
+ const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource)
690
+ const localMarks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey))
691
+ const hostOwner = useMemo(() => data?.kind === 'change' && data.viewed !== null
692
+ ? { url: data.url, headSha: data.headSha, files: data.files, viewed: data.viewed } : null, [data])
693
+ const host = useHostViewed(hostOwner, setFileViewed, (failure) => {
694
+ if (failure.kind === 'stale') report('viewed.syncStale')
695
+ else if (failure.kind === 'unknown') report('viewed.syncUnknown', { message: failure.message })
696
+ else report('viewed.syncFailed', { message: failure.message })
697
+ })
698
+ const marks = host?.marks ?? localMarks
699
+ // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again.
700
+ const rereading = read !== null && finished !== read && data !== null
701
+ const failed = failure !== null && failure.key === dataKey ? failure.code : null
702
+ const [expansion, setExpansion] = useState<Expansion>({ data: null, texts: {}, open: {} })
703
+ const current = expansion.data === data ? expansion : { data, texts: {}, open: {} }
704
+ const latest = useRef(data)
705
+ useEffect(() => { latest.current = data }, [data])
706
+ const [revealed, setRevealed] = useState<ReadonlySet<string>>(new Set())
707
+ // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays
708
+ // collapsed while it is marked viewed unless the reader expands it; a file whose change differs from its mark expands
709
+ // like an unmarked one.
710
+ const initial = useMemo(() => initiallyOpen(allFiles, marks), [allFiles])
711
+ const expandedByDefault = (file: ForgeDiffFile): boolean => initial.has(file.path) && viewedStateOf(marks, file.path, file.digest) !== 'viewed'
712
+ const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file)
713
+ const sections = useRef(new Map<string, HTMLElement>())
714
+ const scrollport = useRef<HTMLDivElement | null>(null)
715
+ const toolbarRow = useRef<HTMLDivElement>(null)
716
+ useLayoutEffect(() => {
717
+ const row = toolbarRow.current
718
+ /* v8 ignore next -- the toolbar row renders in every state of the view */
719
+ if (row === null) return
720
+ return observeToolbarFold(row)
721
+ }, [])
722
+ const reach = useMemo(() => new SectionReach(), [])
723
+ const attachScrollport = useCallback((element: HTMLDivElement | null) => {
724
+ scrollport.current = element
725
+ reach.attach(element)
726
+ }, [reach])
727
+ // A short final file cannot align with the viewport top; retain its jump until the reader scrolls away.
728
+ const jumpPosition = useRef<{ readonly data: ChangesData; readonly top: number } | null>(null)
729
+ useLayoutEffect(() => {
730
+ if (!tab.visible || wanted === null || data === null) return
731
+ // A file the lens or the test switch hides is shown before the view scrolls to it.
732
+ const hidden = allFiles.find(file => file.path === wanted.path && !shownBy(file, lens, hideTests))
733
+ if (hidden !== undefined) {
734
+ if (lens !== 'all') actions.lensed(tab.id, 'all')
735
+ if (hideTests && hidden.layer === 'test') actions.toggledTests(tab.id)
736
+ return
737
+ }
738
+ // The browser's scroll anchoring keeps the section in place while the sections above it draw their lines.
739
+ const section = sections.current.get(wanted.path)
740
+ section?.scrollIntoView({ block: 'start' })
741
+ // A thread the reader opened from the thread list or a file's unresolved count centers inside its file, which the jump
742
+ // expanded and revealed; the jump ends here, so a later jump to the file stops at its header.
743
+ const { center } = wanted
744
+ if (center !== null) {
745
+ /* v8 ignore next 4 -- a centered thread's file is drawn and its card unfolded, so both are found. */
746
+ const card = [...section?.querySelectorAll<HTMLElement>('[data-forge-thread]') ?? []]
747
+ .find(element => element.dataset.forgeThread === center.id)
748
+ card?.scrollIntoView({ block: 'center' })
749
+ if (center.focus) card?.focus({ preventScroll: true })
750
+ }
751
+ if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop }
752
+ setWanted(null)
753
+ }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id])
754
+ const refresh = (): void => { setAttempt(value => value + 1) }
755
+ const root = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.root : null
756
+ // A chosen base branch that is gone or shares no history with HEAD offers the automatic fork point instead.
757
+ const baseFailure = baseFailureOf(failed, source.kind === 'local' && scope === 'branch' ? base : null, t)
758
+ // Configuration reads may recover after the user fixes Git settings or raises the output limit.
759
+ const message = failed === null ? undefined : FAILURE[failed]
760
+ const failureText = baseFailure ?? t(message ?? 'diff.error')
761
+ const changeUrl = source.kind === 'change' ? entry?.snapshot?.url ?? source.url : null
762
+ const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed')
763
+ const automaticBase = baseFailure !== undefined ? (
764
+ <Button size="sm" variant="outline" onClick={() => { actions.based(tab.id, null) }}>{t('diff.useAutomaticBase')}</Button>
765
+ ) : (failed === 'forgePanel/commits-missing' || failed === 'forgePanel/commits-not-linear') && (
766
+ <Button size="sm" variant="outline" onClick={() => { actions.committed(tab.id, null) }}>{t('commits.showAll')}</Button>
767
+ )
768
+
769
+ /** Apply a change to the unchanged lines of `owner`, unless newer changes replaced it. */
770
+ const update = (owner: ChangesData, change: (value: Expansion) => Expansion): void => {
771
+ setExpansion((previous) => {
772
+ if (latest.current !== owner) return previous
773
+ return change(previous.data === owner ? previous : { data: owner, texts: {}, open: {} })
774
+ })
775
+ }
776
+ const expand = (owner: ChangesData, file: ForgeDiffFile, index: number): void => {
777
+ const path = file.path
778
+ update(owner, value => ({ ...value, open: { ...value.open, [path]: new Set([...value.open[path] ?? [], index]) } }))
779
+ if (current.texts[path] !== undefined) return
780
+ update(owner, value => ({ ...value, texts: { ...value.texts, [path]: 'loading' } }))
781
+ const reading = owner.kind === 'local' ? localText(owner.scope, path) : changeRequestText(owner.url, owner.headSha, path)
782
+ void reading.then((result) => {
783
+ const lines = result.ok ? textLines(result.value) : undefined
784
+ if (lines !== undefined && matchesHunks(lines, file.hunks)) {
785
+ update(owner, value => ({ ...value, texts: { ...value.texts, [path]: lines } }))
786
+ return
787
+ }
788
+ if (result.ok) report('toast.expandStale')
789
+ else report('toast.expandFailed', { message: result.error.message })
790
+ update(owner, (value) => {
791
+ const { [path]: _text, ...texts } = value.texts
792
+ const { [path]: _open, ...open } = value.open
793
+ return { ...value, texts, open }
794
+ })
795
+ })
796
+ }
797
+ const fileActions = (owner: ChangesData, file: ForgeDiffFile): DiffFileAction[] => {
798
+ const list: DiffFileAction[] = [{ label: 'diff.copyPath', run: () => { copyPath(file.path) } }]
799
+ if (file.status === 'deleted') return list
800
+ if (owner.kind === 'local') {
801
+ if (root !== null) {
802
+ list.push({ label: 'diff.openFileInSidebar', run: () => { tab.actions.openResource(fileAddressFor(sessionId, undefined, `${root}/${file.path}`)) } })
803
+ }
804
+ } else {
805
+ const url = owner.fileUrls[file.path]
806
+ if (url !== undefined) list.push({ label: 'diff.openFileInBrowser', run: () => { openLink(url) } })
807
+ }
808
+ return list
809
+ }
810
+
811
+ // A review addresses the head commit, so it is submitted from the view of the whole change request. A pending review on
812
+ // the code host is submitted or discarded there; without one, the summary and any comment drafts kept in the browser
813
+ // are published as one review.
814
+ const pendingReview = review?.pendingReview ?? null
815
+ // Logins compare without case, as GitHub's do.
816
+ const ownChangeRequest = review?.viewer != null && prAuthor !== null && review.viewer.toLowerCase() === prAuthor.toLowerCase()
817
+ const finishWrite = async (send: () => Promise<string | undefined>, done: ForgePanelKey): Promise<void> => {
818
+ if (reviewRunning.current) return
819
+ reviewRunning.current = true
820
+ setReviewBusy(true)
821
+ setReviewError(null)
822
+ try {
823
+ const failure = await send()
824
+ if (failure !== undefined) {
825
+ setReviewError(failure)
826
+ return
827
+ }
828
+ report(done)
829
+ setReviewOpen(false)
830
+ } finally {
831
+ reviewRunning.current = false
832
+ setReviewBusy(false)
833
+ }
834
+ }
835
+ const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && data.commits === null && <SubmitReview queue={queue}
836
+ url={data.url} headSha={data.headSha} pending={pendingReview} own={ownChangeRequest} busy={reviewBusy} error={reviewError}
837
+ close={() => { setReviewOpen(false) }}
838
+ check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }}
839
+ submit={() => {
840
+ const latest = queue.getSnapshot()
841
+ if (pendingReview === null) {
842
+ void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event,
843
+ body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url))
844
+ return
845
+ }
846
+ // The submission is kept as the write to reconcile until the host answers, so an unknown outcome blocks another
847
+ // submission, which would otherwise publish a second review once the pending review no longer reads.
848
+ void finishWrite(async () => {
849
+ if (!queue.begin({ kind: 'review', headSha: data.headSha, event: latest.event, body: latest.body, comments: [] })) {
850
+ return t('review.saveFailed')
851
+ }
852
+ const refusal = await sendWrite(data.url, { kind: 'submit-pending', headSha: data.headSha, review: pendingReview.id,
853
+ event: latest.event, body: latest.body })
854
+ if (refusal === undefined) {
855
+ if (!queue.finish(true)) report('review.saveFailed')
856
+ return undefined
857
+ }
858
+ if (!refusal.unknown) queue.finish(false)
859
+ return refusal.message
860
+ }, 'review.submitted')
861
+ }}
862
+ discard={pendingReview === null ? undefined : () => {
863
+ void finishWrite(() => writeReview(data.url, { kind: 'discard-pending', headSha: data.headSha, review: pendingReview.id }), 'review.discarded')
864
+ }} t={t} />
865
+
866
+ /** Add a comment to the pending review on the code host at the head the comment was selected on. */
867
+ const addPending = (selection: ReviewSelection): Promise<string | undefined> => {
868
+ if (selection.source.kind !== 'change') return Promise.resolve(t('review.stale'))
869
+ const { path, side, startLine, endLine, body } = selection.comment
870
+ return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } })
871
+ }
872
+
873
+ const recordActions: ReviewActions = {
874
+ source: shownSource ?? (source.kind === 'local'
875
+ ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) }
876
+ : { kind: 'change', url: source.url, headSha: '', commits: changeCommits }),
877
+ records: queue, addToInput: addReviewToInput, openLink,
878
+ }
879
+ const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)]
880
+ .filter(item => sameReviewSource(item.source, recordActions.source)).map(item => item.comment.path))]
881
+ .filter(path => !data?.files.some(file => file.path === path))
882
+ const orphanRecords = absentPaths.map(path => <OrphanReviews key={path} path={path} actions={recordActions} t={t} />)
883
+
884
+ // Thread groups keep their identity across renders that change neither the threads nor what their cards share, so
885
+ // only the sections whose threads changed redraw.
886
+ const url = data?.kind === 'change' ? data.url : null
887
+ const threadActions = useMemo((): ThreadActions | null => review === null || url === null ? null : {
888
+ author: prAuthor,
889
+ addToInput: (thread, range) => addThreadToInput(thread, url, range),
890
+ openLink,
891
+ readText: (commit, path) => changeRequestText(url, commit, path),
892
+ inputFailed: () => { live.current.report('thread.inputFailed') },
893
+ focused: focus,
894
+ writes: {
895
+ write: (write: ThreadWrite) => live.current.writeReview(url, { ...write, headSha: review.headSha }),
896
+ reviewStarted: review.pendingReview !== null,
897
+ canReview: review.viewerCanReview,
898
+ },
899
+ }, [review, url, prAuthor, addThreadToInput, openLink, changeRequestText, focus])
900
+ const fileThreads = useMemo(() => new Map<string, FileThreads>(threadActions === null ? []
901
+ : [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions])
902
+ /** Show a file's next unresolved thread in display order after the one last shown, or its first. */
903
+ const nextThread = (path: string): void => {
904
+ const order = inFileOrder(placed.entries.filter(({ thread }) => thread.path === path && !thread.resolved),
905
+ allFiles.find(file => file.path === path))
906
+ const next = order[(order.findIndex(({ thread }) => thread.id === focus?.id) + 1) % order.length]
907
+ /* v8 ignore next -- the count that calls this shows only while the file has an unresolved thread. */
908
+ if (next !== undefined) openThread(next, false)
909
+ }
910
+ /** Close the thread list at the reader's request and return the focus to its toggle. */
911
+ const closeThreadList = (): void => {
912
+ setThreadList(value => ({ ...value, open: false }))
913
+ threadsToggle.current?.focus()
914
+ }
915
+ /**
916
+ * Show a thread: all commits for a thread the chosen ones do not hold, whose diff holds the file of every thread with a
917
+ * position at the head, then its file, with the thread unfolded and centered; `focusCard` moves the focus to it. A
918
+ * thread on a file the shown changes lack opens on the host.
919
+ */
920
+ const openThread = ({ thread, place }: PlacedThread, focusCard: boolean): void => {
921
+ if (place.kind === 'elsewhere') actions.committed(tab.id, null)
922
+ else if (!allFiles.some(file => file.path === thread.path)) {
923
+ const url = thread.comments[0]?.url ?? null
924
+ if (url !== null) openLink(url)
925
+ return
926
+ }
927
+ setFocus(value => ({ id: thread.id, revision: (value?.revision ?? 0) + 1 }))
928
+ setRevealed(value => new Set([...value, thread.path]))
929
+ jump(thread.path, { id: thread.id, focus: focusCard })
930
+ }
931
+ const jump = (path: string, center: Wanted['center'] = null): void => {
932
+ setTreeState(value => ({ ...value, selected: path }))
933
+ setChosen(value => ({ ...value, [path]: true }))
934
+ setWanted({ path, center })
935
+ }
936
+ /**
937
+ * The file being read: the file last jumped to while the scroll stays there, else the first file whose section still
938
+ * reaches below the viewport top, so the gap between two cards at the top belongs to the file after it; past the last
939
+ * section, the last file.
940
+ */
941
+ const currentIndex = (viewport: HTMLElement): number => {
942
+ const remembered = jumpPosition.current
943
+ const index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop
944
+ ? files.findIndex(file => file.path === treeState.selected) : -1
945
+ if (index >= 0) return index
946
+ const top = viewport.getBoundingClientRect().top
947
+ const reading = files.findIndex((file) => {
948
+ const section = sections.current.get(file.path)
949
+ return section !== undefined && section.getBoundingClientRect().bottom > top + 1
950
+ })
951
+ return reading >= 0 ? reading : Math.max(0, files.length - 1)
952
+ }
953
+ /** Whether a key press belongs to a field, a comment, a menu, or a text selection rather than to the file list. */
954
+ const typing = (container: HTMLElement, origin: EventTarget): boolean => {
955
+ const selection = window.getSelection()
956
+ return !(origin instanceof HTMLElement) || !container.contains(origin)
957
+ || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment], [role="menu"]') !== null
958
+ || (selection !== null && !selection.isCollapsed)
959
+ }
960
+ const navigateFiles = (event: KeyboardEvent<HTMLDivElement>): void => {
961
+ if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing
962
+ || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey
963
+ || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) return
964
+ const viewport = event.currentTarget
965
+ if (typing(viewport, event.target)) return
966
+ const index = currentIndex(viewport)
967
+ event.preventDefault()
968
+ event.stopPropagation()
969
+ const next = files[index + (event.key === 'ArrowRight' ? 1 : -1)]
970
+ if (next === undefined) return
971
+ viewport.focus({ preventScroll: true })
972
+ jump(next.path)
973
+ }
974
+ /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */
975
+ const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => {
976
+ if (host !== null) {
977
+ if (!host.mark(file.path, viewed)) return
978
+ } else if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) {
979
+ report('viewed.saveFailed')
980
+ return
981
+ }
982
+ const section = sections.current.get(file.path)
983
+ const viewport = scrollport.current
984
+ if (viewed && section !== undefined && viewport !== null
985
+ && section.getBoundingClientRect().top < viewport.getBoundingClientRect().top) setWanted({ path: file.path, center: null })
986
+ // A new mark collapses the file through its default; clearing a mark expands it.
987
+ setChosen(({ [file.path]: _choice, ...value }) => viewed ? value : { ...value, [file.path]: true })
988
+ }
989
+ /** The shown file whose section holds an element or a text node, if any. */
990
+ const fileAt = (target: EventTarget | null | undefined): ForgeDiffFile | undefined => {
991
+ const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null
992
+ const path = element?.closest('[data-forge-diff-file]')?.getAttribute('data-forge-diff-file')
993
+ return files.find(file => file.path === path)
994
+ }
995
+ // `V` marks or clears the file being read, from anywhere in the tab except fields, comments, and menus: the file
996
+ // holding the focus, else the one holding the text cursor, as after clicking its code, else the file at the top.
997
+ const toggleViewed = (event: KeyboardEvent<HTMLDivElement>): void => {
998
+ const viewport = scrollport.current
999
+ if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey
1000
+ || event.key.toLowerCase() !== 'v' || viewport === null || data === null || typing(event.currentTarget, event.target)) return
1001
+ const file = fileAt(event.target) ?? fileAt(window.getSelection()?.anchorNode) ?? files[currentIndex(viewport)]
1002
+ /* v8 ignore next -- the files region renders only while files show, so its position always names one */
1003
+ if (file === undefined) return
1004
+ event.preventDefault()
1005
+ markViewed(data, file, viewedStateOf(marks, file.path, file.digest) !== 'viewed')
1006
+ }
1007
+
1008
+ // What the section handlers and comment actions read when they run, replaced on every render. The assignment happens
1009
+ // during render rather than in an effect because the file menus read their actions while this same render draws them;
1010
+ // an effect would hand them the previous diff's links. A render React discards leaves values derived from the same
1011
+ // props and state, which the retried render assigns again.
1012
+ const callbacks = {
1013
+ data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, t,
1014
+ }
1015
+ const live = useRef(callbacks)
1016
+ live.current = callbacks
1017
+ const handlers = useMemo((): DiffFileHandlers => ({
1018
+ toggle: (file) => {
1019
+ const byDefault = live.current.expandedByDefault(file)
1020
+ setChosen(value => ({ ...value, [file.path]: !(value[file.path] ?? byDefault) }))
1021
+ },
1022
+ reveal: (path) => { setRevealed(value => new Set([...value, path])) },
1023
+ expand: (file, index) => {
1024
+ const { data: owner, expand: open } = live.current
1025
+ /* v8 ignore next -- sections render only while changes are loaded */
1026
+ if (owner !== null) open(owner, file, index)
1027
+ },
1028
+ view: (file, viewed) => {
1029
+ const { data: owner, markViewed: mark } = live.current
1030
+ /* v8 ignore next -- sections render only while changes are loaded */
1031
+ if (owner !== null) mark(owner, file, viewed)
1032
+ },
1033
+ actions: (file) => {
1034
+ const { data: owner, fileActions: list } = live.current
1035
+ /* v8 ignore next -- sections render only while changes are loaded */
1036
+ return owner === null ? [] : list(owner, file)
1037
+ },
1038
+ section: (path, element) => {
1039
+ if (element === null) sections.current.delete(path)
1040
+ else sections.current.set(path, element)
1041
+ },
1042
+ nextThread: (path) => { live.current.nextThread(path) },
1043
+ reach,
1044
+ }), [reach])
1045
+ const reviewStarted = pendingReview !== null
1046
+ const publishingBlocked = reviewState.uncertain !== null
1047
+ // Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments:
1048
+ // into its pending review once the threads say the user may review, and on their own while the user has no pending
1049
+ // review, since GitHub refuses a single comment beside one.
1050
+ const whole = data?.kind === 'change' && data.commits === null
1051
+ const queueable = whole && review?.viewerCanReview === true
1052
+ const single = whole && pendingReview === null
1053
+ const fileReview = useMemo((): ReviewActions | undefined => shownSource === null ? undefined : {
1054
+ source: shownSource,
1055
+ addToInput: addReviewToInput,
1056
+ records: queue, openLink, reviewStarted,
1057
+ onQuoted: (selection) => { if (!queue.recordAgent(selection)) live.current.report('review.saveFailed') },
1058
+ publishingBlocked,
1059
+ ...queueable ? { queue: (selection: ReviewSelection) => live.current.addPending(selection) } : {},
1060
+ ...single ? {
1061
+ publish: (selection: ReviewSelection) => selection.source.kind === 'change'
1062
+ ? live.current.publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment },
1063
+ url => queue.published(selection, url))
1064
+ : Promise.resolve(live.current.t('review.stale')),
1065
+ } : {},
1066
+ }, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single])
1067
+
1068
+ let body: ReactNode
1069
+ if (data === null) {
1070
+ if (state === null && snapshot?.disconnected) {
1071
+ body = (
1072
+ <div className={css.centered}>
1073
+ <span>{t('stream.failed')}</span>
1074
+ <Button size="sm" variant="outline" onClick={reconnect}>{t('retry')}</Button>
1075
+ </div>
1076
+ )
1077
+ } else if (failed === null) {
1078
+ body = <div className={css.centered}><StateDot state="ongoing" /></div>
1079
+ } else {
1080
+ body = (
1081
+ <div className={css.centered} role="status">
1082
+ <span>{failureText}</span>
1083
+ {(retry || changeUrl !== null || automaticBase !== false) && (
1084
+ <div className={css.actions}>
1085
+ {retry && <Button size="sm" variant="outline" onClick={refresh}>{t('retry')}</Button>}
1086
+ {automaticBase}
1087
+ {changeUrl !== null && (
1088
+ <Button size="sm" variant="outline" onClick={() => { openLink(changeUrl) }}>{t('diff.viewInBrowser')}</Button>
1089
+ )}
1090
+ </div>
1091
+ )}
1092
+ </div>
1093
+ )
1094
+ }
1095
+ } else if (data.files.length === 0) {
1096
+ body = <div className={css.files}>{orphanRecords}<div className={css.centered}>{t('diff.empty')}</div></div>
1097
+ } else if (files.length === 0) {
1098
+ body = <div className={css.files}>{orphanRecords}<div className={css.centered}>{t('lens.empty')}</div></div>
1099
+ } else {
1100
+ body = (
1101
+ <div ref={attachScrollport} className={css.files} data-forge-changes-scroll="" role="region"
1102
+ aria-label={t('diff.allFiles', { count: files.length })} aria-keyshortcuts="ArrowLeft ArrowRight V" tabIndex={0}
1103
+ onKeyDown={navigateFiles} onScroll={(event) => {
1104
+ if (jumpPosition.current?.top !== event.currentTarget.scrollTop) jumpPosition.current = null
1105
+ }}>
1106
+ {files.map((file) => {
1107
+ const path = file.path
1108
+ return (
1109
+ <DiffFile
1110
+ key={path}
1111
+ visible={tab.visible}
1112
+ file={file}
1113
+ review={fileReview}
1114
+ expanded={isExpanded(file)}
1115
+ large={drawnLines(file) > LARGE_FILE_LINES}
1116
+ revealed={revealed.has(path)}
1117
+ text={current.texts[path]}
1118
+ open={current.open[path] ?? NO_GAPS}
1119
+ split={split}
1120
+ wrap={wrap}
1121
+ badge={badgeOf(file, data, t)}
1122
+ tooltip={pathTooltipOf(file, t)}
1123
+ threads={fileThreads.get(path)}
1124
+ drawNow={wanted !== null && wanted.center !== null && wanted.path === path}
1125
+ viewed={viewedStateOf(marks, path, file.digest)}
1126
+ viewedNote={host === null ? t('viewed.hint') : host.unavailable ? t('viewed.unavailable')
1127
+ : host.saving(path) ? t('viewed.saving') : t('viewed.hintHost')}
1128
+ viewedDisabled={host !== null && (host.unavailable || host.saving(path))}
1129
+ handlers={handlers}
1130
+ t={t}
1131
+ />
1132
+ )
1133
+ })}
1134
+ {orphanRecords}
1135
+ </div>
1136
+ )
1137
+ }
1138
+ const navigator: ChangedFilesProps = {
1139
+ files, state: treeState, t,
1140
+ filter: (query) => { setTreeState(value => ({ ...value, query })) },
1141
+ toggle: (path) => { setTreeState(value => ({ ...value, collapsed: { ...value.collapsed, [path]: value.collapsed[path] !== true } })) },
1142
+ jump,
1143
+ ...review === null ? {} : { threadCounts: placed.unresolved },
1144
+ }
1145
+ // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise.
1146
+ const anyExpanded = files.some(isExpanded)
1147
+ const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll')
1148
+ const toggleExpansion = (): void => { setChosen(Object.fromEntries(files.map(file => [file.path, !anyExpanded]))) }
1149
+ const toggleSplit = (): void => { actions.toggledSplit(tab.id) }
1150
+ const toggleWrap = (): void => { actions.toggledWrap(tab.id) }
1151
+ const toggleTests = (): void => { actions.toggledTests(tab.id) }
1152
+ const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft')
1153
+ let additions = 0
1154
+ let deletions = 0
1155
+ for (const file of files) {
1156
+ additions += file.additions
1157
+ deletions += file.deletions
1158
+ }
1159
+ const viewedCount = files.filter(file => viewedStateOf(marks, file.path, file.digest) === 'viewed').length
1160
+ const treeShown = allFiles.length > 0 && treePosition !== 'hidden'
1161
+ const lensProps = { lens, counts: lensCounts, hideTests, choose: (next: ChangesLens) => { actions.lensed(tab.id, next) }, t }
1162
+ const commitMenu = source.kind === 'local' && scope !== 'branch' ? null : <CommitMenu chosen={chosenCommits} visible={tab.visible}
1163
+ list={source.kind === 'local' ? listLocalCommits : listChangeCommits} kept={source.kind === 'local' ? 'newest' : 'oldest'}
1164
+ version={commitsVersion}
1165
+ choose={(next) => { actions.committed(tab.id, next) }} t={t} />
1166
+ const toolbarStyle: CSSProperties & { '--forge-tree-width': string } = { '--forge-tree-width': `${treeWidth}px` }
1167
+ return (
1168
+ <div className={css.root} data-forge-changes={source.kind} onKeyDown={toggleViewed}>
1169
+ {source.kind === 'local'
1170
+ ? <LocalHeader state={state} scope={scope} base={base} missing={failed === 'forgePanel/base-missing'} visible={tab.visible}
1171
+ diffBases={diffBases} choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu}
1172
+ createChangeRequest={createChangeRequest} t={t} />
1173
+ : <ChangeHeader url={source.url} entry={entry} openLink={openLink} commitMenu={commitMenu}
1174
+ reviewCount={(pendingReview?.comments ?? 0) + reviewState.comments.length}
1175
+ reviewDisabled={data === null || changeCommits !== null} onReview={() => { setReviewOpen(true) }} t={t} />}
1176
+ {!reviewOpen && reviewState.error !== null && <Notice>{t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}</Notice>}
1177
+ {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' && <div className={css.reviewNotice} role="alert">
1178
+ <span>{t('review.unknown')}</span>
1179
+ {reviewState.uncertain.kind === 'comment' && <blockquote>{reviewState.uncertain.comment.body}</blockquote>}
1180
+ <Button size="sm" variant="outline" onClick={() => { openLink(source.url) }}>{t('review.recheck')}</Button>
1181
+ <Button size="sm" variant="outline" onClick={() => { queue.finish(false); setReviewError(null) }}>{t('review.confirmRetry')}</Button>
1182
+ </div>}
1183
+ {!reviewOpen && reviewError !== null && reviewState.uncertain === null && <Notice>{reviewError}</Notice>}
1184
+ <div className={css.toolbar} data-tree={treeShown ? treePosition : 'hidden'} style={toolbarStyle}>
1185
+ {/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */}
1186
+ {treeShown && <div className={css.lensCell}><LensControl {...lensProps} /></div>}
1187
+ <div ref={toolbarRow} className={css.toolbarMain}>
1188
+ {tab.visible && source.kind === 'local' && <ScopeMenu scope={scope} choose={(next) => { actions.scoped(tab.id, next) }} t={t} />}
1189
+ {tab.visible && <span className={css.filesSlot}><ChangedFilesMenu {...navigator} visible /></span>}
1190
+ {tab.visible && allFiles.length > 0 && (
1191
+ <span className={css.lensMenu}><LensMenu {...lensProps} visible /></span>
1192
+ )}
1193
+ {allFiles.length > 0 && <span className={css.foldTests}>
1194
+ <HideTestsSwitch hidden={hideTests} toggle={toggleTests} t={t} />
1195
+ </span>}
1196
+ <span className={css.spacer} data-fold-spacer="" />
1197
+ {/* A truncated read keeps the list, whose footer says so, even when it kept no thread. */}
1198
+ {review !== null && (review.threads.length > 0 || review.truncated) && (
1199
+ <button ref={threadsToggle} type="button" className={css.threadsToggle} aria-pressed={threadList.open} data-forge-threads-toggle=""
1200
+ aria-label={t('thread.listAria', { count: review.threads.length })}
1201
+ onClick={() => { setThreadList(value => ({ ...value, open: !value.open, claim: !value.open })) }}>
1202
+ {t('thread.list')}<span className={css.threadsTotal}>{review.threads.length}</span>
1203
+ </button>
1204
+ )}
1205
+ <span className={css.progressSlot}><ViewedProgress viewed={viewedCount} total={files.length} t={t} /></span>
1206
+ {files.length > 0 && (
1207
+ <span className={clsx(css.totals, css.foldViews)}><Counts file={{ additions, deletions, binary: false }} t={t} /></span>
1208
+ )}
1209
+ <span className={css.tools}>
1210
+ <Tooltip label={t('diff.refresh')} side="bottom">
1211
+ <button type="button" className={clsx(css.tool, css.foldRefresh)} aria-label={t('diff.refresh')} onClick={refresh}>
1212
+ <RefreshGlyph busy={rereading} size={16} />
1213
+ </button>
1214
+ </Tooltip>
1215
+ <Tooltip label={expansionLabel} side="bottom">
1216
+ <button type="button" className={clsx(css.tool, css.foldViews)} data-expanded={anyExpanded ? '' : undefined} aria-label={expansionLabel}
1217
+ disabled={files.length === 0} onClick={toggleExpansion}>
1218
+ <IconChevronsUpDownOutlineRegular />
1219
+ </button>
1220
+ </Tooltip>
1221
+ <Tooltip label={t(split ? 'diff.unified' : 'diff.split')} side="bottom">
1222
+ <button type="button" className={clsx(css.tool, css.foldViews)} aria-pressed={split} aria-label={t('diff.splitAria')}
1223
+ onClick={toggleSplit}>
1224
+ <IconCompareSplitOutlineRegular className={css.compareIcon} />
1225
+ </button>
1226
+ </Tooltip>
1227
+ <Tooltip label={t(wrap ? 'diff.nowrap' : 'diff.wrap')} side="bottom">
1228
+ <button type="button" className={clsx(css.tool, css.foldViews)} aria-pressed={wrap} aria-label={t('diff.wrapAria')}
1229
+ onClick={toggleWrap}>
1230
+ {wrap ? <IconNowrapFillRegular /> : <IconWrapFillRegular />}
1231
+ </button>
1232
+ </Tooltip>
1233
+ <span className={css.treeToggle}>
1234
+ <Tooltip label={treeAction} side="bottom">
1235
+ <button type="button" className={css.tool} aria-label={treeAction} aria-expanded={treePosition !== 'hidden'}
1236
+ aria-controls={treeId} disabled={allFiles.length === 0}
1237
+ onClick={() => { setTreePosition(value => value === 'left' ? 'right' : value === 'right' ? 'hidden' : 'left') }}>
1238
+ <IconWorkspaceTreeOutlineRegular />
1239
+ </button>
1240
+ </Tooltip>
1241
+ </span>
1242
+ <ViewOptionsMenu visible={tab.visible} options={{
1243
+ anyExpanded, hasFiles: files.length > 0, toggleExpansion, split, toggleSplit, wrap, toggleWrap,
1244
+ hideTests: allFiles.length > 0 ? hideTests : undefined, toggleTests, refresh,
1245
+ }} t={t} />
1246
+ </span>
1247
+ </div>
1248
+ </div>
1249
+ {data !== null && failed !== null && (
1250
+ <Notice action={retry
1251
+ ? <Button size="sm" variant="outline" className={css.noticeAction} onClick={refresh}>{t('retry')}</Button>
1252
+ : automaticBase !== false && <span className={css.noticeAction}>{automaticBase}</span>}>
1253
+ {failureText}
1254
+ </Notice>
1255
+ )}
1256
+ {data?.kind === 'change' && data.localAhead !== null && data.localAhead > 0 && (
1257
+ <Notice>{t('diff.stale', { count: data.localAhead })}</Notice>
1258
+ )}
1259
+ {data?.kind === 'local' && data.omitted > 0 && <Notice>{t('diff.omitted', { count: data.omitted })}</Notice>}
1260
+ {data?.kind === 'change' && data.viewed?.kind === 'failed' && (
1261
+ <Notice action={<Button size="sm" variant="outline" className={css.noticeAction} onClick={refresh}>{t('retry')}</Button>}>
1262
+ {t('viewed.readFailed', { message: data.viewed.message })}
1263
+ </Notice>
1264
+ )}
1265
+ {data?.kind === 'change' && threadRead.failure !== null && (
1266
+ <Notice action={<Button size="sm" variant="outline" className={css.noticeAction} onClick={refresh}>{t('retry')}</Button>}>
1267
+ {t('thread.loadFailed', { message: threadRead.failure })}
1268
+ </Notice>
1269
+ )}
1270
+ {reviewForm}
1271
+ <div className={css.body}>
1272
+ {body}
1273
+ {allFiles.length > 0 && <FileTreePane {...navigator} id={treeId} position={treePosition} onWidth={setTreeWidth} />}
1274
+ {review !== null && data?.kind === 'change' && threadList.open && (
1275
+ <ThreadList entries={placed.entries} files={allFiles} truncated={review.truncated} url={data.url}
1276
+ filter={threadList.filter} choose={(filter) => { setThreadList(value => ({ ...value, filter })) }}
1277
+ claim={threadList.claim} claimed={() => { setThreadList(value => ({ ...value, claim: false })) }}
1278
+ open={(entry, covering) => {
1279
+ // A list that covers the files closes and hands the focus to the thread it opens, which it would cover.
1280
+ if (covering) setThreadList(value => ({ ...value, open: false }))
1281
+ openThread(entry, covering)
1282
+ }}
1283
+ openLink={openLink} close={closeThreadList} t={t} />
1284
+ )}
1285
+ </div>
1286
+ </div>
1287
+ )
1288
+ }