rvlib-shipkit 2.9.0 → 2.11.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 (75) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +164 -0
  4. package/src/cli/cmd_Review.ts +2 -1
  5. package/src/cli/family-pages.ts +1 -0
  6. package/src/cli/registry.ts +2 -0
  7. package/src/collections/pings.ts +6 -4
  8. package/src/core/app-icon.ts +17 -4
  9. package/src/core/scratch-objects.ts +56 -0
  10. package/src/core/trace-audit.ts +13 -1
  11. package/src/home/home-paths.ts +4 -0
  12. package/src/home/home-routes.ts +36 -2
  13. package/src/home/hubs.ts +5 -0
  14. package/src/home/inbox-shape.ts +182 -0
  15. package/src/home/inbox.ts +48 -0
  16. package/src/home/run-daemon.ts +12 -2
  17. package/src/home/serve-web.ts +155 -16
  18. package/src/ledger/git-scan.ts +73 -25
  19. package/src/ledger/repo-view.ts +2 -22
  20. package/src/media-kinds.ts +7 -0
  21. package/src/media-store/content.ts +51 -0
  22. package/src/media-store/daemon.ts +91 -0
  23. package/src/media-store/db.ts +74 -0
  24. package/src/media-store/fact.ts +9 -0
  25. package/src/media-store/kind.ts +44 -0
  26. package/src/media-store/purge.ts +139 -0
  27. package/src/media-store/remote.ts +93 -0
  28. package/src/media-store/space.ts +124 -0
  29. package/src/media-store/sync.ts +101 -0
  30. package/src/media-store/upload.ts +98 -0
  31. package/src/repo-config.ts +4 -0
  32. package/src/review/anim.ts +6 -5
  33. package/src/review/cells.ts +552 -0
  34. package/src/review/format.ts +1 -1
  35. package/src/review/media-kind.ts +84 -0
  36. package/src/review/media-read.ts +48 -0
  37. package/src/review/model.ts +43 -5
  38. package/src/review/previews.ts +153 -0
  39. package/src/review/routes.ts +105 -47
  40. package/src/review/store.ts +106 -45
  41. package/src/review/trailer-desk.ts +79 -46
  42. package/src/review/trailer-media.ts +163 -0
  43. package/src/review/trailer-routes.ts +5 -2
  44. package/src/serve/hub-app/home-st.ts +39 -9
  45. package/src/serve/hub-app/home.html +2 -1
  46. package/src/serve/hub-app/hub-app.tsx +7 -23
  47. package/src/serve/hub-app/icons.tsx +2 -0
  48. package/src/serve/hub-app/inbox-st.ts +144 -0
  49. package/src/serve/hub-app/inbox-view.tsx +205 -0
  50. package/src/serve/hub-app/inbox.css +73 -0
  51. package/src/serve/hub-app/item-view.tsx +19 -0
  52. package/src/serve/hub-app/keys.ts +4 -3
  53. package/src/serve/hub-app/palette-st.ts +2 -1
  54. package/src/serve/hub-app/project-list.tsx +1 -0
  55. package/src/serve/hub-app/projects-svc.ts +1 -1
  56. package/src/serve/hub-app/repo-st.ts +1 -1
  57. package/src/serve/hub-app/review/kind-view.tsx +21 -22
  58. package/src/serve/hub-app/review/kit.tsx +11 -12
  59. package/src/serve/hub-app/review/review-board.tsx +15 -13
  60. package/src/serve/hub-app/review/review-cells.tsx +241 -0
  61. package/src/serve/hub-app/review/review-kit.ts +79 -0
  62. package/src/serve/hub-app/review/review-list.tsx +87 -122
  63. package/src/serve/hub-app/review/review-page.tsx +22 -79
  64. package/src/serve/hub-app/review/review-st.ts +269 -698
  65. package/src/serve/hub-app/review/review-thread.tsx +302 -0
  66. package/src/serve/hub-app/review/review-views.tsx +322 -253
  67. package/src/serve/hub-app/review/thread-st.ts +770 -0
  68. package/src/serve/hub-app/review.css +235 -91
  69. package/src/serve/hub-runtime.ts +9 -4
  70. package/src/serve/serve-hub.ts +4 -1
  71. package/src/serve/warm-cell.ts +6 -1
  72. package/src/trailer/footage.ts +6 -2
  73. package/src/trailer/passage.ts +4 -2
  74. package/src/trailer/prune.ts +6 -10
  75. package/src/serve/hub-app/review/review-answer.tsx +0 -249
@@ -0,0 +1,770 @@
1
+ // one open card of the review page read as a thread (wiki build/shipkit/review.md, The review page): its cells from
2
+ // `GET /api/review/threads/<id>`, what he folded, the contents strip and where a click on it lands, his draft on the
3
+ // newest version (rectangles, reactions, stars, the pick, his word), each clip's clock. Made when a card opens,
4
+ // disposed when another one does. Only the newest version takes his marks: an older one shows what was said on it
5
+ import { makeAutoObservable, observableRef, runInAction } from 'mobx'
6
+ import type { Cell, EventCell, NoteCell, ReplyCell, ThreadView, VerdictCell, VersionCell } from '../../../review/cells.ts'
7
+ import {
8
+ asOptions,
9
+ isApproved,
10
+ isChoice,
11
+ isGallery,
12
+ isPair,
13
+ STARS,
14
+ viewTag,
15
+ type Item,
16
+ type MediaView,
17
+ type Rect,
18
+ type ReviewReaction,
19
+ type ReviewStatus,
20
+ type ReviewView,
21
+ type Side,
22
+ } from '../../../review/model.ts'
23
+ import { ClipSt } from './clip-st.ts'
24
+ import { etagLoader, postJson, type Zoom } from './review-kit.ts'
25
+ import type { ReviewSt } from './review-st.ts'
26
+
27
+ export interface Draft {
28
+ rects: Rect[]
29
+ comment: string
30
+ reactions?: ReviewReaction[]
31
+ /** the option he picked, on a choice card */
32
+ pick?: number
33
+ }
34
+
35
+ const EMPTY: Draft = { rects: [], comment: '' }
36
+
37
+ const isDirty = (d: Draft | undefined): boolean => d !== undefined && (d.rects.length > 0 || d.comment.trim() !== '' || (d.reactions ?? []).length > 0 || d.pick !== undefined)
38
+
39
+ /** a framed cell: every kind but the thin event line */
40
+ export type Framed = VersionCell | VerdictCell | ReplyCell | NoteCell
41
+
42
+ /** one line of the thread as drawn: a day's divider, a run of state changes, or a framed cell */
43
+ export type Line = { kind: 'day'; day: string } | { kind: 'events'; cells: EventCell[] } | { kind: 'cell'; cell: Framed }
44
+
45
+ /** one item of the contents strip: a cell, or one view of a version, and the key a click unfolds */
46
+ export interface Entry {
47
+ key: string
48
+ kind: Framed['kind'] | 'view'
49
+ cell: string
50
+ view?: number
51
+ label: string
52
+ /** the kind's word on the strip */
53
+ badge: string
54
+ /** a status or reaction tone class, `st-…` or `re-…` */
55
+ tone: string | null
56
+ /** it is the one his answer goes to */
57
+ head: boolean
58
+ }
59
+
60
+ /** one view on the minimap: its tag and his answer on it; `noted` a draft note waits on it for the verdict */
61
+ export interface ViewMark {
62
+ view: number
63
+ tag: string
64
+ answer: 'none' | ReviewStatus | 'scored' | 'picked' | 'sent'
65
+ noted: boolean
66
+ }
67
+
68
+ /** a note said on a view of an older answer: a rectangle or a reaction, with the verdict that carried it */
69
+ export interface SaidNote {
70
+ verdict: VerdictCell
71
+ rect?: { r: Rect; n: number }
72
+ reaction?: ReviewReaction
73
+ }
74
+
75
+ /** the dom id of a cell and of a view of a version: a message id carries a slash */
76
+ export const cellDom = (id: string): string => `rvc-${id.replace(/[^A-Za-z0-9-]/g, '_')}`
77
+ export const viewDom = (id: string, view: number): string => `${cellDom(id)}-v${view}`
78
+ export const viewKey = (id: string, view: number): string => `${id}#${view}`
79
+
80
+ const sameSpot = (r: ReviewReaction, view: number, tile: number | undefined): boolean => r.view === view && r.tile === tile
81
+ const dayOf = (iso: string): string => new Date(iso).toLocaleDateString(undefined, { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' })
82
+
83
+ /** a view's kind, as its badge says it */
84
+ export function viewKind(v: ReviewView, choice: boolean): string {
85
+ if (choice) return 'option'
86
+ if (isGallery(v)) return 'gallery'
87
+ const pair = isPair(v.files)
88
+ if (v.audio) return pair ? 'sound · before / after' : 'sound'
89
+ if (v.clip) return pair ? 'clip · before / after' : 'clip'
90
+ return pair ? 'before / after' : 'image'
91
+ }
92
+
93
+ const KIND_WORD: Record<Framed['kind'], string> = { version: 'version', verdict: 'verdict', reply: 'reply', note: 'note' }
94
+
95
+ /** a sound's clock steps a tenth of a second */
96
+ const SOUND_FPS = 10
97
+
98
+ export class ThreadSt {
99
+ data: ThreadView | null = null
100
+ error: string | null = null
101
+ /** what he folded or unfolded by hand, by cell id or `<cell>#<view>`; the rest follows each cell's `open` */
102
+ folds: Record<string, boolean> = {}
103
+ /** a scroll asked of the thread column: it brings that dom id into view once, then clears it */
104
+ jump: string | null = null
105
+ /** the column scrolled to the newest cell once, on the first load */
106
+ landed = false
107
+ private drafts: Record<string, Draft> = {}
108
+ /** the older version his draft sits on: a version landed while he wrote. His answer goes there until he moves it */
109
+ draftOn: string | null = null
110
+ /** he chose to keep his draft on the older version: the banner that offers the move is gone */
111
+ keptOn = false
112
+ /** the newest version's active view: the one last drawn on or picked, whose clip the keys drive */
113
+ view = 0
114
+ /** a picked rectangle of his draft: its note box opens beside it */
115
+ rect: number | null = null
116
+ /** the rectangle whose note box takes the focus once it shows */
117
+ noteFocus: number | null = null
118
+ viewZoom: Record<string, Zoom> = {}
119
+ /** the gallery tile shown large, `<item>#<view>/<tile>` */
120
+ bigTile: string | null = null
121
+ /** a draft card's past frame shown in place of its live one; null is now */
122
+ frame: number | null = null
123
+ /** a card of options shown full, by item id */
124
+ full: Record<string, boolean> = {}
125
+ /** an option row folded or unfolded by hand, by `<item>#<view>` */
126
+ openRows: Record<string, boolean> = {}
127
+ busy = false
128
+ private readonly clips = new Map<string, ClipSt>()
129
+ /** the agent words already sent as read, by message id */
130
+ private readonly reading = new Set<string>()
131
+ private readonly load: () => Promise<ThreadView>
132
+
133
+ constructor(
134
+ private readonly rv: ReviewSt,
135
+ /** the id the address names: an old version opens its thread at its cell */
136
+ readonly id: string,
137
+ view = 0,
138
+ ) {
139
+ this.view = view
140
+ this.load = etagLoader<ThreadView>(() => rv.url(`/api/review/threads/${encodeURIComponent(id)}`))
141
+ makeAutoObservable<this, 'rv' | 'clips' | 'reading' | 'load'>(this, { rv: false, clips: false, reading: false, load: false, data: observableRef })
142
+ }
143
+
144
+ dispose(): void {
145
+ for (const c of this.clips.values()) c.pause()
146
+ this.clips.clear()
147
+ }
148
+
149
+ async refresh(): Promise<void> {
150
+ try {
151
+ const v = await this.load()
152
+ runInAction(() => {
153
+ this.receive(v)
154
+ this.error = null
155
+ })
156
+ } catch (e) {
157
+ runInAction(() => (this.error = (e as Error).message))
158
+ }
159
+ }
160
+
161
+ /** a thread from the server: a cell he sees keeps its fold when a new answer changes the defaults; a version that
162
+ * lands while he writes leaves his draft on the version he started it on */
163
+ receive(v: ThreadView): void {
164
+ if (v === this.data) return
165
+ const before = this.data
166
+ if (before) for (const c of before.cells) if (c.kind !== 'event' && this.folds[c.id] === undefined && this.defaultOpen(c, before) !== this.defaultOpen(c, v)) this.folds = { ...this.folds, [c.id]: this.defaultOpen(c, before) }
167
+ if (before && before.head !== v.head && this.draftOn === null && isDirty(this.drafts[before.head]) && v.members.includes(before.head)) this.draftOn = before.head
168
+ this.data = v
169
+ // an address's view on a link to an old version is that version's view, never the newest's
170
+ if (!before && v.asked !== v.head && this.view > 0) {
171
+ const at = this.view
172
+ this.view = 0
173
+ this.reveal(v.asked, at)
174
+ }
175
+ if (this.draftOn !== null && !v.members.includes(this.draftOn)) this.draftOn = null
176
+ if (this.drafts[v.head] === undefined) {
177
+ const d = this.rv.storedDraft(v.head)
178
+ if (d) this.drafts = { ...this.drafts, [v.head]: d }
179
+ }
180
+ // a draft left under an older version of this thread (a version landed after the page closed) is found again
181
+ if (this.draftOn === null && !isDirty(this.drafts[v.head])) {
182
+ const older = [...v.members].reverse().find((id) => id !== v.head && (isDirty(this.drafts[id]) || isDirty(this.rv.storedDraft(id) ?? undefined)))
183
+ if (older) {
184
+ const d = this.drafts[older] ?? this.rv.storedDraft(older)
185
+ if (d) this.drafts = { ...this.drafts, [older]: d }
186
+ this.draftOn = older
187
+ }
188
+ }
189
+ }
190
+
191
+ private defaultOpen(c: Cell, v: ThreadView): boolean {
192
+ return c.open || c.id === v.asked
193
+ }
194
+
195
+ // ── the cells ──
196
+
197
+ get cells(): Cell[] {
198
+ return this.data?.cells ?? []
199
+ }
200
+
201
+ /** the cell the owner's verdict and reply go to: the newest version, or the raised item no card answers; the older
202
+ * version his draft sits on while a newer one landed */
203
+ get head(): Framed | null {
204
+ const h = this.draftOn ?? this.data?.head
205
+ return (this.cells.find((c) => c.id === h && c.kind !== 'event') as Framed | undefined) ?? null
206
+ }
207
+
208
+ /** the newest version's cell, whoever his answer goes to */
209
+ get newest(): Framed | null {
210
+ const h = this.data?.head
211
+ return (this.cells.find((c) => c.id === h && c.kind !== 'event') as Framed | undefined) ?? null
212
+ }
213
+
214
+ /** his draft moved onto the newest version: his word, and the marks whose view the newest has; what does not fit
215
+ * stays on the older one */
216
+ moveDraft(): void {
217
+ const from = this.draftOn
218
+ const to = this.data?.head
219
+ if (from === null || !to) return
220
+ const d = this.drafts[from] ?? EMPTY
221
+ const views = (this.versionOf(to)?.item.views ?? []).length
222
+ const fits = (view: number | undefined): boolean => (view ?? 0) < views
223
+ const into = this.drafts[to] ?? EMPTY
224
+ const moved: Draft = {
225
+ comment: [into.comment, d.comment].filter((x) => x.trim() !== '').join('\n'),
226
+ rects: [...into.rects, ...d.rects.filter((r) => fits(r.view))],
227
+ ...(into.pick !== undefined ? { pick: into.pick } : {}),
228
+ }
229
+ const reactions = [...(into.reactions ?? []), ...(d.reactions ?? []).filter((r) => fits(r.view) && !(into.reactions ?? []).some((q) => sameSpot(q, r.view, r.tile)))]
230
+ if (reactions.length > 0) moved.reactions = reactions
231
+ const left: Draft = { comment: '', rects: d.rects.filter((r) => !fits(r.view)) }
232
+ const leftReactions = (d.reactions ?? []).filter((r) => !fits(r.view))
233
+ if (leftReactions.length > 0) left.reactions = leftReactions
234
+ this.put(to, moved)
235
+ this.put(from, isDirty(left) ? left : null)
236
+ this.draftOn = null
237
+ this.keptOn = false
238
+ this.rect = null
239
+ }
240
+
241
+ /** he keeps his draft on the older version: his answer goes there */
242
+ keepDraftOn(): void {
243
+ this.keptOn = true
244
+ }
245
+
246
+ get headItem(): Item | null {
247
+ const h = this.head
248
+ return h?.kind === 'version' ? h.item : (h?.kind === 'note' ? (h.item ?? null) : null)
249
+ }
250
+
251
+ /** the newest version takes a verdict and his marks: an agent's card that is no draft */
252
+ get takesVerdict(): boolean {
253
+ const h = this.head
254
+ return h?.kind === 'version' && !h.item.wip
255
+ }
256
+
257
+ /** the version cell an item id names */
258
+ versionOf(id: string): VersionCell | null {
259
+ return (this.cells.find((c) => c.kind === 'version' && c.id === id) as VersionCell | undefined) ?? null
260
+ }
261
+
262
+ /** the thread in reading order: a divider when the day changes, the state changes in a row folded into one line */
263
+ get lines(): Line[] {
264
+ const out: Line[] = []
265
+ let day = ''
266
+ for (const c of this.cells) {
267
+ const d = dayOf(c.at)
268
+ if (d !== day) {
269
+ out.push({ kind: 'day', day: d })
270
+ day = d
271
+ }
272
+ const last = out.at(-1)
273
+ if (c.kind === 'event') {
274
+ if (last?.kind === 'events') last.cells.push(c)
275
+ else out.push({ kind: 'events', cells: [c] })
276
+ } else out.push({ kind: 'cell', cell: c })
277
+ }
278
+ return out
279
+ }
280
+
281
+ // ── folding ──
282
+
283
+ isOpen(c: Cell): boolean {
284
+ const own = this.folds[c.id]
285
+ if (own !== undefined) return own
286
+ return this.data ? this.defaultOpen(c, this.data) : c.open
287
+ }
288
+
289
+ /** a view of a version: open unless he folded it */
290
+ viewOpen(id: string, view: number): boolean {
291
+ return this.folds[viewKey(id, view)] ?? true
292
+ }
293
+
294
+ toggle(key: string, open: boolean): void {
295
+ this.folds = { ...this.folds, [key]: !open }
296
+ }
297
+
298
+ toggleCell(c: Cell): void {
299
+ this.toggle(c.id, this.isOpen(c))
300
+ }
301
+
302
+ toggleView(id: string, view: number): void {
303
+ this.toggle(viewKey(id, view), this.viewOpen(id, view))
304
+ }
305
+
306
+ /** every framed cell folded, or unfolded */
307
+ foldAll(open: boolean): void {
308
+ const next: Record<string, boolean> = {}
309
+ for (const c of this.cells) if (c.kind !== 'event') next[c.id] = open
310
+ this.folds = next
311
+ }
312
+
313
+ /** a click on the contents strip: the cell and its view unfold, and the column scrolls there */
314
+ reveal(cell: string, view?: number): void {
315
+ const next = { ...this.folds, [cell]: true }
316
+ if (view !== undefined) next[viewKey(cell, view)] = true
317
+ this.folds = next
318
+ this.jump = view === undefined ? cellDom(cell) : viewDom(cell, view)
319
+ if (view !== undefined && cell === this.target) this.setView(view)
320
+ }
321
+
322
+ jumped(): void {
323
+ this.jump = null
324
+ }
325
+
326
+ /** where the column opens: the cell an old link names, else the first agent word he has not read, else the newest
327
+ * version's top (the column stops at its end: a short tail shows whole), else the newest framed cell */
328
+ get landing(): string | null {
329
+ const v = this.data
330
+ if (!v) return null
331
+ if (v.asked !== v.head && this.cells.some((c) => c.id === v.asked)) return cellDom(v.asked)
332
+ const unread = this.cells.find((c) => (c.kind === 'reply' || c.kind === 'note') && c.party === 'agent' && !c.read)
333
+ if (unread) return cellDom(unread.id)
334
+ const to = this.cells.find((c) => c.kind === 'version' && c.id === v.head) ?? this.cells.findLast((c) => c.kind !== 'event')
335
+ return to ? cellDom(to.id) : null
336
+ }
337
+
338
+ land(): void {
339
+ this.landed = true
340
+ }
341
+
342
+ // ── the contents strip ──
343
+
344
+ /** every item of the card: each version and each of its views, each verdict, reply and note */
345
+ get contents(): Entry[] {
346
+ const head = this.target
347
+ const out: Entry[] = []
348
+ for (const c of this.cells) {
349
+ if (c.kind === 'event') continue
350
+ const isHead = c.id === head
351
+ if (c.kind === 'version') {
352
+ out.push({ key: c.id, kind: 'version', cell: c.id, label: `v${c.n} · ${c.summary || c.item.title}`, badge: `v${c.n}`, tone: `st-${c.status}`, head: isHead })
353
+ const choice = isChoice(c.item)
354
+ c.item.views.forEach((v, i) => {
355
+ const r = this.reactionShown(c, i)
356
+ out.push({ key: viewKey(c.id, i), kind: 'view', cell: c.id, view: i, label: `${viewTag(c.n, i)}${v.label ? ` ${v.label}` : ''}`, badge: viewKind(v, choice), tone: r?.status ? `re-${r.status}` : this.pickShown(c) === i ? 're-approved' : null, head: isHead })
357
+ })
358
+ } else if (c.kind === 'verdict') out.push({ key: c.id, kind: 'verdict', cell: c.id, label: `on v${c.n} · ${c.summary}`, badge: 'verdict', tone: `st-${c.verdict}`, head: false })
359
+ else out.push({ key: c.id, kind: c.kind, cell: c.id, label: `${c.who === 'owner' ? 'you' : c.who} · ${c.summary}`, badge: KIND_WORD[c.kind], tone: null, head: isHead })
360
+ }
361
+ return out
362
+ }
363
+
364
+ // ── the minimap: where his answer stands on each view of the version it goes to ──
365
+
366
+ /** each view of the version his answer goes to, and his answer on it: none yet, OK, fix or no (a choice: scored or
367
+ * picked). A view with only a draft note (a rectangle, a word) is not answered: the note goes with the verdict.
368
+ * Once a verdict holds the version, every view is answered by it */
369
+ get viewMarks(): ViewMark[] {
370
+ const h = this.head
371
+ if (h?.kind !== 'version' || h.item.wip) return []
372
+ const sent = this.verdictsOn(h.id).findLast((v) => v.current)
373
+ const choice = isChoice(h.item)
374
+ return h.item.views.map((_, i) => {
375
+ const own = this.reactionOf(i)
376
+ const given = sent?.reactions.find((r) => r.view === i && r.tile === undefined)
377
+ const r = own ?? given
378
+ const picked = this.pickShown(h) === i
379
+ const answer: ViewMark['answer'] = picked ? 'picked' : r?.status ? r.status : choice && r?.stars ? 'scored' : sent ? 'sent' : 'none'
380
+ const noted = this.draft.rects.some((q) => (q.view ?? 0) === i) || (own?.comment ?? '').trim() !== ''
381
+ return { view: i, tag: viewTag(h.n, i), answer, noted }
382
+ })
383
+ }
384
+
385
+ /** the views of that version still waiting for his answer, of all its views: « 3 of 5 views waiting for you » */
386
+ get waitingViews(): { waiting: number; of: number } | null {
387
+ const marks = this.viewMarks
388
+ if (marks.length === 0) return null
389
+ return { waiting: marks.filter((m) => m.answer === 'none').length, of: marks.length }
390
+ }
391
+
392
+ // ── what was said on each view ──
393
+
394
+ /** the verdicts on one version, oldest first */
395
+ verdictsOn(id: string): VerdictCell[] {
396
+ return this.cells.filter((c): c is VerdictCell => c.kind === 'verdict' && c.on === id)
397
+ }
398
+
399
+ /** every note said on one view of a version: each verdict's rectangles and its reaction to the view or a tile */
400
+ saidOn(id: string, view: number): SaidNote[] {
401
+ return this.verdictsOn(id).flatMap((v) => [
402
+ ...v.rects.flatMap((r, k) => ((r.view ?? 0) === view ? [{ verdict: v, rect: { r, n: k + 1 } }] : [])),
403
+ ...v.reactions.filter((r) => r.view === view).map((reaction) => ({ verdict: v, reaction })),
404
+ ])
405
+ }
406
+
407
+ /** the sent rectangles drawn over a view of a version, with their number in their verdict */
408
+ sentRects(id: string, view: number, side: Side | undefined): { r: Rect; n: number }[] {
409
+ return this.verdictsOn(id).flatMap((v) => v.rects.flatMap((r, k) => ((r.view ?? 0) === view && r.side === side ? [{ r, n: k + 1 }] : [])))
410
+ }
411
+
412
+ /** the reaction a view shows: his draft's on the newest version, else the latest verdict's */
413
+ reactionShown(c: VersionCell, view: number, tile?: number): ReviewReaction | null {
414
+ if (c.id === this.target && this.takesVerdict) {
415
+ const own = this.reactionOf(view, tile)
416
+ if (own) return own
417
+ }
418
+ for (const v of this.verdictsOn(c.id).reverse()) {
419
+ const r = v.reactions.find((q) => sameSpot(q, view, tile))
420
+ if (r) return r
421
+ }
422
+ return null
423
+ }
424
+
425
+ /** the option picked on a version: his draft's pick on the newest, else the latest verdict's */
426
+ pickShown(c: VersionCell): number | undefined {
427
+ if (c.id === this.target && this.draft.pick !== undefined) return this.draft.pick
428
+ return this.verdictsOn(c.id).findLast((v) => v.pick !== undefined)?.pick
429
+ }
430
+
431
+ // ── his draft on the newest version ──
432
+
433
+ /** the id his draft and his answer go to */
434
+ get target(): string | null {
435
+ return this.draftOn ?? this.data?.head ?? null
436
+ }
437
+
438
+ get draft(): Draft {
439
+ const h = this.target
440
+ return (h && this.drafts[h]) || EMPTY
441
+ }
442
+
443
+ get dirty(): boolean {
444
+ return isDirty(this.draft)
445
+ }
446
+
447
+ /** a draft kept under an id, in memory and in the browser; null drops it */
448
+ private put(id: string, d: Draft | null): void {
449
+ const { [id]: _, ...rest } = this.drafts
450
+ this.drafts = d === null ? rest : { ...rest, [id]: d }
451
+ this.rv.keepDraft(id, d)
452
+ }
453
+
454
+ private edit(f: (d: Draft) => Draft): void {
455
+ const h = this.target
456
+ if (!h) return
457
+ const d = this.draft
458
+ const { reactions, ...rest } = f({ ...d, rects: [...d.rects], reactions: [...(d.reactions ?? [])] })
459
+ this.put(h, reactions && reactions.length > 0 ? { ...rest, reactions } : rest)
460
+ }
461
+
462
+ setComment(comment: string): void {
463
+ this.edit((d) => ({ ...d, comment }))
464
+ }
465
+
466
+ dropDraft(): void {
467
+ const h = this.target
468
+ if (!h) return
469
+ this.put(h, null)
470
+ if (this.draftOn === h) this.draftOn = null
471
+ this.rect = null
472
+ }
473
+
474
+ /** what was sent leaves the draft of `on`; whatever he typed or drew while it was on its way stays */
475
+ private settle(on: string, sent: Draft): void {
476
+ const now = this.drafts[on]
477
+ if (now === undefined || now === sent) this.put(on, null)
478
+ else {
479
+ const left: Draft = {
480
+ comment: now.comment === sent.comment ? '' : now.comment,
481
+ rects: now.rects.filter((r) => !sent.rects.includes(r)),
482
+ ...(now.pick !== undefined && now.pick !== sent.pick ? { pick: now.pick } : {}),
483
+ }
484
+ const reactions = (now.reactions ?? []).filter((r) => !(sent.reactions ?? []).includes(r))
485
+ if (reactions.length > 0) left.reactions = reactions
486
+ this.put(on, isDirty(left) ? left : null)
487
+ }
488
+ if (this.draftOn === on) {
489
+ this.draftOn = null
490
+ this.keptOn = false
491
+ }
492
+ if (this.target !== on) this.rect = null
493
+ }
494
+
495
+ /** a rectangle on a view of the newest version, which becomes the active one; on a clip it keeps the frame's time */
496
+ addRect(r: { x: number; y: number; w: number; h: number }, side: Side | undefined, on: number): void {
497
+ if (on !== this.view) this.setView(on)
498
+ const view = on > 0 ? { view: on } : {}
499
+ const clip = this.clipKey ? this.clipOf(this.target ?? '', on) : null
500
+ const t = clip ? { t: Math.round(clip.time * 1000) / 1000 } : {}
501
+ this.edit((d) => ({ ...d, rects: [...d.rects, { ...r, comment: '', ...view, ...(side ? { side } : {}), ...t }] }))
502
+ this.rect = this.draft.rects.length - 1
503
+ this.noteFocus = this.rect
504
+ }
505
+
506
+ /** a rectangle picked: its view becomes the active one, and on a clip its frame shows, paused; `focus` (a click on it
507
+ * on the image) puts the cursor in its note box */
508
+ pickRect(i: number | null, focus = false): void {
509
+ this.rect = i
510
+ this.noteFocus = focus ? i : null
511
+ if (i === null) return
512
+ const r = this.draft.rects[i]
513
+ this.view = r?.view ?? 0
514
+ if (r?.t === undefined || !this.clipKey) return
515
+ this.clipOf(this.target ?? '', this.view).seek(r.t)
516
+ }
517
+
518
+ noteFocused(): void {
519
+ this.noteFocus = null
520
+ }
521
+
522
+ setRectComment(i: number, comment: string): void {
523
+ this.edit((d) => ({ ...d, rects: d.rects.map((r, j) => (j === i ? { ...r, comment } : r)) }))
524
+ }
525
+
526
+ removeRect(i: number): void {
527
+ this.edit((d) => ({ ...d, rects: d.rects.filter((_, j) => j !== i) }))
528
+ this.rect = null
529
+ this.noteFocus = null
530
+ }
531
+
532
+ reactionOf(view: number, tile?: number): ReviewReaction | null {
533
+ return (this.draft.reactions ?? []).find((r) => sameSpot(r, view, tile)) ?? null
534
+ }
535
+
536
+ /** a reaction's toggle: sets that status, or clears it when it is already the one */
537
+ react(view: number, tile: number | undefined, status: ReviewStatus): void {
538
+ const cur = this.reactionOf(view, tile)
539
+ this.putReaction(view, tile, { ...cur, status: cur?.status === status ? undefined : status, comment: cur?.comment ?? '' })
540
+ }
541
+
542
+ setReactionComment(view: number, tile: number | undefined, comment: string): void {
543
+ this.putReaction(view, tile, { ...this.reactionOf(view, tile), comment })
544
+ }
545
+
546
+ /** an option's stars; the same number again clears them */
547
+ setStars(view: number, n: number): void {
548
+ const cur = this.reactionOf(view)
549
+ this.putReaction(view, undefined, { ...cur, comment: cur?.comment ?? '', stars: cur?.stars === n ? undefined : n })
550
+ }
551
+
552
+ removeReaction(view: number, tile: number | undefined): void {
553
+ this.putReaction(view, tile, { comment: '' })
554
+ }
555
+
556
+ private putReaction(view: number, tile: number | undefined, r: { status?: ReviewStatus | undefined; comment: string; stars?: number | undefined }): void {
557
+ const next: ReviewReaction = { view, ...(tile !== undefined ? { tile } : {}), ...(r.status ? { status: r.status } : {}), comment: r.comment, ...(r.stars ? { stars: r.stars } : {}) }
558
+ const empty = !r.status && r.comment === '' && !r.stars
559
+ this.edit((d) => {
560
+ const rest = (d.reactions ?? []).filter((q) => !sameSpot(q, view, tile))
561
+ return { ...d, reactions: empty ? rest : [...rest, next] }
562
+ })
563
+ }
564
+
565
+ /** the reactions that go with the verdict, in the card's order */
566
+ get outgoingReactions(): ReviewReaction[] {
567
+ return [...(this.draft.reactions ?? [])].sort((a, b) => a.view - b.view || (a.tile ?? -1) - (b.tile ?? -1))
568
+ }
569
+
570
+ /** « pick »: that option is his answer, sent at once as an approval; his stars and words go with it */
571
+ async choose(view: number): Promise<void> {
572
+ const h = this.head
573
+ if (h?.kind !== 'version' || !isChoice(h.item)) return
574
+ this.edit((d) => ({ ...d, pick: view }))
575
+ await this.submit('approved')
576
+ }
577
+
578
+ // ── the views of a version ──
579
+
580
+ setView(i: number): void {
581
+ this.view = i
582
+ this.rect = null
583
+ }
584
+
585
+ zoomOf(id: string, i: number): Zoom {
586
+ return this.viewZoom[viewKey(id, i)] ?? this.rv.zoom
587
+ }
588
+
589
+ setViewZoom(id: string, i: number, z: Zoom): void {
590
+ this.viewZoom = { ...this.viewZoom, [viewKey(id, i)]: z }
591
+ }
592
+
593
+ setFrame(f: number | null): void {
594
+ this.frame = f
595
+ }
596
+
597
+ toggleTile(id: string, view: number, tile: number): void {
598
+ const k = `${viewKey(id, view)}/${tile}`
599
+ this.bigTile = this.bigTile === k ? null : k
600
+ }
601
+
602
+ /** a version as thin option rows: a choice, or views that each play alone, unless he asked them full */
603
+ rows(item: Item): boolean {
604
+ return asOptions(item) && this.full[item.id] !== true
605
+ }
606
+
607
+ setFull(id: string, on: boolean): void {
608
+ this.full = { ...this.full, [id]: on }
609
+ }
610
+
611
+ /** an option row shows its full view under it: from the start for an image, a pair or a clip, never for a sound */
612
+ rowOpen(item: Item, i: number): boolean {
613
+ const own = this.openRows[viewKey(item.id, i)]
614
+ if (own !== undefined) return own
615
+ const v = item.views[i]
616
+ return v !== undefined && (isGallery(v) || v.audio === undefined)
617
+ }
618
+
619
+ toggleRow(item: Item, i: number): void {
620
+ this.openRows = { ...this.openRows, [viewKey(item.id, i)]: !this.rowOpen(item, i) }
621
+ }
622
+
623
+ /** the clock of a clip or sound view of a version, made on first use: the newest version's first clip loops on its
624
+ * own, every other one waits on its first frame */
625
+ clipOf(id: string, view: number): ClipSt {
626
+ const k = viewKey(id, view)
627
+ let c = this.clips.get(k)
628
+ if (!c) {
629
+ c = new ClipSt()
630
+ const item = (this.cells.find((x) => x.kind === 'version' && x.id === id) as VersionCell | undefined)?.item
631
+ const views = item?.views ?? []
632
+ const v = views[view]
633
+ const media = v && !isGallery(v) ? v : undefined
634
+ const first = views.findIndex((w) => !isGallery(w) && w.clip !== undefined)
635
+ const still = id !== this.target || (item !== undefined && this.rows(item)) || view !== first
636
+ if (media?.audio) c.load(k, media.audio.duration, SOUND_FPS, true)
637
+ else c.load(k, media?.clip?.duration ?? 0, media?.clip?.fps ?? 20, still)
638
+ this.clips.set(k, c)
639
+ }
640
+ return c
641
+ }
642
+
643
+ /** the newest version's active view when it plays (a clip, or a sound on a row); empty when it shows images */
644
+ get clipKey(): string {
645
+ const h = this.head
646
+ if (h?.kind !== 'version') return ''
647
+ const v = h.item.views[this.view]
648
+ if (!v || isGallery(v)) return ''
649
+ return v.clip || (v.audio && this.rows(h.item) && !isPair(v.files)) ? viewKey(h.id, this.view) : ''
650
+ }
651
+
652
+ get clip(): ClipSt | null {
653
+ return this.clipKey ? this.clipOf(this.target ?? '', this.view) : null
654
+ }
655
+
656
+ get openView(): MediaView | null {
657
+ const v = this.headItem?.views[this.view]
658
+ return v && !isGallery(v) ? v : null
659
+ }
660
+
661
+ /** a row's ▶: that option plays with its sound, the one playing before it stops; again, it pauses */
662
+ listen(id: string, i: number): void {
663
+ if (id === this.target) this.setView(i)
664
+ const c = this.clipOf(id, i)
665
+ if (c.paused) c.listen()
666
+ else c.pause()
667
+ }
668
+
669
+ // ── what he sends ──
670
+
671
+ /** V, F, R, A: the draft goes to the newest version as the owner's verdict */
672
+ async submit(status: ReviewStatus): Promise<void> {
673
+ const h = this.head
674
+ if (!h || this.busy) return
675
+ if (h.kind !== 'version') {
676
+ this.error = 'this item was raised, not shown by an agent: a word on it goes in a reply'
677
+ return
678
+ }
679
+ if (h.item.wip) {
680
+ this.error = 'a draft card: the verdict comes once its agent makes it ready; a word goes in a reply'
681
+ return
682
+ }
683
+ const d = this.draft
684
+ this.busy = true
685
+ this.error = null
686
+ try {
687
+ const pick = isChoice(h.item) && isApproved(status) && d.pick !== undefined ? { pick: d.pick } : {}
688
+ await postJson(this.rv.url(`/api/review/${h.id}/feedback`), { status, comment: d.comment, rects: d.rects, reactions: d.reactions ?? [], ...pick })
689
+ runInAction(() => this.settle(h.id, d))
690
+ await this.rv.answered()
691
+ } catch (e) {
692
+ runInAction(() => (this.error = (e as Error).message))
693
+ } finally {
694
+ runInAction(() => (this.busy = false))
695
+ }
696
+ }
697
+
698
+ /** ⌘Enter or « reply »: his word goes to the thread's head as a reply; his marks stay in the draft */
699
+ async sendReply(): Promise<void> {
700
+ const h = this.target
701
+ const sent = this.draft.comment
702
+ const text = sent.trim()
703
+ if (!h || !text || this.busy) return
704
+ this.busy = true
705
+ this.error = null
706
+ try {
707
+ await postJson(this.rv.url(`/api/review/${h}/reply`), { text })
708
+ // only the word sent leaves: a word typed while it was on its way stays
709
+ runInAction(() => {
710
+ const now = this.drafts[h]
711
+ if (now && now.comment === sent) this.put(h, isDirty({ ...now, comment: '' }) ? { ...now, comment: '' } : null)
712
+ })
713
+ await this.rv.answered()
714
+ } catch (e) {
715
+ runInAction(() => (this.error = (e as Error).message))
716
+ } finally {
717
+ runInAction(() => (this.busy = false))
718
+ }
719
+ }
720
+
721
+ /** the agent words he has not read, by cell id: the page sends them read once each shows on his screen */
722
+ get unreadCells(): string[] {
723
+ return this.cells.filter((c) => (c.kind === 'reply' || c.kind === 'note') && c.party === 'agent' && !c.read && c.id.includes('/')).map((c) => c.id)
724
+ }
725
+
726
+ /** these cells showed on his screen, the tab visible: their words go read, each message once, only the ones drawn */
727
+ async seen(cellIds: readonly string[]): Promise<void> {
728
+ const unread = new Set(this.unreadCells)
729
+ const byItem = new Map<string, string[]>()
730
+ for (const id of cellIds) {
731
+ if (!unread.has(id)) continue
732
+ const [item = '', m = ''] = id.split('/')
733
+ if (!m || this.reading.has(m)) continue
734
+ this.reading.add(m)
735
+ byItem.set(item, [...(byItem.get(item) ?? []), m])
736
+ }
737
+ if (byItem.size === 0) return
738
+ try {
739
+ await Promise.all([...byItem].map(([item, of]) => postJson(this.rv.url(`/api/review/${item}/read`), { of })))
740
+ void this.refresh()
741
+ } catch (e) {
742
+ runInAction(() => (this.error = (e as Error).message))
743
+ }
744
+ }
745
+
746
+ /** the keys a card takes (ReviewSt.key routes them): 1 to 9 play an option row of the newest version, ⇧1 to ⇧5
747
+ * score the row playing, P picks it; on a clip Space plays, ← → a frame (a sound: two seconds) */
748
+ key(e: Pick<KeyboardEvent, 'key' | 'shiftKey'> & { code?: string }): boolean {
749
+ const h = this.head
750
+ if (h?.kind !== 'version') return false
751
+ const rows = this.rows(h.item)
752
+ const choice = isChoice(h.item)
753
+ const digit = Number(/^Digit([1-9])$/.exec(e.code ?? '')?.[1] ?? (/^[1-9]$/.test(e.key) ? e.key : 0))
754
+ const clip = this.clip
755
+ const sound = this.openView?.audio !== undefined
756
+ if (rows && digit > 0 && !e.shiftKey) {
757
+ if (digit <= h.item.views.length) this.listen(h.id, digit - 1)
758
+ } else if (choice && rows && digit > 0 && e.shiftKey) {
759
+ if (digit <= STARS) this.setStars(this.view, digit)
760
+ } else if (choice && e.key.toLowerCase() === 'p') void this.choose(this.view)
761
+ else if (clip && e.key === ' ') {
762
+ if (clip.paused && rows) clip.listen()
763
+ else clip.toggle()
764
+ } else if (clip && sound && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) clip.jump(clip.time + (e.key === 'ArrowRight' ? 2 : -2))
765
+ else if (clip && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) clip.step(e.key === 'ArrowRight' ? 1 : -1)
766
+ else if ((e.key === 'Delete' || e.key === 'Backspace') && this.rect !== null) this.removeRect(this.rect)
767
+ else return false
768
+ return true
769
+ }
770
+ }