@whity/ui 0.0.0-stage → 0.5.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 (169) hide show
  1. package/README.md +107 -3
  2. package/package.json +192 -6
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +302 -0
  6. package/src/actor-chip.tsx +71 -0
  7. package/src/agent-activity.tsx +163 -0
  8. package/src/agent-collaboration.stories.tsx +156 -0
  9. package/src/agent-run-status.tsx +196 -0
  10. package/src/alert-dialog.stories.tsx +45 -0
  11. package/src/alert-dialog.tsx +147 -0
  12. package/src/alert.stories.tsx +91 -0
  13. package/src/alert.tsx +89 -0
  14. package/src/app-sidebar.stories.tsx +195 -0
  15. package/src/app-sidebar.tsx +500 -0
  16. package/src/approval-queue.tsx +108 -0
  17. package/src/audience-group-picker.stories.tsx +198 -0
  18. package/src/audience-group-picker.tsx +362 -0
  19. package/src/audience-people-picker.stories.tsx +102 -0
  20. package/src/audience-people-picker.tsx +279 -0
  21. package/src/avatar.tsx +83 -0
  22. package/src/badge.stories.tsx +105 -0
  23. package/src/badge.tsx +68 -0
  24. package/src/beta-warning.stories.tsx +79 -0
  25. package/src/beta-warning.tsx +189 -0
  26. package/src/bilingual-input.stories.tsx +82 -0
  27. package/src/bilingual-input.tsx +183 -0
  28. package/src/breadcrumb.stories.tsx +51 -0
  29. package/src/breadcrumb.tsx +90 -0
  30. package/src/button.stories.tsx +87 -0
  31. package/src/button.tsx +118 -0
  32. package/src/card.stories.tsx +423 -0
  33. package/src/card.tsx +180 -0
  34. package/src/chart.stories.tsx +66 -0
  35. package/src/chart.tsx +228 -0
  36. package/src/checkbox.stories.tsx +62 -0
  37. package/src/checkbox.tsx +54 -0
  38. package/src/collapsible.stories.tsx +48 -0
  39. package/src/collapsible.tsx +34 -0
  40. package/src/color-card.stories.tsx +61 -0
  41. package/src/color-card.tsx +270 -0
  42. package/src/color-picker.stories.tsx +65 -0
  43. package/src/color-picker.tsx +425 -0
  44. package/src/command-palette.tsx +306 -0
  45. package/src/copy-block.stories.tsx +38 -0
  46. package/src/copy-block.tsx +85 -0
  47. package/src/data-table.stories.tsx +200 -0
  48. package/src/data-table.tsx +1106 -0
  49. package/src/date-picker.stories.tsx +61 -0
  50. package/src/date-picker.tsx +422 -0
  51. package/src/design-cards.stories.tsx +458 -0
  52. package/src/dialog.stories.tsx +48 -0
  53. package/src/dialog.tsx +166 -0
  54. package/src/documents/barcode-svg.stories.tsx +72 -0
  55. package/src/documents/barcode-svg.tsx +79 -0
  56. package/src/dropdown-menu.stories.tsx +77 -0
  57. package/src/dropdown-menu.tsx +271 -0
  58. package/src/editor/behaviour.ts +279 -0
  59. package/src/editor/block-ids.ts +44 -0
  60. package/src/editor/block-list.tsx +101 -0
  61. package/src/editor/block-toolbar.tsx +477 -0
  62. package/src/editor/bubble.tsx +93 -0
  63. package/src/editor/catalogue.ts +103 -0
  64. package/src/editor/collab-rail.tsx +746 -0
  65. package/src/editor/collab.stories.tsx +207 -0
  66. package/src/editor/collab.ts +87 -0
  67. package/src/editor/contract.ts +408 -0
  68. package/src/editor/convert.ts +362 -0
  69. package/src/editor/doc-editor.stories.tsx +98 -0
  70. package/src/editor/doc-editor.tsx +1287 -0
  71. package/src/editor/editor.css +536 -0
  72. package/src/editor/extensions.ts +86 -0
  73. package/src/editor/field-picker.tsx +107 -0
  74. package/src/editor/fields.ts +100 -0
  75. package/src/editor/gutter.tsx +367 -0
  76. package/src/editor/index.ts +22 -0
  77. package/src/editor/label-sheet.tsx +289 -0
  78. package/src/editor/labels.ts +310 -0
  79. package/src/editor/link-tools.tsx +141 -0
  80. package/src/editor/node-views.tsx +450 -0
  81. package/src/editor/page-view.tsx +353 -0
  82. package/src/editor/publish-check.tsx +182 -0
  83. package/src/editor/rich-blocks.stories.tsx +146 -0
  84. package/src/editor/sample.ts +40 -0
  85. package/src/editor/schema-rich.ts +150 -0
  86. package/src/editor/schema.ts +315 -0
  87. package/src/editor/services.tsx +127 -0
  88. package/src/editor/slash.ts +64 -0
  89. package/src/editor/suggesting.ts +372 -0
  90. package/src/editor/suggestions.ts +763 -0
  91. package/src/editor/table-keys.ts +66 -0
  92. package/src/editor/templates.stories.tsx +324 -0
  93. package/src/editor/toolbar.tsx +358 -0
  94. package/src/empty-state.stories.tsx +51 -0
  95. package/src/empty-state.tsx +100 -0
  96. package/src/empty-state.usage-notes.md +30 -0
  97. package/src/form.stories.tsx +112 -0
  98. package/src/form.tsx +176 -0
  99. package/src/globals.css +20 -0
  100. package/src/icon-button.tsx +85 -0
  101. package/src/icon-map.ts +244 -0
  102. package/src/icon.tsx +41 -0
  103. package/src/index.ts +67 -0
  104. package/src/input.stories.tsx +157 -0
  105. package/src/input.tsx +759 -0
  106. package/src/locked-screen.stories.tsx +29 -0
  107. package/src/locked-screen.tsx +61 -0
  108. package/src/mark.tsx +62 -0
  109. package/src/math-text.stories.tsx +33 -0
  110. package/src/math-text.tsx +43 -0
  111. package/src/menu-bar.stories.tsx +198 -0
  112. package/src/menu-bar.tsx +373 -0
  113. package/src/money/currency.ts +230 -0
  114. package/src/page-header.stories.tsx +95 -0
  115. package/src/page-header.tsx +122 -0
  116. package/src/page-shell.stories.tsx +42 -0
  117. package/src/page-shell.tsx +32 -0
  118. package/src/pagination.stories.tsx +45 -0
  119. package/src/pagination.tsx +98 -0
  120. package/src/plugin-card.stories.tsx +180 -0
  121. package/src/plugin-card.tsx +848 -0
  122. package/src/popover.stories.tsx +48 -0
  123. package/src/popover.tsx +55 -0
  124. package/src/radio-group.stories.tsx +26 -0
  125. package/src/radio-group.tsx +44 -0
  126. package/src/route-flow/editor.tsx +1014 -0
  127. package/src/route-flow/model.ts +716 -0
  128. package/src/scope-grant.tsx +139 -0
  129. package/src/screen-too-small.stories.tsx +61 -0
  130. package/src/screen-too-small.tsx +104 -0
  131. package/src/select.stories.tsx +44 -0
  132. package/src/select.tsx +197 -0
  133. package/src/separator.stories.tsx +34 -0
  134. package/src/separator.tsx +34 -0
  135. package/src/sheet.stories.tsx +49 -0
  136. package/src/sheet.tsx +168 -0
  137. package/src/skeleton.stories.tsx +28 -0
  138. package/src/skeleton.tsx +19 -0
  139. package/src/slider.stories.tsx +78 -0
  140. package/src/slider.tsx +300 -0
  141. package/src/spinner.stories.tsx +33 -0
  142. package/src/spinner.tsx +55 -0
  143. package/src/switch.stories.tsx +42 -0
  144. package/src/switch.tsx +41 -0
  145. package/src/switcher.stories.tsx +111 -0
  146. package/src/switcher.tsx +131 -0
  147. package/src/table.stories.tsx +48 -0
  148. package/src/table.tsx +121 -0
  149. package/src/tabs.stories.tsx +74 -0
  150. package/src/tabs.tsx +90 -0
  151. package/src/tag-input.stories.tsx +67 -0
  152. package/src/tag-input.tsx +117 -0
  153. package/src/tenant-logo.tsx +63 -0
  154. package/src/tenant-switcher.stories.tsx +38 -0
  155. package/src/tenant-switcher.tsx +164 -0
  156. package/src/textarea.stories.tsx +27 -0
  157. package/src/textarea.tsx +18 -0
  158. package/src/theme-mode.ts +52 -0
  159. package/src/time-picker.stories.tsx +62 -0
  160. package/src/time-picker.tsx +615 -0
  161. package/src/toggle-group.tsx +138 -0
  162. package/src/tooltip.stories.tsx +43 -0
  163. package/src/tooltip.tsx +73 -0
  164. package/src/top-nav.stories.tsx +58 -0
  165. package/src/top-nav.tsx +324 -0
  166. package/src/undo-bar.tsx +107 -0
  167. package/src/utils.ts +45 -0
  168. package/src/view-toggle.stories.tsx +84 -0
  169. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,746 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { ActorChip } from "../actor-chip"
6
+ import { Avatar } from "../avatar"
7
+ import { Button } from "../button"
8
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "../dropdown-menu"
9
+ import { Icon } from "../icon"
10
+ import { IconButton } from "../icon-button"
11
+ import { Sheet, SheetContent, SheetTitle } from "../sheet"
12
+ import { ToggleGroup } from "../toggle-group"
13
+ import { cn } from "../utils"
14
+ import type { Decision, DecideAllFilter, MentionPerson, RailSuggestion, RailThread } from "./collab"
15
+ import type { Actor, Inline } from "./contract"
16
+ import { fill, type EditorLabels } from "./labels"
17
+ import type { SuggestionPatch } from "./suggestions"
18
+
19
+ /**
20
+ * The margin rail (E.6, the EditorCollab card): one card per open suggestion
21
+ * and thread, beside its text and stacked without overlapping; the header
22
+ * counts them and offers the All menu (E.29). Under 1024px the same cards go
23
+ * in a drawer with All, Comments, Suggestions and Resolved. Classes follow the
24
+ * card (`.wy-rc`, `.wy-edx__railhead`, `editor.css`).
25
+ */
26
+
27
+ export type RailItem =
28
+ | {
29
+ kind: "suggestion"
30
+ id: string
31
+ suggestion: RailSuggestion
32
+ pending?: boolean
33
+ unplaced?: boolean
34
+ }
35
+ | { kind: "thread"; id: string; thread: RailThread }
36
+ | { kind: "composer"; id: "composer"; quote: string }
37
+
38
+ export interface RailActions {
39
+ canEdit: boolean
40
+ canComment: boolean
41
+ onDecide?: (id: string, decision: Decision) => void
42
+ onDecideAll?: (decision: Decision, filter?: DecideAllFilter) => void
43
+ onReply?: (threadId: string, body: Inline[], mentions: string[]) => Promise<void>
44
+ onResolve?: (threadId: string) => void
45
+ onReopen?: (threadId: string) => void
46
+ onComment?: (body: Inline[], mentions: string[]) => Promise<void>
47
+ onCancelComment?: () => void
48
+ searchPeople?: (query: string) => Promise<MentionPerson[]>
49
+ }
50
+
51
+ /** Whether the rail fits beside the sheet: 1024px and up (E.6); below, the drawer. */
52
+ export function useWideRail(): boolean {
53
+ const query = "(min-width: 1024px)"
54
+ const [wide, setWide] = React.useState(() =>
55
+ typeof window === "undefined" || typeof window.matchMedia !== "function" ? true : window.matchMedia(query).matches
56
+ )
57
+ React.useEffect(() => {
58
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return
59
+ const mq = window.matchMedia(query)
60
+ const on = () => setWide(mq.matches)
61
+ on()
62
+ mq.addEventListener("change", on)
63
+ return () => mq.removeEventListener("change", on)
64
+ }, [])
65
+ return wide
66
+ }
67
+
68
+ /** 24-hour time in Western digits (stage 5). */
69
+ export function railTime(iso: string): string {
70
+ const d = new Date(iso)
71
+ if (Number.isNaN(d.getTime())) return ""
72
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
73
+ }
74
+
75
+ const actorName = (a: Actor) => (a.kind === "system" ? "Whity" : a.name)
76
+
77
+ /** The card's sentence, with the quoted text bold ("Replace **30 days** with **14 days**"). */
78
+ export function summaryNode(patch: SuggestionPatch, labels: EditorLabels, fallback: string): React.ReactNode {
79
+ const quote = (t: string) => `“${t.length > 60 ? `${t.slice(0, 59)}…` : t}”`
80
+ const text = (content: Inline[]) => content.map((r) => (r.type === "text" ? r.text : r.type === "break" ? " " : "…")).join("")
81
+ const blockText = (b: { content?: Inline[]; type: string }) => (Array.isArray(b.content) ? text(b.content) : "")
82
+ const parts = (template: string, values: Record<string, string>) =>
83
+ template.split(/(\{\w+\})/).map((part, i) => {
84
+ const key = /^\{(\w+)\}$/.exec(part)?.[1]
85
+ if (!key) return part
86
+ return key === "mark" ? <React.Fragment key={i}>{values[key]}</React.Fragment> : <b key={i}>{values[key]}</b>
87
+ })
88
+ switch (patch.op) {
89
+ case "replace-text": {
90
+ const ins = text(patch.insert)
91
+ if (patch.deleteText && ins) return parts(labels.sugReplace, { from: patch.deleteText, to: ins })
92
+ if (patch.deleteText) return parts(labels.sugDelete, { text: quote(patch.deleteText) })
93
+ return parts(labels.sugAdd, { text: quote(ins) })
94
+ }
95
+ case "format": {
96
+ const markLabel = (labels as Record<string, string>)[patch.mark.type] ?? patch.mark.type
97
+ return parts(patch.add ? labels.sugFormat : labels.sugUnformat, {
98
+ text: quote(patch.text),
99
+ mark: markLabel.toLowerCase(),
100
+ })
101
+ }
102
+ case "insert-blocks": {
103
+ const t = patch.blocks.map(blockText).join(" ").trim()
104
+ return parts(labels.sugAddBlocks, {
105
+ text: t ? quote(t) : labels.sugBlock,
106
+ })
107
+ }
108
+ case "delete-blocks":
109
+ return fallback || parts(labels.sugDeleteBlocks, { text: labels.sugBlock })
110
+ case "move-block":
111
+ return parts(labels.sugMoveBlock, { text: labels.sugBlock })
112
+ }
113
+ }
114
+
115
+ function Who({ by, at, labels, mine }: { by: Actor; at?: string; labels: EditorLabels; mine?: boolean }) {
116
+ if (by.kind === "agent")
117
+ return <ActorChip kind="agent" name={by.name} onBehalfOf={by.onBehalfOf.name} labels={{ for: labels.actorFor }} />
118
+ const name = mine ? labels.you : actorName(by)
119
+ return (
120
+ <>
121
+ <Avatar name={actorName(by) || name} size={24} kind={by.kind === "system" ? "system" : "person"} />
122
+ <span className="wy-rc__name">{name}</span>
123
+ {at !== undefined && <span className="wy-rc__time">{at}</span>}
124
+ </>
125
+ )
126
+ }
127
+
128
+ function plain(body: Inline[]): string {
129
+ return body.map((r) => (r.type === "text" ? r.text : r.type === "break" ? "\n" : "")).join("")
130
+ }
131
+
132
+ /** Message text with its @mentions on the tint. */
133
+ function MessageBody({ body, mentions }: { body: Inline[]; mentions: Actor[] }) {
134
+ const text = plain(body)
135
+ const names = mentions.map((m) => `@${actorName(m)}`).filter((n) => n.length > 1)
136
+ if (!names.length) return <div className="whitespace-pre-wrap">{text}</div>
137
+ const re = new RegExp(`(${names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "g")
138
+ return (
139
+ <div className="whitespace-pre-wrap">
140
+ {text.split(re).map((part, i) =>
141
+ names.includes(part) ? (
142
+ <span key={i} className="wy-mention">
143
+ {part}
144
+ </span>
145
+ ) : (
146
+ part
147
+ )
148
+ )}
149
+ </div>
150
+ )
151
+ }
152
+
153
+ /* ------------------------------------------------------------ The @ box */
154
+
155
+ /** A text box that offers workspace people after @, as the card's mention picker. */
156
+ function MentionBox({
157
+ placeholder,
158
+ search,
159
+ labels,
160
+ onSubmit,
161
+ onCancel,
162
+ submitLabel,
163
+ autoFocus,
164
+ }: {
165
+ placeholder: string
166
+ search?: (q: string) => Promise<MentionPerson[]>
167
+ labels: EditorLabels
168
+ onSubmit: (body: Inline[], mentions: string[]) => Promise<void>
169
+ onCancel?: () => void
170
+ submitLabel: string
171
+ autoFocus?: boolean
172
+ }) {
173
+ const [value, setValue] = React.useState("")
174
+ const [query, setQuery] = React.useState<string | null>(null)
175
+ const [people, setPeople] = React.useState<MentionPerson[]>([])
176
+ // The query the shown list answers, so "No one matches" never shows while a search is on its way.
177
+ const [answered, setAnswered] = React.useState<string | null>(null)
178
+ const [active, setActive] = React.useState(0)
179
+ const [picked, setPicked] = React.useState<MentionPerson[]>([])
180
+ const [busy, setBusy] = React.useState(false)
181
+ const [failed, setFailed] = React.useState(false)
182
+ const box = React.useRef<HTMLTextAreaElement>(null)
183
+ // The new comment's box takes the focus from the editor once the card is placed.
184
+ React.useEffect(() => {
185
+ if (!autoFocus) return
186
+ const frame = requestAnimationFrame(() => box.current?.focus())
187
+ return () => cancelAnimationFrame(frame)
188
+ }, [autoFocus])
189
+
190
+ React.useEffect(() => {
191
+ // An empty query is never sent (the server refuses it): the hint shows until a name is typed.
192
+ if (!query || !search) {
193
+ setPeople([])
194
+ setAnswered(null)
195
+ return
196
+ }
197
+ let live = true
198
+ const timer = setTimeout(() => {
199
+ search(query).then(
200
+ (list) => live && (setPeople(list.slice(0, 8)), setActive(0), setAnswered(query)),
201
+ () => live && (setPeople([]), setAnswered(query))
202
+ )
203
+ }, 200)
204
+ return () => {
205
+ live = false
206
+ clearTimeout(timer)
207
+ }
208
+ }, [query, search])
209
+
210
+ const update = (next: string, caret: number) => {
211
+ setValue(next)
212
+ setFailed(false)
213
+ const m = /(?:^|\s)@([^\s@]{0,30})$/.exec(next.slice(0, caret))
214
+ setQuery(m ? m[1] : null)
215
+ }
216
+ const pick = (person: MentionPerson) => {
217
+ const el = box.current
218
+ const caret = el?.selectionStart ?? value.length
219
+ const before = value.slice(0, caret).replace(/@([^\s@]{0,30})$/, `@${person.name} `)
220
+ setValue(before + value.slice(caret))
221
+ setPicked((p) => (p.some((x) => x.id === person.id) ? p : [...p, person]))
222
+ setQuery(null)
223
+ requestAnimationFrame(() => {
224
+ el?.focus()
225
+ el?.setSelectionRange(before.length, before.length)
226
+ })
227
+ }
228
+ const submit = async () => {
229
+ const text = value.trim()
230
+ if (!text || busy) return
231
+ setBusy(true)
232
+ try {
233
+ const mentions = picked.filter((p) => text.includes(`@${p.name}`)).map((p) => p.id)
234
+ await onSubmit([{ type: "text", text }], mentions)
235
+ setValue("")
236
+ setPicked([])
237
+ } catch {
238
+ setFailed(true)
239
+ } finally {
240
+ setBusy(false)
241
+ }
242
+ }
243
+ const open = query !== null && !!search
244
+
245
+ return (
246
+ <div className="grid gap-2">
247
+ <div className="relative">
248
+ <textarea
249
+ ref={box}
250
+ autoFocus={autoFocus}
251
+ value={value}
252
+ placeholder={placeholder}
253
+ aria-label={placeholder}
254
+ rows={2}
255
+ onChange={(e) => update(e.target.value, e.target.selectionStart)}
256
+ onKeyDown={(e) => {
257
+ if (open && people.length) {
258
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
259
+ e.preventDefault()
260
+ setActive((i) => (i + (e.key === "ArrowDown" ? 1 : people.length - 1)) % people.length)
261
+ return
262
+ }
263
+ if (e.key === "Enter") {
264
+ e.preventDefault()
265
+ pick(people[active])
266
+ return
267
+ }
268
+ }
269
+ if (e.key === "Escape") {
270
+ if (open) setQuery(null)
271
+ else onCancel?.()
272
+ return
273
+ }
274
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
275
+ e.preventDefault()
276
+ void submit()
277
+ }
278
+ }}
279
+ className="wy-rc__box resize-none bg-transparent outline-none placeholder:text-muted-foreground focus-visible:border-ring"
280
+ />
281
+ {open && (
282
+ <div
283
+ role="listbox"
284
+ aria-label={labels.mentionPeople}
285
+ className="wy-mentionpop absolute inset-x-0 top-full z-30 mt-1 rounded-lg border border-border bg-popover text-popover-foreground shadow-float"
286
+ >
287
+ <div className="px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground">{labels.mentionPeople}</div>
288
+ {!query && <div className="px-2 py-2 text-muted-foreground">{labels.mentionHint}</div>}
289
+ {query && answered === query && people.length === 0 && <div className="px-2 py-2 text-muted-foreground">{labels.mentionNone}</div>}
290
+ {people.map((person, i) => (
291
+ <div
292
+ key={person.id}
293
+ role="option"
294
+ aria-selected={i === active}
295
+ onMouseDown={(e) => e.preventDefault()}
296
+ onMouseEnter={() => setActive(i)}
297
+ onClick={() => pick(person)}
298
+ className={cn("flex cursor-pointer items-center gap-2 rounded-[6px] px-2 py-1.5", i === active && "bg-muted")}
299
+ >
300
+ <Avatar name={person.name} size={20} />
301
+ <span className="truncate">{person.name}</span>
302
+ {person.detail && <span className="ms-auto truncate text-xs text-muted-foreground">{person.detail}</span>}
303
+ </div>
304
+ ))}
305
+ </div>
306
+ )}
307
+ </div>
308
+ {failed && (
309
+ <p role="alert" className="m-0 text-xs text-error-text">
310
+ {labels.collabFailed}
311
+ </p>
312
+ )}
313
+ <div className="wy-rc__foot">
314
+ {onCancel && (
315
+ <Button variant="ghost" size="sm" onClick={onCancel}>
316
+ {labels.cancel}
317
+ </Button>
318
+ )}
319
+ <Button variant="outline" size="sm" disabled={!value.trim() || busy} onClick={() => void submit()}>
320
+ {submitLabel}
321
+ </Button>
322
+ </div>
323
+ </div>
324
+ )
325
+ }
326
+
327
+ /* ----------------------------------------------------------------- Cards */
328
+
329
+ interface CardProps {
330
+ item: RailItem
331
+ labels: EditorLabels
332
+ actions: RailActions
333
+ active: boolean
334
+ meId?: string
335
+ onActivate: () => void
336
+ /** Rail cards are positioned; drawer cards sit in a list. */
337
+ positioned?: { top: number }
338
+ cardRef?: (el: HTMLDivElement | null) => void
339
+ }
340
+
341
+ function Card({ item, labels, actions, active, meId, onActivate, positioned, cardRef }: CardProps) {
342
+ const common = {
343
+ ref: cardRef,
344
+ "data-rail-id": item.id,
345
+ style: positioned ? { top: positioned.top } : undefined,
346
+ onClick: (e: React.MouseEvent) => {
347
+ if ((e.target as HTMLElement).closest("button,textarea,a,[role=option]")) return
348
+ onActivate()
349
+ },
350
+ }
351
+ const base = cn("wy-rc", !positioned && "wy-rc--static", active && "is-active")
352
+
353
+ if (item.kind === "composer") {
354
+ return (
355
+ <div {...common} className={cn(base, "is-active")} role="group" aria-label={labels.comment}>
356
+ <div className="wy-rc__who">
357
+ <span className="wy-rc__name">{labels.you}</span>
358
+ <span className="wy-rc__time">{labels.now}</span>
359
+ </div>
360
+ {item.quote && <div className="wy-rc__q">{item.quote}</div>}
361
+ <MentionBox
362
+ autoFocus
363
+ placeholder={labels.commentPlaceholder}
364
+ labels={labels}
365
+ search={actions.searchPeople}
366
+ submitLabel={labels.comment}
367
+ onSubmit={(body, mentions) => actions.onComment?.(body, mentions) ?? Promise.resolve()}
368
+ onCancel={actions.onCancelComment}
369
+ />
370
+ </div>
371
+ )
372
+ }
373
+
374
+ if (item.kind === "suggestion") {
375
+ const s = item.suggestion
376
+ const isAgent = s.by.kind === "agent"
377
+ const mine = !!meId && s.by.kind === "person" && s.by.id === meId
378
+ return (
379
+ <div {...common} className={cn(base, isAgent && "is-agent", item.pending && "is-pending")} role="group" aria-label={s.summary}>
380
+ <div className="wy-rc__who">
381
+ <Who by={s.by} at={item.pending ? labels.sugSending : railTime(s.at)} labels={labels} mine={mine} />
382
+ {actions.canEdit && !item.pending && (
383
+ <span className="wy-rc__acts">
384
+ <IconButton icon="check" label={labels.accept} size="sm" onClick={() => actions.onDecide?.(s.id, "accepted")} />
385
+ <IconButton icon="close" label={labels.reject} size="sm" onClick={() => actions.onDecide?.(s.id, "rejected")} />
386
+ </span>
387
+ )}
388
+ </div>
389
+ <div className="wy-rc__what">{summaryNode(s.patch, labels, s.summary)}</div>
390
+ {item.unplaced && <div className="wy-rc__time">{labels.sugUnplaced}</div>}
391
+ </div>
392
+ )
393
+ }
394
+
395
+ const t = item.thread
396
+ const [first, ...rest] = t.messages
397
+ if (t.resolved) {
398
+ return (
399
+ <div {...common} className={cn(base, "is-resolved")} role="group">
400
+ <div className="wy-rc__resolved">
401
+ <Icon name="success" size={14} />
402
+ {fill(labels.resolvedBy, {
403
+ name: actorName(t.resolved.by),
404
+ time: railTime(t.resolved.at),
405
+ })}
406
+ </div>
407
+ <div className="wy-rc__what">{first ? plain(first.body) : t.quote}</div>
408
+ {actions.canComment && actions.onReopen && (
409
+ <div>
410
+ <Button variant="ghost" size="sm" onClick={() => actions.onReopen?.(t.id)}>
411
+ {labels.reopen}
412
+ </Button>
413
+ </div>
414
+ )}
415
+ </div>
416
+ )
417
+ }
418
+ return (
419
+ <div {...common} className={base} role="group" aria-label={t.quote}>
420
+ {first && (
421
+ <div className="wy-rc__who">
422
+ <Who by={first.by} at={railTime(first.at)} labels={labels} mine={!!meId && first.by.kind === "person" && first.by.id === meId} />
423
+ {actions.canComment && actions.onResolve && (
424
+ <span className="wy-rc__acts">
425
+ <IconButton icon="check" label={labels.resolve} size="sm" onClick={() => actions.onResolve?.(t.id)} />
426
+ </span>
427
+ )}
428
+ </div>
429
+ )}
430
+ {!positioned && t.quote && <div className="wy-rc__q">{t.quote}</div>}
431
+ {first && <MessageBody body={first.body} mentions={first.mentions} />}
432
+ {rest.length > 0 &&
433
+ (active || positioned ? (
434
+ <div className="wy-rc__replies">
435
+ {rest.map((m) => (
436
+ <div key={m.id}>
437
+ <div className="wy-rc__who">
438
+ <Who by={m.by} at={railTime(m.at)} labels={labels} mine={!!meId && m.by.kind === "person" && m.by.id === meId} />
439
+ </div>
440
+ <div className="mt-1">
441
+ <MessageBody body={m.body} mentions={m.mentions} />
442
+ </div>
443
+ </div>
444
+ ))}
445
+ </div>
446
+ ) : (
447
+ <div className="wy-rc__time">{rest.length === 1 ? labels.oneReply : fill(labels.replies, { n: rest.length })}</div>
448
+ ))}
449
+ {actions.canComment &&
450
+ actions.onReply &&
451
+ (active ? (
452
+ <MentionBox
453
+ placeholder={labels.replyPlaceholder}
454
+ labels={labels}
455
+ search={actions.searchPeople}
456
+ submitLabel={labels.reply}
457
+ onSubmit={(body, mentions) => actions.onReply!(t.id, body, mentions)}
458
+ />
459
+ ) : (
460
+ positioned && (
461
+ <button type="button" className="wy-rc__reply text-start" onClick={onActivate}>
462
+ {labels.replyPlaceholder}
463
+ </button>
464
+ )
465
+ ))}
466
+ </div>
467
+ )
468
+ }
469
+
470
+ /* -------------------------------------------------------------- Header */
471
+
472
+ function counts(items: RailItem[], labels: EditorLabels) {
473
+ const s = items.filter((i) => i.kind === "suggestion").length
474
+ const c = items.filter((i) => i.kind === "thread" && !i.thread.resolved).length
475
+ const parts: string[] = []
476
+ if (s) parts.push(s === 1 ? labels.countSuggestion : fill(labels.countSuggestions, { n: s }))
477
+ if (c) parts.push(c === 1 ? labels.countComment : fill(labels.countComments, { n: c }))
478
+ return parts.join(" · ")
479
+ }
480
+
481
+ function AllMenu({ items, labels, actions }: { items: RailItem[]; labels: EditorLabels; actions: RailActions }) {
482
+ const suggestions = items.flatMap((i) => (i.kind === "suggestion" && !i.pending ? [i.suggestion] : []))
483
+ if (!actions.canEdit || !actions.onDecideAll || suggestions.length === 0) return null
484
+ const agents = [...new Map(suggestions.flatMap((s) => (s.by.kind === "agent" ? [[s.by.id, s.by.name] as const] : []))).entries()]
485
+ return (
486
+ <DropdownMenu modal={false}>
487
+ <DropdownMenuTrigger asChild>
488
+ <Button variant="ghost" size="sm" iconEnd="chevron-down">
489
+ {labels.railAll}
490
+ </Button>
491
+ </DropdownMenuTrigger>
492
+ <DropdownMenuContent align="end">
493
+ <DropdownMenuItem onSelect={() => actions.onDecideAll?.("accepted")}>
494
+ <Icon name="check" />
495
+ {labels.acceptAll}
496
+ </DropdownMenuItem>
497
+ <DropdownMenuItem onSelect={() => actions.onDecideAll?.("rejected")}>
498
+ <Icon name="close" />
499
+ {labels.rejectAll}
500
+ </DropdownMenuItem>
501
+ {agents.map(([id, name]) => (
502
+ <React.Fragment key={id}>
503
+ <DropdownMenuSeparator />
504
+ <DropdownMenuItem onSelect={() => actions.onDecideAll?.("accepted", { agent: id })}>
505
+ <Icon name="robot" />
506
+ {fill(labels.acceptAllFrom, { name })}
507
+ </DropdownMenuItem>
508
+ <DropdownMenuItem onSelect={() => actions.onDecideAll?.("rejected", { agent: id })}>
509
+ <Icon name="robot" />
510
+ {fill(labels.rejectAllFrom, { name })}
511
+ </DropdownMenuItem>
512
+ </React.Fragment>
513
+ ))}
514
+ </DropdownMenuContent>
515
+ </DropdownMenu>
516
+ )
517
+ }
518
+
519
+ /* ------------------------------------------------------------------ Rail */
520
+
521
+ const GAP = 10
522
+
523
+ /**
524
+ * Card tops: each as near its text as it can be without overlapping; the
525
+ * active card sits exactly beside its text and the others make room (E.6).
526
+ */
527
+ export function stackCards(want: { id: string; y: number; h: number }[], active: string | null, minTop = 0): Record<string, number> {
528
+ const sorted = [...want].sort((a, b) => a.y - b.y)
529
+ const tops: Record<string, number> = {}
530
+ const pin = sorted.findIndex((c) => c.id === active)
531
+ if (pin < 0) {
532
+ let next = minTop
533
+ for (const c of sorted) {
534
+ tops[c.id] = Math.max(c.y, next)
535
+ next = tops[c.id] + c.h + GAP
536
+ }
537
+ return tops
538
+ }
539
+ tops[sorted[pin].id] = Math.max(sorted[pin].y, minTop)
540
+ let next = tops[sorted[pin].id] + sorted[pin].h + GAP
541
+ for (let i = pin + 1; i < sorted.length; i++) {
542
+ tops[sorted[i].id] = Math.max(sorted[i].y, next)
543
+ next = tops[sorted[i].id] + sorted[i].h + GAP
544
+ }
545
+ let limit = tops[sorted[pin].id] - GAP
546
+ for (let i = pin - 1; i >= 0; i--) {
547
+ tops[sorted[i].id] = Math.min(sorted[i].y, limit - sorted[i].h)
548
+ limit = tops[sorted[i].id] - GAP
549
+ }
550
+ // Pushed above the top: lay them out downwards again from the top.
551
+ const first = sorted[0] && tops[sorted[0].id]
552
+ if (first !== undefined && first < minTop) {
553
+ let n = minTop
554
+ for (const c of sorted) {
555
+ tops[c.id] = Math.max(tops[c.id], n)
556
+ n = tops[c.id] + c.h + GAP
557
+ }
558
+ }
559
+ return tops
560
+ }
561
+
562
+ export function CollabRail({
563
+ items,
564
+ resolved,
565
+ labels,
566
+ actions,
567
+ active,
568
+ onActive,
569
+ anchorTop,
570
+ meId,
571
+ layoutKey,
572
+ defaultShowResolved = false,
573
+ }: {
574
+ items: RailItem[]
575
+ resolved: RailItem[]
576
+ labels: EditorLabels
577
+ actions: RailActions
578
+ active: string | null
579
+ onActive: (id: string | null) => void
580
+ /** Where an item's text is, in viewport pixels (from coordsAtPos), or null. */
581
+ anchorTop: (item: RailItem) => number | null
582
+ meId?: string
583
+ /** Changes whenever the document's layout may have moved. */
584
+ layoutKey: unknown
585
+ /** Start with the resolved threads showing (stories). */
586
+ defaultShowResolved?: boolean
587
+ }) {
588
+ const railRef = React.useRef<HTMLDivElement>(null)
589
+ const headRef = React.useRef<HTMLDivElement>(null)
590
+ const cards = React.useRef(new Map<string, HTMLDivElement>())
591
+ const [tops, setTops] = React.useState<Record<string, number>>({})
592
+ const [showResolved, setShowResolved] = React.useState(defaultShowResolved)
593
+
594
+ const layout = React.useCallback(() => {
595
+ const rail = railRef.current
596
+ if (!rail) return
597
+ const origin = rail.getBoundingClientRect().top
598
+ const head = headRef.current
599
+ const minTop = head ? head.offsetTop + head.offsetHeight + 12 : 0
600
+ const want = items.map((item) => {
601
+ const y = anchorTop(item)
602
+ return {
603
+ id: item.id,
604
+ y: y === null ? minTop : y - origin,
605
+ h: cards.current.get(item.id)?.offsetHeight ?? 96,
606
+ }
607
+ })
608
+ const next = stackCards(want, active, minTop)
609
+ setTops((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next))
610
+ }, [items, anchorTop, active])
611
+
612
+ React.useLayoutEffect(layout, [layout, layoutKey])
613
+ React.useEffect(() => {
614
+ const ro = new ResizeObserver(() => layout())
615
+ if (railRef.current) ro.observe(railRef.current)
616
+ cards.current.forEach((el) => ro.observe(el))
617
+ window.addEventListener("resize", layout)
618
+ return () => {
619
+ ro.disconnect()
620
+ window.removeEventListener("resize", layout)
621
+ }
622
+ }, [layout, items])
623
+
624
+ const bottom = Math.max(0, ...items.map((i) => (tops[i.id] ?? 0) + (cards.current.get(i.id)?.offsetHeight ?? 96)))
625
+
626
+ return (
627
+ <aside ref={railRef} aria-label={labels.commentsAndSuggestions} className="wy-edx__rail" data-slot="collab-rail">
628
+ <div ref={headRef} className="wy-edx__railhead">
629
+ <span>{counts(items, labels) || labels.commentsAndSuggestions}</span>
630
+ <span className="flex items-center gap-1">
631
+ {resolved.length > 0 && (
632
+ <Button variant="ghost" size="sm" aria-pressed={showResolved} onClick={() => setShowResolved((v) => !v)}>
633
+ {fill(labels.countResolved, { n: resolved.length })}
634
+ </Button>
635
+ )}
636
+ <AllMenu items={items} labels={labels} actions={actions} />
637
+ </span>
638
+ </div>
639
+ {items.length === 0 && !showResolved && <p className="wy-edx__railnote">{labels.railEmpty}</p>}
640
+ {items.map((item) => (
641
+ <Card
642
+ key={item.id}
643
+ item={item}
644
+ labels={labels}
645
+ actions={actions}
646
+ active={active === item.id}
647
+ meId={meId}
648
+ onActivate={() => onActive(item.id)}
649
+ positioned={{ top: tops[item.id] ?? 0 }}
650
+ cardRef={(el) => {
651
+ if (el) cards.current.set(item.id, el)
652
+ else cards.current.delete(item.id)
653
+ }}
654
+ />
655
+ ))}
656
+ {showResolved && (
657
+ <div
658
+ className="wy-drawerlist"
659
+ style={{
660
+ marginTop: items.length ? bottom + GAP - (headRef.current ? headRef.current.offsetTop + headRef.current.offsetHeight : 0) : 0,
661
+ }}
662
+ >
663
+ {resolved.map((item) => (
664
+ <Card key={item.id} item={item} labels={labels} actions={actions} active={false} meId={meId} onActivate={() => undefined} />
665
+ ))}
666
+ </div>
667
+ )}
668
+ </aside>
669
+ )
670
+ }
671
+
672
+ /* ---------------------------------------------------------------- Drawer */
673
+
674
+ type Tab = "all" | "comments" | "suggestions" | "resolved"
675
+
676
+ export function CollabDrawer({
677
+ open,
678
+ onOpenChange,
679
+ items,
680
+ resolved,
681
+ labels,
682
+ actions,
683
+ active,
684
+ onActive,
685
+ meId,
686
+ defaultTab = "all",
687
+ }: {
688
+ open: boolean
689
+ onOpenChange: (open: boolean) => void
690
+ items: RailItem[]
691
+ resolved: RailItem[]
692
+ labels: EditorLabels
693
+ actions: RailActions
694
+ active: string | null
695
+ onActive: (id: string | null) => void
696
+ meId?: string
697
+ defaultTab?: Tab
698
+ }) {
699
+ const [tab, setTab] = React.useState<Tab>(defaultTab)
700
+ const shown =
701
+ tab === "resolved"
702
+ ? resolved
703
+ : items.filter((i) => tab === "all" || (tab === "comments" ? i.kind !== "suggestion" : i.kind === "suggestion"))
704
+ return (
705
+ <Sheet open={open} onOpenChange={onOpenChange}>
706
+ <SheetContent
707
+ side="right"
708
+ closeLabel={labels.close}
709
+ className="w-full max-w-[380px] gap-2.5 p-3 text-[0.8125rem]"
710
+ aria-describedby={undefined}
711
+ >
712
+ <div className="flex min-h-8 items-center justify-between pe-8">
713
+ <SheetTitle className="text-sm font-semibold">{labels.commentsAndSuggestions}</SheetTitle>
714
+ <AllMenu items={items} labels={labels} actions={actions} />
715
+ </div>
716
+ <ToggleGroup
717
+ size="sm"
718
+ label={labels.show}
719
+ required
720
+ value={tab}
721
+ onChange={(v) => setTab((v as Tab) ?? "all")}
722
+ options={[
723
+ { value: "all", label: labels.tabAll },
724
+ { value: "comments", label: labels.tabComments },
725
+ { value: "suggestions", label: labels.tabSuggestions },
726
+ { value: "resolved", label: labels.tabResolved },
727
+ ]}
728
+ />
729
+ <div className="wy-drawerlist">
730
+ {shown.length === 0 && <p className="wy-edx__railnote">{tab === "resolved" ? labels.resolvedEmpty : labels.railEmpty}</p>}
731
+ {shown.map((item) => (
732
+ <Card
733
+ key={item.id}
734
+ item={item}
735
+ labels={labels}
736
+ actions={actions}
737
+ active={active === item.id}
738
+ meId={meId}
739
+ onActivate={() => onActive(item.id)}
740
+ />
741
+ ))}
742
+ </div>
743
+ </SheetContent>
744
+ </Sheet>
745
+ )
746
+ }