ref0-git 0.3.0 → 0.6.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 (210) hide show
  1. package/app/apps/github/.dev.vars.example +2 -1
  2. package/app/apps/github/generated/git-rest.ts +191 -25
  3. package/app/apps/github/generated/routeTree.gen.ts +21 -0
  4. package/app/apps/github/package.json +1 -1
  5. package/app/apps/github/src/branches/branch-list.tsx +8 -4
  6. package/app/apps/github/src/branches/branches.ts +10 -5
  7. package/app/apps/github/src/camo/addresses.ts +120 -0
  8. package/app/apps/github/src/camo/client.ts +125 -0
  9. package/app/apps/github/src/camo/fetch.ts +201 -0
  10. package/app/apps/github/src/camo/lookup.ts +23 -0
  11. package/app/apps/github/src/camo/node.ts +50 -0
  12. package/app/apps/github/src/camo/proxy.ts +116 -0
  13. package/app/apps/github/src/camo/sign-images.ts +307 -0
  14. package/app/apps/github/src/camo/signing.ts +80 -0
  15. package/app/apps/github/src/clients/allowed.ts +111 -18
  16. package/app/apps/github/src/clients/clients.ts +76 -61
  17. package/app/apps/github/src/clients/transport.ts +13 -0
  18. package/app/apps/github/src/code/code-tree.tsx +3 -1
  19. package/app/apps/github/src/code/file-view.tsx +15 -6
  20. package/app/apps/github/src/code/files.ts +26 -19
  21. package/app/apps/github/src/code/go-to-file.tsx +2 -1
  22. package/app/apps/github/src/code/load.ts +41 -23
  23. package/app/apps/github/src/code/markdown-files.ts +13 -2
  24. package/app/apps/github/src/code/ref-pages.ts +14 -5
  25. package/app/apps/github/src/code/ref-switcher.tsx +4 -3
  26. package/app/apps/github/src/code/refs.ts +42 -8
  27. package/app/apps/github/src/code/repo-home.tsx +6 -2
  28. package/app/apps/github/src/code/repo.ts +12 -6
  29. package/app/apps/github/src/code/saved.ts +5 -3
  30. package/app/apps/github/src/code/trees.ts +11 -9
  31. package/app/apps/github/src/components/markdown/markdown.css +6 -0
  32. package/app/apps/github/src/components/markdown/markdown.tsx +95 -10
  33. package/app/apps/github/src/components/owner-card.tsx +3 -1
  34. package/app/apps/github/src/components/repos/your-repos.tsx +3 -1
  35. package/app/apps/github/src/components/shell/owner-repos.tsx +7 -12
  36. package/app/apps/github/src/components/shell/repo-switcher.tsx +10 -16
  37. package/app/apps/github/src/components/signin/device-card.tsx +9 -2
  38. package/app/apps/github/src/components/user-avatar.tsx +2 -1
  39. package/app/apps/github/src/context/context.ts +13 -0
  40. package/app/apps/github/src/diffs/blobs.ts +37 -14
  41. package/app/apps/github/src/diffs/diff-job.ts +53 -0
  42. package/app/apps/github/src/diffs/diff-worker.ts +6 -0
  43. package/app/apps/github/src/diffs/diffing.ts +136 -0
  44. package/app/apps/github/src/diffs/files.ts +4 -3
  45. package/app/apps/github/src/diffs/hunks.tsx +101 -53
  46. package/app/apps/github/src/diffs/patch.ts +20 -11
  47. package/app/apps/github/src/history/commit-diff.ts +10 -5
  48. package/app/apps/github/src/history/commit-list.tsx +3 -1
  49. package/app/apps/github/src/history/commit-page.tsx +4 -2
  50. package/app/apps/github/src/history/history.ts +12 -10
  51. package/app/apps/github/src/hooks/allowed.ts +9 -9
  52. package/app/apps/github/src/hooks/avatars.ts +3 -3
  53. package/app/apps/github/src/hooks/open-counts.ts +5 -4
  54. package/app/apps/github/src/hooks/profiles.ts +26 -12
  55. package/app/apps/github/src/hooks/repos.ts +78 -25
  56. package/app/apps/github/src/inbox/count.ts +30 -29
  57. package/app/apps/github/src/inbox/inbox-item.tsx +3 -1
  58. package/app/apps/github/src/inbox/inbox-page.tsx +5 -2
  59. package/app/apps/github/src/inbox/marks.ts +26 -15
  60. package/app/apps/github/src/inbox/release-tags.ts +7 -6
  61. package/app/apps/github/src/inbox/subjects.ts +5 -4
  62. package/app/apps/github/src/inbox/subscription-controls.tsx +14 -5
  63. package/app/apps/github/src/inbox/subscriptions.ts +95 -35
  64. package/app/apps/github/src/inbox/threads.ts +6 -6
  65. package/app/apps/github/src/issues/changes.ts +40 -16
  66. package/app/apps/github/src/issues/counts.ts +8 -5
  67. package/app/apps/github/src/issues/issue-list.tsx +20 -6
  68. package/app/apps/github/src/issues/issue-page.tsx +30 -14
  69. package/app/apps/github/src/issues/issues.ts +195 -46
  70. package/app/apps/github/src/issues/label-dialog.tsx +8 -11
  71. package/app/apps/github/src/issues/labels-page.tsx +35 -3
  72. package/app/apps/github/src/issues/milestone-dialog.tsx +197 -0
  73. package/app/apps/github/src/issues/milestones-page.tsx +269 -0
  74. package/app/apps/github/src/issues/new-issue.tsx +3 -1
  75. package/app/apps/github/src/issues/sidebar.tsx +8 -6
  76. package/app/apps/github/src/markdown/README.md +22 -17
  77. package/app/apps/github/src/markdown/context.ts +83 -10
  78. package/app/apps/github/src/markdown/images.ts +3 -2
  79. package/app/apps/github/src/markdown/lookup.ts +9 -8
  80. package/app/apps/github/src/markdown/page-budget.ts +50 -0
  81. package/app/apps/github/src/markdown/patches.ts +74 -32
  82. package/app/apps/github/src/markdown/query.ts +7 -2
  83. package/app/apps/github/src/markdown/remote.ts +106 -0
  84. package/app/apps/github/src/markdown/render.ts +101 -24
  85. package/app/apps/github/src/markdown/texts.ts +43 -0
  86. package/app/apps/github/src/markdown/words-module.d.ts +5 -0
  87. package/app/apps/github/src/markdown/words-plugin.ts +135 -0
  88. package/app/apps/github/src/names/repos.ts +1 -1
  89. package/app/apps/github/src/palette/palette.tsx +7 -4
  90. package/app/apps/github/src/palette/rows.tsx +54 -33
  91. package/app/apps/github/src/palette/server.ts +5 -5
  92. package/app/apps/github/src/palette/targets.ts +1 -0
  93. package/app/apps/github/src/policy.ts +165 -66
  94. package/app/apps/github/src/private-repos.ts +2 -2
  95. package/app/apps/github/src/pulls/compare-page.tsx +6 -3
  96. package/app/apps/github/src/pulls/files-tab.tsx +480 -214
  97. package/app/apps/github/src/pulls/held-summary.ts +178 -0
  98. package/app/apps/github/src/pulls/live.ts +6 -4
  99. package/app/apps/github/src/pulls/merge-box.tsx +17 -10
  100. package/app/apps/github/src/pulls/pull-list.tsx +6 -3
  101. package/app/apps/github/src/pulls/pull-page.tsx +19 -10
  102. package/app/apps/github/src/pulls/pull.ts +68 -40
  103. package/app/apps/github/src/pulls/pulls.ts +39 -22
  104. package/app/apps/github/src/pulls/review-drafts.ts +131 -0
  105. package/app/apps/github/src/pulls/review.ts +374 -99
  106. package/app/apps/github/src/pulls/threads.tsx +152 -0
  107. package/app/apps/github/src/queue/queue-page.tsx +15 -8
  108. package/app/apps/github/src/queue/queue.ts +35 -20
  109. package/app/apps/github/src/releases/latest-release.tsx +3 -1
  110. package/app/apps/github/src/releases/overview.tsx +4 -2
  111. package/app/apps/github/src/releases/release-form.tsx +8 -5
  112. package/app/apps/github/src/releases/release-list.tsx +8 -5
  113. package/app/apps/github/src/releases/release-view.tsx +1 -0
  114. package/app/apps/github/src/releases/releases.ts +33 -23
  115. package/app/apps/github/src/releases/tag-list.tsx +3 -1
  116. package/app/apps/github/src/router.tsx +5 -2
  117. package/app/apps/github/src/routes/$owner/$repo/_code/blob/$.tsx +7 -1
  118. package/app/apps/github/src/routes/$owner/$repo/_code/tree/$.tsx +6 -1
  119. package/app/apps/github/src/routes/$owner/$repo/_releases/releases/index.tsx +2 -1
  120. package/app/apps/github/src/routes/$owner/$repo/_releases/tags.tsx +1 -1
  121. package/app/apps/github/src/routes/$owner/$repo/branches.tsx +5 -1
  122. package/app/apps/github/src/routes/$owner/$repo/commit/$sha.tsx +1 -1
  123. package/app/apps/github/src/routes/$owner/$repo/commits/$.tsx +6 -1
  124. package/app/apps/github/src/routes/$owner/$repo/index.tsx +1 -1
  125. package/app/apps/github/src/routes/$owner/$repo/issues/$number.tsx +4 -2
  126. package/app/apps/github/src/routes/$owner/$repo/issues/index.tsx +2 -2
  127. package/app/apps/github/src/routes/$owner/$repo/issues/new.tsx +5 -2
  128. package/app/apps/github/src/routes/$owner/$repo/labels.tsx +2 -1
  129. package/app/apps/github/src/routes/$owner/$repo/milestones.tsx +36 -0
  130. package/app/apps/github/src/routes/$owner/$repo/pull/$number/route.tsx +4 -2
  131. package/app/apps/github/src/routes/$owner/$repo/pulls/index.tsx +2 -2
  132. package/app/apps/github/src/routes/$owner/$repo/queue.tsx +2 -1
  133. package/app/apps/github/src/routes/$owner/$repo/releases/edit/$.tsx +5 -2
  134. package/app/apps/github/src/routes/$owner/$repo/releases/new.tsx +2 -1
  135. package/app/apps/github/src/routes/$owner/$repo/releases/tag/$.tsx +4 -2
  136. package/app/apps/github/src/routes/$owner/$repo/route.tsx +9 -5
  137. package/app/apps/github/src/routes/$owner/$repo/settings/hooks/index.tsx +3 -1
  138. package/app/apps/github/src/routes/$owner/$repo/settings/index.tsx +3 -1
  139. package/app/apps/github/src/routes/-nav.tsx +10 -2
  140. package/app/apps/github/src/routes/-root-testing.ts +29 -6
  141. package/app/apps/github/src/routes/__root.tsx +9 -4
  142. package/app/apps/github/src/routes/index.tsx +3 -1
  143. package/app/apps/github/src/routes/orgs/$owner/route.tsx +4 -1
  144. package/app/apps/github/src/routes/orgs/$owner/settings.tsx +4 -1
  145. package/app/apps/github/src/seed/acme.ts +1 -1
  146. package/app/apps/github/src/seed/seed.ts +199 -110
  147. package/app/apps/github/src/server.ts +24 -15
  148. package/app/apps/github/src/settings/account-avatar.tsx +4 -1
  149. package/app/apps/github/src/settings/general-settings.tsx +3 -1
  150. package/app/apps/github/src/settings/general.ts +4 -4
  151. package/app/apps/github/src/settings/hook-form.tsx +3 -1
  152. package/app/apps/github/src/settings/hook-list.tsx +5 -2
  153. package/app/apps/github/src/settings/hooks.ts +7 -7
  154. package/app/apps/github/src/settings/org-settings.tsx +3 -1
  155. package/app/apps/github/src/settings/orgs.ts +21 -11
  156. package/app/apps/github/src/settings/settings-layout.tsx +3 -1
  157. package/app/apps/github/src/signin/approval.ts +4 -3
  158. package/app/apps/github/src/signin/auth.ts +9 -2
  159. package/app/apps/github/src/signin/device-code.ts +8 -3
  160. package/app/apps/github/src/signin/device-prompt.ts +28 -3
  161. package/app/apps/github/src/signin/revoke.ts +36 -0
  162. package/app/apps/github/tsconfig.json +4 -1
  163. package/app/apps/github/vite.config.ts +8 -0
  164. package/app/pnpm-workspace.yaml +12 -5
  165. package/app/tsconfig.base.json +1 -0
  166. package/dist/cli/child.mjs +1 -1
  167. package/dist/cli/credentials.mjs +4 -4
  168. package/dist/cli/documents.mjs +32 -22
  169. package/dist/cli/events.mjs +1 -1
  170. package/dist/cli/failure.mjs +20 -7
  171. package/dist/cli/folders.mjs +2 -2
  172. package/dist/cli/git-remote-ref0.mjs +47 -22
  173. package/dist/cli/git.mjs +1 -1
  174. package/dist/cli/helpers.mjs +2 -2
  175. package/dist/cli/hosts.mjs +3 -3
  176. package/dist/cli/output.mjs +2 -2
  177. package/dist/cli/prompt.mjs +1 -1
  178. package/dist/cli/queue.mjs +7 -7
  179. package/dist/cli/ref0-git.mjs +2 -2
  180. package/dist/cli/repos.mjs +35 -18
  181. package/dist/cli/resources.mjs +5 -5
  182. package/dist/cli/retry-after.mjs +8 -0
  183. package/dist/cli/setup.mjs +172 -66
  184. package/dist/cli/sign-in.mjs +65 -23
  185. package/dist/cli/sign-ins.mjs +4 -4
  186. package/dist/cli/sqlite.mjs +2 -2
  187. package/dist/cli/tokens.mjs +3 -3
  188. package/dist/cli/vendor.mjs +1 -1
  189. package/dist/init/app.mjs +20 -21
  190. package/dist/init/choices.mjs +1 -1
  191. package/dist/init/cloudflare.mjs +15 -19
  192. package/dist/init/create.mjs +3 -2
  193. package/dist/init/detect.mjs +4 -4
  194. package/dist/init/files.mjs +120 -13
  195. package/dist/init/frameworks.mjs +16 -0
  196. package/dist/init/git-module.mjs +22 -7
  197. package/dist/init/jsonc.mjs +9 -7
  198. package/dist/init/metadata.mjs +9 -3
  199. package/dist/init/mounts.mjs +13 -10
  200. package/dist/init/next.mjs +2 -2
  201. package/dist/init/node-app.mjs +3 -3
  202. package/dist/init/node.mjs +42 -45
  203. package/dist/init/nuxt.mjs +153 -27
  204. package/dist/init/stores.mjs +14 -9
  205. package/dist/init/sveltekit.mjs +4 -2
  206. package/dist/init/template.mjs +9 -6
  207. package/dist/init/templates.mjs +63 -47
  208. package/dist/init/vercel.mjs +37 -37
  209. package/dist/init/versions.mjs +3 -3
  210. package/package.json +6 -5
@@ -2,8 +2,9 @@ import type { DiffLineAnnotation, SelectedLineRange } from '@pierre/diffs';
2
2
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
3
  import { useRouteContext } from '@tanstack/react-router';
4
4
  import { ChevronRightIcon } from 'lucide-react';
5
- import { useMemo, useRef, useState } from 'react';
5
+ import { useEffect, useMemo, useState, type ReactNode } from 'react';
6
6
 
7
+ import { useClients } from '../clients/clients.ts';
7
8
  import { Go } from '../code/controls.tsx';
8
9
  import { commitHref, type RepoPlace } from '../code/places.ts';
9
10
  import { Markdown } from '../components/markdown/markdown.tsx';
@@ -36,28 +37,36 @@ import { pullFiles, type Notes } from '../diffs/files.ts';
36
37
  import { useAllowed } from '../hooks/allowed.ts';
37
38
  import { Comment, Failed } from '../issues/issue-page.tsx';
38
39
  import { refreshPull, reviewsOf, type PullDetail } from './pull.ts';
40
+ import { ResolvableThread } from './threads.tsx';
39
41
  import {
42
+ addDraft,
40
43
  commentOnLines,
44
+ deleteDraft,
41
45
  discardPending,
42
- draftsOf,
46
+ editDraft,
43
47
  lineCommentsOf,
44
- noReviewDraft,
45
48
  mergeBaseOf,
46
49
  onHead,
47
50
  outdatedThreads,
51
+ threadsOf,
52
+ type ThreadState,
48
53
  pendingCommentsOf,
54
+ refreshPending,
49
55
  refreshReviews,
56
+ replyDraft,
50
57
  replyTo,
51
- reviewDraftOf,
58
+ saveSummary,
59
+ startReview,
60
+ submitNew,
52
61
  submitPending,
53
- submitReview,
54
- type Draft,
62
+ useUnsaved,
55
63
  type LineComment,
56
64
  type LinePlace,
57
65
  type LineSide,
58
- type ReviewDraft,
59
66
  type ReviewEvent,
60
67
  } from './review.ts';
68
+ import { keepEdits, usePicked, useTyped } from './review-drafts.ts';
69
+ import { useHeldSummary, type Summary, type SummaryEvent } from './held-summary.ts';
61
70
 
62
71
  /** Where `@pierre/diffs` draws a side's notes: the old file's lines, or the new's. */
63
72
  const sides = { LEFT: 'deletions', RIGHT: 'additions' } as const;
@@ -65,6 +74,31 @@ const sides = { LEFT: 'deletions', RIGHT: 'additions' } as const;
65
74
  const sideOf = (side: SelectedLineRange['side']): LineSide =>
66
75
  side === 'deletions' ? 'LEFT' : 'RIGHT';
67
76
 
77
+ /**
78
+ * The review bar's words for the viewer's pending review and its count of comments: a reply kept
79
+ * in that review says it joins it in the same words.
80
+ */
81
+ const yourReview = 'Your pending review';
82
+
83
+ const pendingSaid = (count: number) =>
84
+ count === 1 ? '1 pending comment' : `${count} pending comments`;
85
+
86
+ /** The button that keeps a comment in the viewer's pending review, as GitHub's says it. */
87
+ const addReviewComment = 'Add review comment';
88
+
89
+ /**
90
+ * How a thread takes its reader's reply: posted at once, or kept in their pending review as a draft
91
+ * in the thread, which `joins` says; or, while the thread's node a kept reply names is read, not yet.
92
+ */
93
+ type ThreadReply =
94
+ | { readonly kind: 'post'; readonly send: (body: string) => Promise<void> }
95
+ | {
96
+ readonly kind: 'keep';
97
+ readonly send: (body: string) => Promise<void>;
98
+ readonly joins: string;
99
+ }
100
+ | { readonly kind: 'loading' };
101
+
68
102
  /**
69
103
  * The lines picked from the gutter, as GitHub's REST places a comment: on its last line, from its
70
104
  * first when it's a range, whichever way the drag went.
@@ -107,27 +141,38 @@ const events: readonly {
107
141
  ];
108
142
 
109
143
  /**
110
- * A thread: its first comment, its replies, and a reply box for those allowed. An outdated one
111
- * says which file and lines it was made on, and links the commit, since it isn't drawn on the diff.
144
+ * A thread: its first comment, its replies, the viewer's replies kept in their pending review, and
145
+ * a reply box for those allowed. An outdated one says which file and lines it was made on, and
146
+ * links the commit, since it isn't drawn on the diff.
112
147
  */
113
148
  function Thread({
149
+ place,
150
+ pull,
114
151
  repo,
115
152
  comments,
116
153
  outdatedIn,
154
+ kept,
117
155
  reply,
118
156
  }: {
157
+ readonly place: RepoPlace;
158
+ readonly pull: number;
119
159
  readonly repo: string;
120
160
  readonly comments: readonly LineComment[];
121
161
  /** The repo an outdated thread's commit is in, or `undefined` for a thread on the diff. */
122
162
  readonly outdatedIn?: RepoPlace;
123
- readonly reply: ((body: string) => Promise<void>) | undefined;
163
+ /** The viewer's replies in it that their pending review keeps, drawn under its comments. */
164
+ readonly kept?: ReactNode;
165
+ readonly reply: ThreadReply | undefined;
124
166
  }) {
125
- const [draft, setDraft] = useState<string | undefined>();
167
+ const first = comments[0];
168
+ // Held above the thread, by its first comment, so a push that draws it afresh keeps the reply.
169
+ const [draft, setDraft] = useTyped(place, pull, `reply:${first?.id}`);
126
170
  const replied = useMutation({
127
- mutationFn: async (body: string) => reply?.(body),
171
+ mutationFn: async (body: string) => (reply?.kind === 'loading' ? undefined : reply?.send(body)),
128
172
  onSuccess: () => setDraft(undefined),
129
173
  });
130
- const first = comments[0];
174
+ // Until a kept reply's thread node is read, Reply stays, waiting, so the thread doesn't look broken.
175
+ const ready = reply !== undefined && reply.kind !== 'loading';
131
176
 
132
177
  return (
133
178
  <div
@@ -158,27 +203,40 @@ function Thread({
158
203
  upload={comment.pictures.get(comment.login)}
159
204
  created={comment.created}
160
205
  body={comment.body}
206
+ from={{ kind: 'review-comment', repo, id: comment.id }}
161
207
  save={undefined}
162
208
  />
163
209
  ))}
210
+ {kept}
164
211
  {reply !== undefined &&
165
212
  (draft === undefined ? (
166
- <Button variant="outline" size="sm" className="self-start" onClick={() => setDraft('')}>
167
- Reply
213
+ <Button
214
+ variant="outline"
215
+ size="sm"
216
+ className="self-start"
217
+ disabled={!ready}
218
+ aria-busy={!ready}
219
+ onClick={() => setDraft('')}
220
+ >
221
+ {ready ? 'Reply' : 'Loading reply…'}
168
222
  </Button>
169
223
  ) : (
170
224
  <div className="flex flex-col gap-2" data-hotkey-box>
225
+ {reply.kind === 'keep' && (
226
+ <p className="text-meta text-muted-foreground">{reply.joins}</p>
227
+ )}
171
228
  <MarkdownEditor repo={repo} label="Reply" value={draft} onChange={setDraft} />
172
229
  <div className="flex justify-end gap-2">
173
230
  <Button variant="ghost" onClick={() => setDraft(undefined)}>
174
231
  Cancel
175
232
  </Button>
176
233
  <Button
177
- disabled={replied.isPending || draft.trim() === ''}
234
+ disabled={!ready || replied.isPending || draft.trim() === ''}
235
+ aria-busy={!ready}
178
236
  onClick={() => replied.mutate(draft)}
179
237
  data-hotkey={hotkeys.submit}
180
238
  >
181
- Reply
239
+ {reply.kind === 'keep' ? addReviewComment : ready ? 'Reply' : 'Loading reply…'}
182
240
  <HotkeyHint keys={hotkeys.submit} />
183
241
  </Button>
184
242
  </div>
@@ -190,17 +248,23 @@ function Thread({
190
248
  }
191
249
 
192
250
  /**
193
- * The threads begun on an earlier head, folded above the diff as GitHub folds an outdated thread:
194
- * their lines may hold other code now, so they aren't drawn on it.
251
+ * The outdated threads, whose lines changed at the head, folded above the diff as GitHub folds an
252
+ * outdated thread: their lines hold other code now, so they aren't drawn on it.
195
253
  */
196
254
  function OutdatedThreads({
197
255
  place,
256
+ pull,
198
257
  threads,
258
+ states,
259
+ kept,
199
260
  reply,
200
261
  }: {
201
262
  readonly place: RepoPlace;
263
+ readonly pull: number;
202
264
  readonly threads: readonly (readonly LineComment[])[];
203
- readonly reply: (first: LineComment) => ((body: string) => Promise<void>) | undefined;
265
+ readonly states: ReadonlyMap<number, ThreadState> | undefined;
266
+ readonly kept: (first: LineComment) => ReactNode;
267
+ readonly reply: (first: LineComment) => ThreadReply | undefined;
204
268
  }) {
205
269
  if (threads.length === 0) return null;
206
270
 
@@ -217,8 +281,10 @@ function OutdatedThreads({
217
281
  data-icon="inline-start"
218
282
  className="transition-transform group-data-panel-open:rotate-90"
219
283
  />
220
- {threads.length} outdated {threads.length === 1 ? 'thread' : 'threads'}
221
- <span className="font-normal text-muted-foreground">, made on earlier commits</span>
284
+ <span>
285
+ {threads.length} outdated {threads.length === 1 ? 'thread' : 'threads'}
286
+ <span className="font-normal text-muted-foreground">, on lines changed since</span>
287
+ </span>
222
288
  </CollapsibleTrigger>
223
289
  {/* Kept in the page while folded, as a details element keeps its threads, for find in page. */}
224
290
  <CollapsibleContent hiddenUntilFound className="flex flex-col gap-2 border-t p-2">
@@ -227,13 +293,23 @@ function OutdatedThreads({
227
293
 
228
294
  return (
229
295
  first && (
230
- <Thread
296
+ <ResolvableThread
231
297
  key={first.id}
232
- repo={`${place.owner}/${place.repo}`}
233
- comments={thread}
234
- outdatedIn={place}
235
- reply={reply(first)}
236
- />
298
+ repo={place}
299
+ pull={pull}
300
+ thread={states?.get(first.id)}
301
+ place={`${first.path}, ${linesSaid(first)}`}
302
+ >
303
+ <Thread
304
+ place={place}
305
+ pull={pull}
306
+ repo={`${place.owner}/${place.repo}`}
307
+ comments={thread}
308
+ outdatedIn={place}
309
+ kept={kept(first)}
310
+ reply={reply(first)}
311
+ />
312
+ </ResolvableThread>
237
313
  )
238
314
  );
239
315
  })}
@@ -242,21 +318,51 @@ function OutdatedThreads({
242
318
  );
243
319
  }
244
320
 
245
- /** A comment waiting in the viewer's review, until it's submitted, and its delete for the page's. */
321
+ /**
322
+ * A draft in the viewer's pending review, which the drop-in keeps until the review is submitted or
323
+ * discarded: its edit and its delete, each saved on the server as it's made, its text kept while a
324
+ * write is in flight or refused.
325
+ */
246
326
  function Pending({
327
+ place,
328
+ pull,
247
329
  repo,
248
330
  login,
249
331
  draft,
332
+ edit,
250
333
  remove,
334
+ framed,
251
335
  }: {
336
+ readonly place: RepoPlace;
337
+ readonly pull: number;
252
338
  readonly repo: string;
253
339
  readonly login: string;
254
- readonly draft: LinePlace & { readonly body: string };
255
- readonly remove: (() => void) | undefined;
340
+ readonly draft: LinePlace & { readonly body: string; readonly node: string };
341
+ /** Whether it's drawn in a box of its own, as on its lines, or in its thread's, as a reply. */
342
+ readonly framed: boolean;
343
+ readonly edit: (body: string) => Promise<void>;
344
+ readonly remove: () => Promise<void>;
256
345
  }) {
346
+ const client = useQueryClient();
347
+ // Held above it, by the draft, so a push that moves it off the diff keeps the edit.
348
+ const [editing, setEditing] = useTyped(place, pull, `edit:${draft.node}`);
349
+ const saved = useMutation({ mutationFn: edit, onSuccess: () => setEditing(undefined) });
350
+ // A deleted comment's edit goes with it once the drafts are read again (`keepEdits`).
351
+ const removed = useMutation({ mutationFn: remove });
352
+ const busy = saved.isPending || removed.isPending;
353
+ useUnsaved(client, busy || saved.isError || removed.isError);
354
+
257
355
  return (
258
- <div className="border-y bg-muted/30 p-3 font-sans text-sm whitespace-normal">
259
- <article aria-label={`${login}'s pending comment`} className="border bg-background">
356
+ <div
357
+ className={
358
+ framed ? 'border-y bg-muted/30 p-3 font-sans text-sm whitespace-normal' : undefined
359
+ }
360
+ >
361
+ <article
362
+ aria-label={`${login}'s pending comment`}
363
+ aria-busy={removed.isPending}
364
+ className={`border bg-background ${removed.isPending ? 'opacity-60' : ''}`}
365
+ >
260
366
  <header className="flex items-center justify-between gap-2 border-b px-3 py-1.5">
261
367
  <span className="flex items-center gap-2">
262
368
  <UserAvatar login={login} size="sm" account="user" />
@@ -266,14 +372,58 @@ function Pending({
266
372
  <Badge variant="outline">Pending</Badge>
267
373
  <span className="text-meta text-muted-foreground">On {linesSaid(draft)}</span>
268
374
  </span>
269
- {remove !== undefined && (
270
- <Button variant="destructive" size="sm" onClick={remove}>
271
- Delete
375
+ <span className="flex gap-2">
376
+ {editing === undefined && (
377
+ <Button
378
+ variant="outline"
379
+ size="sm"
380
+ disabled={busy}
381
+ onClick={() => setEditing(draft.body)}
382
+ >
383
+ Edit
384
+ </Button>
385
+ )}
386
+ <Button
387
+ variant="destructive"
388
+ size="sm"
389
+ disabled={busy}
390
+ onClick={() => removed.mutate()}
391
+ >
392
+ {removed.isPending ? 'Removing…' : 'Delete'}
272
393
  </Button>
273
- )}
394
+ </span>
274
395
  </header>
275
396
  <div className="px-3 py-2">
276
- <Markdown text={draft.body} context={{ kind: 'comment', repo }} />
397
+ {editing === undefined ? (
398
+ <Markdown text={draft.body} context={{ kind: 'comment', repo }} />
399
+ ) : (
400
+ <div className="flex flex-col gap-2" data-hotkey-box>
401
+ <MarkdownEditor
402
+ repo={repo}
403
+ label="Pending comment"
404
+ value={editing}
405
+ onChange={setEditing}
406
+ />
407
+ <div className="flex justify-end gap-2">
408
+ <Button
409
+ variant="ghost"
410
+ disabled={saved.isPending}
411
+ onClick={() => setEditing(undefined)}
412
+ >
413
+ Cancel
414
+ </Button>
415
+ <Button
416
+ disabled={saved.isPending || editing.trim() === ''}
417
+ onClick={() => saved.mutate(editing)}
418
+ data-hotkey={hotkeys.submit}
419
+ >
420
+ {saved.isPending ? 'Saving…' : saved.isError ? 'Try again' : 'Save'}
421
+ <HotkeyHint keys={hotkeys.submit} />
422
+ </Button>
423
+ </div>
424
+ </div>
425
+ )}
426
+ <Failed error={saved.error ?? removed.error} />
277
427
  </div>
278
428
  </article>
279
429
  </div>
@@ -281,14 +431,15 @@ function Pending({
281
431
  }
282
432
 
283
433
  /**
284
- * The box under picked lines: its comment posted alone, or kept for the review the viewer is
285
- * writing, as GitHub's offers both until a review is started.
434
+ * The box under picked lines: its comment posted alone, or saved in the viewer's pending review,
435
+ * as GitHub's offers both until a review is started. Its text stays while either is in flight, and
436
+ * after a refusal, so a reload asks first and a retry sends it again.
286
437
  */
287
438
  function CommentForm({
288
439
  repo,
289
440
  place,
290
441
  earlier,
291
- typed,
442
+ held,
292
443
  reviewing,
293
444
  single,
294
445
  start,
@@ -297,10 +448,10 @@ function CommentForm({
297
448
  readonly repo: string;
298
449
  readonly place: LinePlace;
299
450
  /**
300
- * What's typed so far, kept by the page: a push draws the diff, and this form, again, and the
301
- * form starts from it.
451
+ * The pull request whose holder keeps what's typed so far: a push draws the diff, and this form,
452
+ * again, as a return to the tab does, and the form starts from it.
302
453
  */
303
- readonly typed: { current: string };
454
+ readonly held: { readonly place: RepoPlace; readonly pull: number };
304
455
  /**
305
456
  * Whether the lines were picked before the latest commit: its comment posts there, and the form
306
457
  * sits above the diff, which may not have the lines.
@@ -308,12 +459,18 @@ function CommentForm({
308
459
  readonly earlier: boolean;
309
460
  readonly reviewing: boolean;
310
461
  readonly single: (body: string) => Promise<void>;
311
- readonly start: (body: string) => void;
462
+ readonly start: (body: string) => Promise<void>;
312
463
  readonly cancel: () => void;
313
464
  }) {
314
- const [body, setBody] = useState(typed.current);
465
+ const client = useQueryClient();
466
+ const [typed, setTyped] = useTyped(held.place, held.pull, 'new');
467
+ const body = typed ?? '';
315
468
  const posted = useMutation({ mutationFn: single });
469
+ const kept = useMutation({ mutationFn: start });
470
+ const busy = posted.isPending || kept.isPending;
471
+ useUnsaved(client, busy || posted.isError || kept.isError);
316
472
  const empty = body.trim() === '';
473
+ const keep = reviewing ? addReviewComment : 'Start a review';
317
474
 
318
475
  return (
319
476
  <section
@@ -326,8 +483,8 @@ function CommentForm({
326
483
  {earlier && (
327
484
  <>
328
485
  {' of '}
329
- <span className="font-mono">{place.path}</span> in an earlier commit, where it posts as
330
- outdated
486
+ <span className="font-mono">{place.path}</span> in an earlier commit, where it posts.
487
+ It's outdated only if a later commit changed its lines
331
488
  </>
332
489
  )}
333
490
  </p>
@@ -336,82 +493,84 @@ function CommentForm({
336
493
  autoFocus
337
494
  label="Review comment"
338
495
  value={body}
339
- onChange={(text) => {
340
- typed.current = text;
341
- setBody(text);
342
- }}
496
+ onChange={setTyped}
343
497
  placeholder="Leave a comment"
344
498
  />
345
499
  <div className="flex flex-wrap justify-end gap-2">
346
- <Button variant="ghost" onClick={cancel}>
500
+ <Button variant="ghost" disabled={busy} onClick={cancel}>
347
501
  Cancel
348
502
  </Button>
349
503
  {!reviewing && (
350
- <Button
351
- variant="outline"
352
- disabled={empty || posted.isPending}
353
- onClick={() => posted.mutate(body)}
354
- >
504
+ <Button variant="outline" disabled={empty || busy} onClick={() => posted.mutate(body)}>
355
505
  Add single comment
356
506
  </Button>
357
507
  )}
358
508
  <Button
359
- disabled={empty || posted.isPending}
360
- onClick={() => start(body)}
509
+ disabled={empty || busy}
510
+ onClick={() => kept.mutate(body)}
361
511
  data-hotkey={hotkeys.submit}
362
512
  >
363
- {reviewing ? 'Add review comment' : 'Start a review'}
513
+ {kept.isPending ? 'Saving…' : kept.isError ? 'Try again' : keep}
364
514
  <HotkeyHint keys={hotkeys.submit} />
365
515
  </Button>
366
516
  </div>
367
- <Failed error={posted.error} />
517
+ <Failed error={posted.error ?? kept.error} />
368
518
  </section>
369
519
  );
370
520
  }
371
521
 
522
+ /** How long the summary waits after the last key before it's saved. */
523
+ const summaryPause = 1000;
524
+
372
525
  /**
373
526
  * **Review changes**' dialog: a summary, what the review says of the pull request, and its submit,
374
- * with the drafts the page holds, or the viewer's pending review started elsewhere. It starts
375
- * from the page's draft, and each change is the draft's too, so closing the dialog keeps it.
527
+ * with the viewer's pending review's drafts. The summary is the pending review's body, held by the
528
+ * page's machine, `summary`, which saves it a second after the last key and as the dialog closes,
529
+ * starting a pending review when there's none; what the review says is the page's, as GitHub keeps
530
+ * none on a pending review.
376
531
  */
377
532
  function ReviewBox({
378
533
  repo,
379
534
  own,
380
- start,
381
- setDraft,
535
+ summary,
536
+ send,
537
+ event,
538
+ setEvent,
382
539
  drafted,
383
- earlier,
540
+ behind,
384
541
  submit,
385
542
  discard,
386
- discardEarlier,
387
543
  }: {
388
544
  readonly repo: string;
389
545
  /** Whether the viewer opened the pull request, who can neither approve it nor ask for changes. */
390
546
  readonly own: boolean;
391
- /** The draft as it is when the dialog opens. */
392
- readonly start: () => ReviewDraft;
393
- readonly setDraft: (change: (held: ReviewDraft) => ReviewDraft) => void;
547
+ readonly summary: Summary;
548
+ readonly send: (event: SummaryEvent) => Summary;
549
+ readonly event: ReviewEvent;
550
+ readonly setEvent: (event: ReviewEvent) => void;
394
551
  readonly drafted: number;
395
- /** How many of the drafts were written on an earlier head, and post there. */
396
- readonly earlier: number;
397
- readonly submit: (event: ReviewEvent, body: string) => Promise<void>;
398
- /** Discards a pending review started elsewhere, and its comments, when there's one. */
552
+ /** Whether the pending review is on an earlier commit than the latest, where its drafts post. */
553
+ readonly behind: boolean;
554
+ /** Submits the review with the summary, once no save of it is in flight. */
555
+ readonly submit: (event: ReviewEvent) => Promise<void>;
556
+ /** Discards the pending review and its comments, when there's one. */
399
557
  readonly discard: (() => Promise<void>) | undefined;
400
- readonly discardEarlier: () => void;
401
558
  }) {
402
- // Its own state answers at once, and each change is the page's draft too, which reopening reads.
403
- const [{ body, event }, setHeld] = useState(start);
404
- const change = (next: Partial<ReviewDraft>) => {
405
- setHeld((held) => ({ ...held, ...next }));
406
- setDraft((held) => ({ ...held, ...next }));
407
- };
408
-
409
559
  const acted = useMutation({ mutationFn: (act: () => Promise<void>) => act() });
560
+ const body = summary.text;
410
561
  // GitHub refuses a comment with nothing in it, and changes asked for with no word of which.
411
562
  const empty = body.trim() === '';
412
563
  const refused =
413
564
  (event === 'COMMENT' && empty && drafted === 0) || (event === 'REQUEST_CHANGES' && empty);
414
- const comments = drafted === 1 ? '1 pending comment' : `${drafted} pending comments`;
565
+ const comments = pendingSaid(drafted);
566
+ const status =
567
+ summary.kind === 'saving'
568
+ ? 'Saving…'
569
+ : summary.kind === 'refused'
570
+ ? 'Not saved'
571
+ : summary.kind === 'synced' && summary.server !== ''
572
+ ? 'Saved'
573
+ : undefined;
415
574
 
416
575
  return (
417
576
  <>
@@ -424,32 +583,36 @@ function ReviewBox({
424
583
  A summary, and whether the review comments, approves or asks for changes.
425
584
  </DialogDescription>
426
585
  </DialogHeader>
427
- {earlier > 0 && (
428
- // Discarding them deletes them, so it's a destructive button after the line, not a link in it.
429
- <div className="flex flex-wrap items-center gap-2">
430
- <p className="text-muted-foreground">
431
- {earlier === 1 ? '1 comment was' : `${earlier} comments were`} written before the latest
432
- commit, and {earlier === 1 ? 'posts' : 'post'} on the commit{' '}
433
- {earlier === 1 ? 'it was' : 'they were'} written on, as outdated.
434
- </p>
435
- <Button variant="destructive" size="sm" onClick={discardEarlier}>
436
- Discard {earlier === 1 ? 'it' : 'them'}
437
- </Button>
438
- </div>
586
+ {behind && (
587
+ <p className="text-muted-foreground">
588
+ Your pending review is on an earlier commit than the latest, and its comments post there.
589
+ Each is outdated only if a later commit changed its lines.
590
+ </p>
439
591
  )}
440
592
  <MarkdownEditor
441
593
  repo={repo}
442
594
  label="Review summary"
443
595
  value={body}
444
- onChange={(next) => change({ body: next })}
596
+ onChange={(text) => send({ type: 'type', text })}
445
597
  placeholder="Leave a comment"
446
598
  />
599
+ {status !== undefined && (
600
+ <p className="flex items-center gap-2 text-meta text-muted-foreground" role="status">
601
+ {status}
602
+ {summary.kind === 'refused' && (
603
+ <Button variant="outline" size="sm" onClick={() => send({ type: 'send' })}>
604
+ Try again
605
+ </Button>
606
+ )}
607
+ </p>
608
+ )}
609
+ <Failed error={summary.kind === 'refused' ? summary.error : null} />
447
610
  <RadioGroup
448
611
  aria-label="What the review says"
449
612
  value={event}
450
613
  onValueChange={(value) => {
451
614
  const picked = events.find((each) => each.event === value);
452
- if (picked !== undefined) change({ event: picked.event });
615
+ if (picked !== undefined) setEvent(picked.event);
453
616
  }}
454
617
  >
455
618
  {events.map((each) => {
@@ -486,7 +649,7 @@ function ReviewBox({
486
649
  <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
487
650
  <Button
488
651
  disabled={refused || acted.isPending}
489
- onClick={() => acted.mutate(() => submit(event, body))}
652
+ onClick={() => acted.mutate(() => submit(event))}
490
653
  data-hotkey={hotkeys.submit}
491
654
  >
492
655
  Submit review
@@ -500,9 +663,9 @@ function ReviewBox({
500
663
  /**
501
664
  * A pull request's Files changed: its diff, the review comments on its lines in threads, and, for
502
665
  * those the drop-in lets review it, a comment on lines picked from the gutter, posted alone or
503
- * kept for a review the viewer submits as a comment, an approval or changes requested. The page
504
- * holds a review's drafts until it's submitted; a pending review started elsewhere shows, and is
505
- * submitted or discarded here.
666
+ * saved in the viewer's pending review, which they submit as a comment, an approval or changes
667
+ * requested. The pending review is the drop-in's: each draft, its edit and its delete are saved as
668
+ * they're made, so a reload, another tab and `gh` show the same review.
506
669
  */
507
670
  export function PullFiles({
508
671
  place,
@@ -511,59 +674,120 @@ export function PullFiles({
511
674
  readonly place: RepoPlace;
512
675
  readonly pull: PullDetail;
513
676
  }) {
677
+ // Its state is one pull request's: another's page draws it anew, so nothing held leaks there.
678
+ return <FilesOf key={`${place.owner}/${place.repo}#${pull.number}`} place={place} pull={pull} />;
679
+ }
680
+
681
+ function FilesOf({ place, pull }: { readonly place: RepoPlace; readonly pull: PullDetail }) {
682
+ const clients = useClients();
514
683
  const client = useQueryClient();
515
684
  const { viewer } = useRouteContext({ from: '__root__' });
516
685
  const allowed = useAllowed(place, pull.number);
517
686
  const repo = `${place.owner}/${place.repo}`;
518
- const base = useQuery(mergeBaseOf(place, pull)).data;
519
- const comments = useQuery(lineCommentsOf(place, pull.number));
520
- const pending = useQuery(reviewsOf(place, pull.number)).data?.find(
521
- (review) => review.state === 'PENDING',
522
- );
523
- const elsewhere = useQuery({
524
- ...pendingCommentsOf(place, pull.number, pending?.id),
687
+ const base = useQuery(mergeBaseOf(clients, place, pull)).data;
688
+ const comments = useQuery(lineCommentsOf(clients, place, pull.number, pull.head.sha));
689
+ // GraphQL answers only the signed in, as GitHub's does: a visitor sees each thread as it is,
690
+ // and so does someone whose session ended, whose page still holds what it read before.
691
+ const read = useQuery({ ...threadsOf(clients, place, pull.number), enabled: viewer !== null });
692
+ const states = viewer === null ? undefined : read.data;
693
+ const reviews = useQuery(reviewsOf(clients, place, pull.number));
694
+ const pending = reviews.data?.find((review) => review.state === 'PENDING');
695
+ const drafts = useQuery({
696
+ ...pendingCommentsOf(clients, place, pull.number, pending?.id),
525
697
  enabled: pending !== undefined,
526
698
  });
527
- const drafts = useQuery(draftsOf(place, pull.number)).data ?? [];
699
+ // The pending comments as the drop-in last answered, once it has: an edit to one gone lets go.
700
+ const draftNodes =
701
+ reviews.isSuccess && pending === undefined
702
+ ? ''
703
+ : drafts.isSuccess
704
+ ? drafts.data.map((draft) => draft.node).join(' ')
705
+ : undefined;
706
+ useEffect(() => {
707
+ if (draftNodes !== undefined) {
708
+ keepEdits(client, place, pull.number, draftNodes === '' ? [] : draftNodes.split(' '));
709
+ }
710
+ }, [client, place, pull.number, draftNodes]);
528
711
  // The lines picked, and the head whose diff they were picked from, which a push may move on from.
529
- const [picked, setPicked] = useState<(LinePlace & { readonly head: string }) | undefined>();
530
- const typed = useRef('');
712
+ const [picked, setPicked] = usePicked(place, pull.number);
531
713
  const [reviewing, setReviewing] = useState(false);
714
+ const [event, setEvent] = useState<ReviewEvent>('COMMENT');
532
715
  const login = viewer?.login;
533
716
  const canReview = allowed.has('pull.review') && login !== undefined;
534
717
 
535
- const setDrafts = (change: (held: readonly Draft[]) => readonly Draft[]) =>
536
- client.setQueryData(draftsOf(place, pull.number).queryKey, (held) => change(held ?? []));
718
+ const refresh = () => refreshReviews(client, place, pull.number);
719
+ const refreshDrafts = () => refreshPending(client, place, pull.number);
720
+
721
+ const head = pull.head.sha;
722
+ // The commit the pending review is on, where each of its drafts goes: a push moves the head on.
723
+ const reviewed = pending?.commit ?? undefined;
724
+ const behind = reviewed !== undefined && reviewed !== head;
725
+ const held = useMemo(() => drafts.data ?? [], [drafts.data]);
537
726
 
538
- // What **Review changes** holds, which closing it keeps, read as it opens.
539
- const draftKey = reviewDraftOf(place, pull.number).queryKey;
540
- const setDraft = (change: (held: ReviewDraft) => ReviewDraft) =>
541
- client.setQueryData(draftKey, (held) => change(held ?? noReviewDraft));
727
+ // With a review pending, a reply is kept in it, naming its thread by the node GraphQL gives it.
728
+ const replyIn = (first: LineComment): ThreadReply | undefined => {
729
+ if (!canReview) return undefined;
730
+
731
+ if (pending === undefined) {
732
+ return {
733
+ kind: 'post',
734
+ send: async (body) => {
735
+ await replyTo(clients, place, pull, first, body);
736
+ await refresh();
737
+ },
738
+ };
739
+ }
542
740
 
543
- // A pending review started elsewhere brings its summary, unless one's already typed.
544
- const startDraft = () => {
545
- const held = client.getQueryData(draftKey) ?? noReviewDraft;
546
- const started = pending?.body ?? '';
741
+ const thread = states?.get(first.id);
742
+ if (thread === undefined) return { kind: 'loading' };
547
743
 
548
- return held.body === '' && started !== '' ? { ...held, body: started } : held;
744
+ return {
745
+ kind: 'keep',
746
+ joins: `${yourReview} · ${pendingSaid(held.length)}`,
747
+ send: async (body) => {
748
+ await replyDraft(clients, pending.node, thread.id, body);
749
+ await refreshDrafts();
750
+ },
751
+ };
549
752
  };
550
753
 
551
- const refresh = () => refreshReviews(client, place, pull.number);
754
+ const edit = (draft: LineComment) => async (body: string) => {
755
+ await editDraft(clients, draft.node, body);
756
+ await refreshDrafts();
757
+ };
552
758
 
553
- const head = pull.head.sha;
554
- const current = drafts.filter((draft) => draft.head === head);
759
+ const remove = (draft: LineComment) => async () => {
760
+ await deleteDraft(clients, draft.node);
761
+ await refreshDrafts();
762
+ };
555
763
 
556
- // A reply joins no pending review: the drop-in adds none to one, so it waits until it's done.
557
- const replyIn = (first: LineComment) =>
558
- canReview && pending === undefined
559
- ? async (body: string) => {
560
- await replyTo(place, pull, first, body);
561
- await refresh();
562
- }
563
- : undefined;
764
+ // The diff draws each note in a slot by its place in the list: a key keeps each box, and the
765
+ // writes it has in flight, with its own comment when a note above it goes.
766
+ const pendingBox = (draft: LineComment, framed = true) => (
767
+ <Pending
768
+ key={draft.node}
769
+ place={place}
770
+ pull={pull.number}
771
+ repo={repo}
772
+ login={login ?? draft.login}
773
+ draft={draft}
774
+ edit={edit(draft)}
775
+ remove={remove(draft)}
776
+ framed={framed}
777
+ />
778
+ );
779
+
780
+ // A reply kept in the review goes where its thread goes, on the diff or folded outdated, since
781
+ // its place is its thread's; the review's other drafts go on their lines.
782
+ const onLines = useMemo(() => held.filter((draft) => draft.replyTo === undefined), [held]);
783
+ const keptIn = (first: LineComment) =>
784
+ held.flatMap((draft) => (draft.replyTo === first.id ? [pendingBox(draft, false)] : []));
564
785
 
565
786
  const { notes, apart } = useMemo(() => {
566
- const saved = onHead(comments.data ?? [], head);
787
+ const saved = onHead(comments.data ?? []);
788
+ // A draft posts on its review's commit, which decides where it goes, as a saved thread's own
789
+ // lines decide where it goes: the latest diff draws drafts only while the review is on it.
790
+ const shown = behind ? [] : onLines;
567
791
  const threads = new Map<number, LineComment[]>();
568
792
 
569
793
  for (const comment of saved) {
@@ -576,28 +800,40 @@ export function PullFiles({
576
800
  ...saved.flatMap((comment) =>
577
801
  comment.replyTo === undefined ? [noteOn(comment, `thread:${comment.id}`)] : [],
578
802
  ),
579
- ...onHead(elsewhere.data ?? [], head).map((comment) =>
580
- noteOn(comment, `pending:${comment.id}`),
581
- ),
582
- ...current.map((draft) => noteOn(draft, `draft:${draft.key}`)),
803
+ ...shown.map((comment) => noteOn(comment, `pending:${comment.id}`)),
583
804
  ...(picked === undefined || picked.head !== head ? [] : [noteOn(picked, 'form')]),
584
805
  ];
585
806
 
807
+ // Keyed by its lines, so lines picked anew open a form of their own, with no earlier refusal.
586
808
  const form = picked && (
587
809
  <CommentForm
810
+ key={JSON.stringify(picked)}
588
811
  repo={repo}
589
812
  place={picked}
590
813
  earlier={picked.head !== head}
591
- typed={typed}
592
- reviewing={drafts.length > 0}
814
+ held={{ place, pull: pull.number }}
815
+ reviewing={pending !== undefined}
593
816
  cancel={() => setPicked(undefined)}
594
817
  single={async (body) => {
595
- await commentOnLines(place, pull.number, { ...picked, body });
818
+ await commentOnLines(clients, place, pull.number, { ...picked, body });
596
819
  await refresh();
597
820
  setPicked(undefined);
598
821
  }}
599
- start={(body) => {
600
- setDrafts((held) => [...held, { ...picked, key: crypto.randomUUID(), body }]);
822
+ start={async (body) => {
823
+ if (pending === undefined) {
824
+ await startReview(clients, place, pull.number, {
825
+ head: picked.head,
826
+ draft: { ...picked, body },
827
+ });
828
+ } else if (pending.commit === picked.head) {
829
+ await addDraft(clients, pending.node, { ...picked, body });
830
+ } else {
831
+ throw new Error(
832
+ 'Your pending review is on an earlier commit: submit or discard it to comment on the latest.',
833
+ );
834
+ }
835
+
836
+ await refreshDrafts();
601
837
  setPicked(undefined);
602
838
  }}
603
839
  />
@@ -611,38 +847,31 @@ export function PullFiles({
611
847
  const thread = threads.get(Number(id)) ?? [];
612
848
  const first = thread[0];
613
849
 
850
+ // Keyed by its thread, as the pending boxes are by their comment.
614
851
  return (
615
- <Thread
616
- repo={repo}
617
- comments={thread}
618
- reply={first === undefined ? undefined : replyIn(first)}
619
- />
852
+ <ResolvableThread
853
+ key={key}
854
+ repo={place}
855
+ pull={pull.number}
856
+ thread={states?.get(Number(id))}
857
+ place={first === undefined ? '' : `${first.path}, ${linesSaid(first)}`}
858
+ >
859
+ <Thread
860
+ place={place}
861
+ pull={pull.number}
862
+ repo={repo}
863
+ comments={thread}
864
+ kept={first === undefined ? undefined : keptIn(first)}
865
+ reply={first === undefined ? undefined : replyIn(first)}
866
+ />
867
+ </ResolvableThread>
620
868
  );
621
869
  }
622
870
 
623
871
  case 'pending': {
624
- const comment = elsewhere.data?.find((each) => each.id === Number(id));
625
-
626
- return (
627
- comment && (
628
- <Pending repo={repo} login={comment.login} draft={comment} remove={undefined} />
629
- )
630
- );
631
- }
872
+ const draft = held.find((each) => each.id === Number(id));
632
873
 
633
- case 'draft': {
634
- const draft = drafts.find((each) => each.key === id);
635
-
636
- return (
637
- draft && (
638
- <Pending
639
- repo={repo}
640
- login={login ?? ''}
641
- draft={draft}
642
- remove={() => setDrafts((held) => held.filter((each) => each.key !== id))}
643
- />
644
- )
645
- );
874
+ return draft && pendingBox(draft);
646
875
  }
647
876
 
648
877
  default:
@@ -653,27 +882,24 @@ export function PullFiles({
653
882
  const notes: Notes = {
654
883
  of: (path) => placed.flatMap((each) => (each.path === path ? [each.note] : [])),
655
884
  render,
656
- // A pending review started elsewhere takes no drafts from here: the drop-in adds none to one.
885
+ // A pending review on an earlier commit takes no draft from the latest one's lines.
657
886
  pick:
658
- canReview && pending === undefined
659
- ? (path, lines) => {
660
- typed.current = '';
661
- setPicked({ ...placeOfPick(path, lines), head });
662
- }
887
+ canReview && !behind
888
+ ? (path, lines) => setPicked({ ...placeOfPick(path, lines), head })
663
889
  : undefined,
664
890
  };
665
891
 
666
892
  // Lines picked before a push are an earlier commit's: the new diff may not have them, or have
667
- // other lines there, so their form sits above it, until it's posted, held or cancelled.
893
+ // other lines there, so their form sits above it, until it's posted, saved or cancelled.
668
894
  return { notes, apart: picked?.head === head ? undefined : form };
669
895
  }, [
670
896
  comments.data,
671
- elsewhere.data,
672
- drafts,
673
- current,
897
+ states,
898
+ held,
674
899
  head,
675
900
  picked,
676
901
  canReview,
902
+ behind,
677
903
  pending,
678
904
  repo,
679
905
  place,
@@ -681,28 +907,51 @@ export function PullFiles({
681
907
  login,
682
908
  ]);
683
909
 
684
- /**
685
- * Submits the pending review started elsewhere, or the drafts as a review of the head they were
686
- * written on, removing only those it sent: a draft added meanwhile stays.
687
- */
688
- const submit = async (event: ReviewEvent, body: string) => {
689
- if (pending !== undefined) {
690
- await submitPending(place, pull.number, pending.id, { event, body });
691
- } else {
692
- const sent = drafts;
693
- const heads = [...new Set(sent.map((draft) => draft.head))];
694
-
695
- if (heads.length > 1) {
696
- throw new Error(
697
- 'Your comments are on different commits: discard those written before the latest to submit the rest.',
698
- );
699
- }
910
+ // The summary is the pending review's body: saving one with no review starts it, empty or not.
911
+ const save = async (body: string) => {
912
+ if (pending !== undefined) await saveSummary(clients, place, pull.number, pending.id, body);
913
+ else if (body.trim() !== '') await startReview(clients, place, pull.number, { head, body });
914
+
915
+ await refreshDrafts();
916
+ };
917
+
918
+ const { summary, send, end } = useHeldSummary(save);
919
+ useUnsaved(client, summary.kind !== 'synced');
920
+
921
+ // The drop-in's summary, read again, which the machine follows while nothing is typed past it.
922
+ const server = pending?.body ?? '';
923
+ useEffect(() => {
924
+ send({ type: 'read', body: server });
925
+ }, [server, send]);
926
+
927
+ // A typed summary is saved a second after the last key, or at once once the box is closed.
928
+ useEffect(() => {
929
+ if (summary.kind !== 'typed') return;
700
930
 
701
- await submitReview(place, pull.number, { event, body, head: heads[0] ?? head, drafts: sent });
702
- setDrafts((held) => held.filter((draft) => !sent.includes(draft)));
931
+ if (!reviewing) {
932
+ send({ type: 'send' });
933
+
934
+ return;
703
935
  }
704
936
 
705
- setDraft(() => noReviewDraft);
937
+ const timer = setTimeout(() => send({ type: 'send' }), summaryPause);
938
+
939
+ return () => clearTimeout(timer);
940
+ }, [summary, reviewing, send]);
941
+
942
+ /** Submits the pending review with its drafts, or a review of the head with nothing pending. */
943
+ const submit = async (picked: ReviewEvent) => {
944
+ await end(async (body) => {
945
+ // A save that landed while the submit waited may have started the pending review.
946
+ const now = client
947
+ .getQueryData(reviewsOf(clients, place, pull.number).queryKey)
948
+ ?.find((review) => review.state === 'PENDING');
949
+ if (now === undefined)
950
+ await submitNew(clients, place, pull.number, { event: picked, body, head });
951
+ else await submitPending(clients, place, pull.number, now.id, { event: picked, body });
952
+ });
953
+
954
+ setEvent('COMMENT');
706
955
  setReviewing(false);
707
956
  await refresh();
708
957
  };
@@ -712,25 +961,32 @@ export function PullFiles({
712
961
  pending === undefined
713
962
  ? undefined
714
963
  : async () => {
715
- await discardPending(place, pull.number, pending.id);
716
- setDraft(() => noReviewDraft);
964
+ await end(() => discardPending(clients, place, pull.number, pending.id));
965
+ setEvent('COMMENT');
717
966
  setReviewing(false);
718
967
  await refresh();
719
968
  };
720
969
 
721
- const drafted = pending === undefined ? drafts.length : (elsewhere.data?.length ?? 0);
722
- const earlier = pending === undefined ? drafts.length - current.length : 0;
970
+ const drafted = held.length;
971
+ // Drafts on the review's earlier commit aren't drawn on the latest diff: they're listed above it.
972
+ const earlier = behind ? onLines : [];
723
973
 
724
974
  return (
725
975
  <div className="flex flex-col gap-3">
726
976
  {canReview && (
727
977
  <div className="flex flex-wrap items-center justify-end gap-2">
728
- {pending !== undefined && (
978
+ {behind && (
729
979
  <p className="mr-auto text-sm text-muted-foreground">
730
- You have a pending review, started elsewhere. Submit or discard it to comment here.
980
+ {yourReview} is on an earlier commit: submit or discard it to comment on the latest.
731
981
  </p>
732
982
  )}
733
- <Dialog open={reviewing} onOpenChange={setReviewing}>
983
+ <Dialog
984
+ open={reviewing}
985
+ onOpenChange={(open) => {
986
+ if (open) send({ type: 'open' });
987
+ setReviewing(open);
988
+ }}
989
+ >
734
990
  <DialogTrigger render={<Button />}>
735
991
  Review changes
736
992
  {drafted > 0 && <Badge variant="secondary">{drafted}</Badge>}
@@ -740,29 +996,39 @@ export function PullFiles({
740
996
  <ReviewBox
741
997
  repo={repo}
742
998
  own={pull.author === login}
743
- start={startDraft}
744
- setDraft={setDraft}
999
+ summary={summary}
1000
+ send={send}
1001
+ event={event}
1002
+ setEvent={setEvent}
745
1003
  drafted={drafted}
746
- earlier={earlier}
1004
+ behind={behind}
747
1005
  submit={submit}
748
1006
  discard={discard}
749
- discardEarlier={() =>
750
- setDrafts((held) => held.filter((each) => each.head === head))
751
- }
752
1007
  />
753
1008
  </DialogContent>
754
1009
  </Dialog>
755
1010
  </div>
756
1011
  )}
757
- <Failed error={comments.error ?? elsewhere.error} />
1012
+ <Failed error={comments.error ?? (viewer === null ? null : read.error) ?? drafts.error} />
1013
+ {earlier.length > 0 && (
1014
+ <section aria-label="Pending comments on an earlier commit" className="flex flex-col gap-2">
1015
+ {earlier.map((draft) => (
1016
+ <div key={draft.id}>{pendingBox(draft)}</div>
1017
+ ))}
1018
+ </section>
1019
+ )}
758
1020
  <OutdatedThreads
759
1021
  place={place}
760
- threads={outdatedThreads(comments.data ?? [], head)}
1022
+ pull={pull.number}
1023
+ threads={outdatedThreads(comments.data ?? [])}
1024
+ states={states}
1025
+ kept={keptIn}
761
1026
  reply={replyIn}
762
1027
  />
763
1028
  {apart}
764
1029
  <DiffView
765
1030
  list={pullFiles(
1031
+ clients,
766
1032
  repo,
767
1033
  pull.number,
768
1034
  head,