@estiva-app/ui 0.74.1 → 0.76.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 (87) hide show
  1. package/dist/CardUnder.d.ts +10 -0
  2. package/dist/CardUnder.d.ts.map +1 -0
  3. package/dist/CommentBox.d.ts +119 -0
  4. package/dist/CommentBox.d.ts.map +1 -0
  5. package/dist/ComposeBox.d.ts +2 -0
  6. package/dist/ComposeBox.d.ts.map +1 -1
  7. package/dist/InlineChip.d.ts +2 -0
  8. package/dist/InlineChip.d.ts.map +1 -1
  9. package/dist/LinkCard.d.ts +17 -0
  10. package/dist/LinkCard.d.ts.map +1 -0
  11. package/dist/LinkChip.d.ts +8 -0
  12. package/dist/LinkChip.d.ts.map +1 -0
  13. package/dist/LinkParts.d.ts +45 -0
  14. package/dist/LinkParts.d.ts.map +1 -0
  15. package/dist/LinkPreview.d.ts +21 -0
  16. package/dist/LinkPreview.d.ts.map +1 -0
  17. package/dist/LinkRow.d.ts +24 -0
  18. package/dist/LinkRow.d.ts.map +1 -0
  19. package/dist/PartCard.d.ts +32 -0
  20. package/dist/PartCard.d.ts.map +1 -0
  21. package/dist/ReactionRow.d.ts +44 -0
  22. package/dist/ReactionRow.d.ts.map +1 -0
  23. package/dist/Skeleton.d.ts +12 -2
  24. package/dist/Skeleton.d.ts.map +1 -1
  25. package/dist/editor.d.ts +1 -0
  26. package/dist/editor.d.ts.map +1 -1
  27. package/dist/editor.js +2340 -2043
  28. package/dist/editor.js.map +4 -4
  29. package/dist/eslint/index.js +1 -0
  30. package/dist/eslint/index.js.map +2 -2
  31. package/dist/eslint/no-restyled-part.d.ts.map +1 -1
  32. package/dist/index.d.ts +9 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +546 -72
  35. package/dist/index.js.map +4 -4
  36. package/dist/linked.d.ts +168 -0
  37. package/dist/linked.d.ts.map +1 -0
  38. package/dist/linked.examples.d.ts +27 -0
  39. package/dist/linked.examples.d.ts.map +1 -0
  40. package/package.json +6 -2
  41. package/registry.json +1129 -37
  42. package/src/CardUnder.mdx +53 -0
  43. package/src/CardUnder.stories.tsx +45 -0
  44. package/src/CardUnder.test.tsx +40 -0
  45. package/src/CardUnder.tsx +45 -0
  46. package/src/CommentBox.mdx +83 -0
  47. package/src/CommentBox.stories.tsx +218 -0
  48. package/src/CommentBox.test.tsx +265 -0
  49. package/src/CommentBox.tsx +472 -0
  50. package/src/ComposeBox.tsx +5 -4
  51. package/src/InlineChip.tsx +2 -0
  52. package/src/LinkCard.mdx +58 -0
  53. package/src/LinkCard.stories.tsx +68 -0
  54. package/src/LinkCard.test.tsx +103 -0
  55. package/src/LinkCard.tsx +209 -0
  56. package/src/LinkChip.mdx +51 -0
  57. package/src/LinkChip.stories.tsx +40 -0
  58. package/src/LinkChip.test.tsx +83 -0
  59. package/src/LinkChip.tsx +51 -0
  60. package/src/LinkParts.mdx +49 -0
  61. package/src/LinkParts.stories.tsx +61 -0
  62. package/src/LinkParts.tsx +147 -0
  63. package/src/LinkPreview.mdx +47 -0
  64. package/src/LinkPreview.stories.tsx +38 -0
  65. package/src/LinkPreview.tsx +55 -0
  66. package/src/LinkRow.mdx +47 -0
  67. package/src/LinkRow.stories.tsx +49 -0
  68. package/src/LinkRow.test.tsx +38 -0
  69. package/src/LinkRow.tsx +107 -0
  70. package/src/PartCard.mdx +43 -0
  71. package/src/PartCard.stories.tsx +35 -0
  72. package/src/PartCard.test.tsx +30 -0
  73. package/src/PartCard.tsx +59 -0
  74. package/src/ReactionRow.mdx +50 -0
  75. package/src/ReactionRow.stories.tsx +91 -0
  76. package/src/ReactionRow.test.tsx +68 -0
  77. package/src/ReactionRow.tsx +118 -0
  78. package/src/Skeleton.tsx +7 -3
  79. package/src/editor.ts +11 -0
  80. package/src/eslint/no-native-title.test.ts +3 -2
  81. package/src/eslint/no-restyled-part.ts +1 -0
  82. package/src/index.ts +26 -0
  83. package/src/linked.examples.ts +107 -0
  84. package/src/linked.test.ts +58 -0
  85. package/src/linked.ts +217 -0
  86. package/src/registry/registry.test.ts +8 -8
  87. package/stories/Choosing.mdx +10 -1
@@ -0,0 +1,472 @@
1
+ import { useCallback, useEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
2
+ import { Extension, type AnyExtension } from '@tiptap/core'
3
+ import { EditorContent, useEditor, type Editor, type JSONContent } from '@tiptap/react'
4
+ import StarterKit from '@tiptap/starter-kit'
5
+ import { IconLock, IconPaperclip, IconSquareRounded } from '@tabler/icons-react'
6
+ import { AttachmentCard } from './AttachmentCard'
7
+ import { ReferenceNode, type ReferenceViewProps } from './BlockNodes'
8
+ import { Button } from './Button'
9
+ import { Card } from './Card'
10
+ import { cn } from './cn'
11
+ import { ComposeBox, ComposeKeys, COMPOSE_EDITOR_CLASSES, isEmptyDoc as isEmpty } from './ComposeBox'
12
+ import {
13
+ CaptionedReference,
14
+ PersonMention,
15
+ ReferenceTrigger,
16
+ SlashCommands,
17
+ UrgentPersonMention,
18
+ formatSection,
19
+ typeTrigger,
20
+ type CodeFormat,
21
+ type MentionPerson,
22
+ type ReferenceSection,
23
+ type SlashCommand,
24
+ type SlashSection,
25
+ } from './ComposerTriggers'
26
+ import { FieldLine } from './Field'
27
+ import { FilePicker } from './FilePicker'
28
+ import { Kbd } from './Kbd'
29
+ import { WRITING_BOX_CLASSES } from './looks'
30
+ import { PastedImages } from './PastedImages'
31
+ import { KeptSelection } from './SelectionToolbar'
32
+ import { isSuggestionOpen } from './suggestionPopup'
33
+ import { ToolbarButton } from './Toolbar'
34
+
35
+ /**
36
+ * The one box every app writes a comment, a reply and a chat line in, from the
37
+ * approved prototype (`concept/comments-everywhere`, Miky 17 October): the
38
+ * package's `ComposeBox` with everything each app built around it — `@`,
39
+ * `!@`, `[` and `/`, the keys, drafts, files, the edit mode, sending and a
40
+ * refused send. An app hands over only its people, its `[` sections, its `/`
41
+ * Insert rows and a send that says whether the relay accepted it.
42
+ *
43
+ * It speaks the editor's document. What that document writes as a message,
44
+ * and the document an edit or a draft opens with, are `@estiva-app/conversation`'s
45
+ * (`composerText`, `composerDocument`, `composerDraft`).
46
+ *
47
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-writes-and-reacts-with-one-shared-box.md
48
+ */
49
+
50
+ /** What the relay said about a send, an edit or an upload. */
51
+ export type SendAnswer = { accepted: true } | { accepted: false; reason: string }
52
+
53
+ /** What an upload answered: the app's own record of the file, or why not. */
54
+ export type UploadAnswer = { accepted: true; value: unknown } | { accepted: false; reason: string }
55
+
56
+ /** Where a file in the box is: Send waits for one uploading. */
57
+ export type BoxFileState = 'uploading' | 'ready' | 'failed'
58
+
59
+ /** A file in the box. */
60
+ export interface BoxFile {
61
+ id: string
62
+ name: string
63
+ size?: number
64
+ contentType?: string
65
+ state: BoxFileState
66
+ /** Why it failed, under its name. */
67
+ note?: string
68
+ /** What `upload` answered for it: the app's own record (an `imeta`, a URL). */
69
+ value?: unknown
70
+ }
71
+
72
+ /** A draft, in the box's terms — `@estiva-app/conversation`'s `composerDraft` is one. */
73
+ export interface CommentBoxDraft {
74
+ read(): JSONContent | undefined
75
+ write(body: JSONContent): void
76
+ clear(): void
77
+ }
78
+
79
+ /** Editing something already sent: the same box, with Cancel and Save. */
80
+ export interface CommentBoxEdit {
81
+ /** What it says now, as `composerDocument` opens it. */
82
+ body: JSONContent
83
+ /** Its files, which can be taken off; none can be added. */
84
+ files?: BoxFile[]
85
+ onCancel: () => void
86
+ /** Save; the box holds the words until the answer, and a refusal is said under it. */
87
+ onSave: (body: JSONContent, files: BoxFile[]) => Promise<SendAnswer>
88
+ }
89
+
90
+ export interface CommentBoxProps {
91
+ /** Who `@` and `!@` offer. */
92
+ people: readonly MentionPerson[]
93
+ /** What `[` lists for what was typed, already in the app's order. Absent, `[` opens nothing. */
94
+ references?: (query: string) => readonly ReferenceSection[]
95
+ /** Called with a listener while `[` is open; call it when `references` would answer differently (a search landed). */
96
+ referencesChanged?: (listener: () => void) => () => void
97
+ /** A `[` row's and chip's 16px icon from what it points at; absent, a neutral square. */
98
+ referenceIcon?: (uri: string | null) => ReactNode | undefined
99
+ /** The app's own `/` Insert rows, after the shared Format section: {@link commentBoxRows} and its own. */
100
+ insert?: readonly SlashCommand[]
101
+ /** `/` → Code: a mark inside the line, or a block. */
102
+ code?: CodeFormat
103
+ /** Send what is written, with the files that are ready; resolves with the relay's answer. */
104
+ send: (body: JSONContent, files: BoxFile[]) => Promise<SendAnswer>
105
+ /**
106
+ * The app shows a send before the relay answers: the box empties at once,
107
+ * and a refusal puts the words back. Otherwise the box holds the words, shut,
108
+ * until the answer.
109
+ */
110
+ showsAtOnce?: boolean
111
+ /** The editor's accessible name: what the box is for. */
112
+ label: string
113
+ /** Said in the empty box. */
114
+ placeholder: ReactNode
115
+ /** Keeps what is written when the box goes away. Give the box a React `key` per destination. */
116
+ draft?: CommentBoxDraft
117
+ /** Editing something already sent. */
118
+ edit?: CommentBoxEdit
119
+ /** Offers the paperclip, `/` → File, a pasted picture and a dropped file: uploads one, and answers. */
120
+ upload?: (file: File) => Promise<UploadAnswer>
121
+ /** The file picker's `accept`. */
122
+ accept?: string
123
+ /** The box cannot write here (an archived file, signed out): a line saying why takes its place. */
124
+ closed?: { reason: ReactNode }
125
+ /** How a `nostr:` reference the box holds is drawn — the app's own chip. Absent, as its URI. */
126
+ referenceView?: ComponentType<ReferenceViewProps>
127
+ /** The app's own extra editor extensions: link chips, highlights. */
128
+ extensions?: readonly AnyExtension[]
129
+ autoFocus?: boolean
130
+ /** Called with what was sent once it went out: at once when `showsAtOnce`, else on the answer. */
131
+ onSent?: (body: JSONContent, files: BoxFile[]) => void
132
+ /** Called when a send shown at once was refused, so the app takes it back. */
133
+ onRefused?: () => void
134
+ className?: string
135
+ }
136
+
137
+ const ATTACH_EVENT = 'commentbox:attach'
138
+
139
+ /** Asks the box around the editor for a file, as the paperclip does. */
140
+ const askForFile = (editor: Editor) => editor.view.dom.dispatchEvent(new CustomEvent(ATTACH_EVENT, { bubbles: true }))
141
+
142
+ /**
143
+ * The `/` Insert rows the kit offers. Pass the ones an app can perform, in
144
+ * its order, with its own after them; an edit drops File and Urgent itself.
145
+ */
146
+ export const commentBoxRows: Readonly<Record<'file' | 'mention' | 'urgent' | 'reference', SlashCommand>> = {
147
+ file: { key: 'insert-file', row: { label: 'File' }, keywords: ['attach', 'upload'], run: askForFile },
148
+ mention: { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'Mention a person'], run: typeTrigger('@') },
149
+ urgent: { key: 'insert-urgent', row: { label: 'Urgent', shortcut: '!@' }, keywords: ['!@', 'Urgent mention'], run: typeTrigger('!@') },
150
+ reference: { key: 'insert-reference', row: { label: 'Reference', shortcut: '[' }, keywords: ['[', 'Reference'], run: typeTrigger('[') },
151
+ }
152
+
153
+ /** Ctrl/Cmd+Enter sends as Enter does; Escape cancels an edit (an open list takes Escape first). */
154
+ const BoxKeys = Extension.create<{ onEscape: () => boolean }>({
155
+ name: 'commentBoxKeys',
156
+ addOptions() {
157
+ return { onEscape: () => false }
158
+ },
159
+ addKeyboardShortcuts() {
160
+ return {
161
+ 'Mod-Enter': ({ editor }) => (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys?.send?.() ?? false,
162
+ // Open now, with no grace: the first Escape closes a list, the next is a deliberate cancel (suggestionPopup).
163
+ Escape: () => (isSuggestionOpen() ? false : this.options.onEscape()),
164
+ }
165
+ },
166
+ })
167
+
168
+ const SQUARE = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
169
+ const SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />
170
+
171
+ let fileCount = 0
172
+
173
+ export function CommentBox({
174
+ people,
175
+ references,
176
+ referencesChanged,
177
+ referenceIcon,
178
+ insert = [],
179
+ code = 'block',
180
+ send,
181
+ showsAtOnce = false,
182
+ label,
183
+ placeholder,
184
+ draft,
185
+ edit,
186
+ upload,
187
+ accept,
188
+ closed,
189
+ referenceView,
190
+ extensions = [],
191
+ autoFocus,
192
+ onSent,
193
+ onRefused,
194
+ className,
195
+ }: CommentBoxProps) {
196
+ const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])
197
+ const [sending, setSending] = useState(false)
198
+ const [refused, setRefused] = useState<string | null>(null)
199
+ const picker = useRef<HTMLInputElement>(null)
200
+ const root = useRef<HTMLDivElement>(null)
201
+ // The latest props, for the editor's callbacks, which are made once.
202
+ const latest = useRef({ edit, people, references, referencesChanged, referenceIcon, upload, draft })
203
+ latest.current = { edit, people, references, referencesChanged, referenceIcon, upload, draft }
204
+ const save = useRef<() => boolean>(() => false)
205
+
206
+ const attachFiles = useCallback((picked: File[]): boolean => {
207
+ const uploadOne = latest.current.upload
208
+ if (!uploadOne || latest.current.edit) return false
209
+ for (const file of picked) {
210
+ fileCount += 1
211
+ const id = `file-${fileCount}`
212
+ setFiles((all) => [...all, { id, name: file.name, size: file.size, contentType: file.type, state: 'uploading' }])
213
+ uploadOne(file).then(
214
+ (answer) =>
215
+ setFiles((all) =>
216
+ all.map((f) => (f.id !== id ? f : answer.accepted ? { ...f, state: 'ready', value: answer.value } : { ...f, state: 'failed', note: answer.reason })),
217
+ ),
218
+ () => setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'failed', note: 'It could not be uploaded.' } : f))),
219
+ )
220
+ }
221
+ return true
222
+ }, [])
223
+
224
+ // An edit cannot add a file or make a mention urgent, as in every app before the box; no upload, no File.
225
+ const rows = insert.filter((c) => !((edit || !upload) && c.key === commentBoxRows.file.key) && !(edit && c.key === commentBoxRows.urgent.key))
226
+ // `/` reads its sections each time it opens, from this one array: refilled every render, so a row that
227
+ // comes or goes with `upload`, `insert` or `code` after the box opened is offered as it is now.
228
+ const sections = useRef<SlashSection[]>([]).current
229
+ sections.splice(0, sections.length, formatSection(code), ...(rows.length > 0 ? [{ label: 'Insert', commands: rows }] : []))
230
+ const iconFor = useCallback((uri: string | null) => latest.current.referenceIcon?.(uri), [])
231
+
232
+ const editor = useEditor({
233
+ extensions: [
234
+ StarterKit.configure({ link: { openOnClick: false } }),
235
+ KeptSelection,
236
+ ComposeKeys,
237
+ BoxKeys.configure({
238
+ onEscape: () => {
239
+ const editing = latest.current.edit
240
+ if (!editing) return false
241
+ editing.onCancel()
242
+ return true
243
+ },
244
+ }),
245
+ PersonMention.configure({ people: () => latest.current.people }),
246
+ // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.
247
+ UrgentPersonMention.extend({
248
+ addOptions() {
249
+ const parent = this.parent!()
250
+ return { ...parent, suggestion: { ...parent.suggestion, allow: () => !latest.current.edit } }
251
+ },
252
+ }).configure({ people: () => latest.current.people }),
253
+ CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor }),
254
+ ReferenceTrigger.configure({
255
+ items: () => [],
256
+ sections: (query) => latest.current.references?.(query) ?? [],
257
+ subscribe: (listener) => latest.current.referencesChanged?.(listener) ?? (() => {}),
258
+ ariaLabel: 'References',
259
+ sectionLabel: 'References',
260
+ icon: SQUARE,
261
+ iconFor,
262
+ }),
263
+ SlashCommands.configure({ sections }),
264
+ ReferenceNode.configure({ view: referenceView ?? null }),
265
+ PastedImages.configure({ onImages: attachFiles }),
266
+ ...extensions,
267
+ ],
268
+ content: edit?.body ?? draft?.read(),
269
+ editable: !closed,
270
+ editorProps: { attributes: { class: COMPOSE_EDITOR_CLASSES, role: 'textbox', 'aria-multiline': 'true', 'aria-label': label } },
271
+ })
272
+
273
+ // Drafts: every change is kept, and an empty box is no draft.
274
+ useEffect(() => {
275
+ if (!editor || edit) return
276
+ const keep = () => {
277
+ const kept = latest.current.draft
278
+ if (!kept) return
279
+ if (isEmpty(editor)) kept.clear()
280
+ else kept.write(editor.getJSON())
281
+ }
282
+ editor.on('update', keep)
283
+ return () => {
284
+ editor.off('update', keep)
285
+ }
286
+ }, [editor, edit])
287
+
288
+ useEffect(() => {
289
+ editor?.setEditable(!closed && !sending)
290
+ }, [editor, closed, sending])
291
+
292
+ useEffect(() => {
293
+ if (!editor || !(autoFocus || edit)) return
294
+ const frame = requestAnimationFrame(() => editor.commands.focus('end'))
295
+ return () => cancelAnimationFrame(frame)
296
+ // Once, as the box opens.
297
+ }, [editor])
298
+
299
+ // `/` → File asks for a file the way the paperclip does.
300
+ useEffect(() => {
301
+ const box = root.current
302
+ if (!box || !upload || edit) return
303
+ const ask = () => picker.current?.click()
304
+ box.addEventListener(ATTACH_EVENT, ask)
305
+ return () => box.removeEventListener(ATTACH_EVENT, ask)
306
+ }, [upload, edit])
307
+
308
+ const uploading = files.some((f) => f.state === 'uploading')
309
+ const ready = files.some((f) => f.state === 'ready')
310
+
311
+ const go = useCallback(
312
+ (ed: Editor): boolean => {
313
+ const body = ed.getJSON()
314
+ const sent = files.filter((f) => f.state === 'ready')
315
+ setRefused(null)
316
+ const answered = (answer: Promise<SendAnswer>) => answer.catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
317
+ if (showsAtOnce) {
318
+ // Shown at once: the box empties now (ComposeBox clears it); a refusal puts the words back above anything written since.
319
+ setFiles((all) => all.filter((f) => f.state !== 'ready'))
320
+ draft?.clear()
321
+ onSent?.(body, sent)
322
+ void answered(send(body, sent)).then((answer) => {
323
+ if (answer.accepted) return
324
+ onRefused?.()
325
+ if (ed.isDestroyed) {
326
+ // The box went away before the answer: the words wait in its draft.
327
+ draft?.write(body)
328
+ return
329
+ }
330
+ if (isEmpty(ed)) ed.commands.setContent(body)
331
+ else ed.commands.insertContentAt(0, body.content ?? [])
332
+ ed.commands.focus('end')
333
+ setFiles((all) => [...sent, ...all])
334
+ setRefused(answer.reason)
335
+ })
336
+ return true
337
+ }
338
+ // Held: the words stay, shut, until the relay answers.
339
+ setSending(true)
340
+ void answered(send(body, sent)).then((answer) => {
341
+ setSending(false)
342
+ if (!answer.accepted) {
343
+ setRefused(answer.reason)
344
+ return
345
+ }
346
+ if (!ed.isDestroyed) ed.commands.clearContent(true)
347
+ setFiles((all) => all.filter((f) => !sent.includes(f)))
348
+ draft?.clear()
349
+ onSent?.(body, sent)
350
+ })
351
+ return false
352
+ },
353
+ [files, showsAtOnce, send, draft, onSent, onRefused],
354
+ )
355
+
356
+ save.current = () => {
357
+ if (!editor || !edit || sending || uploading) return true
358
+ setRefused(null)
359
+ setSending(true)
360
+ void edit
361
+ .onSave(editor.getJSON(), files)
362
+ .catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
363
+ .then((answer) => {
364
+ setSending(false)
365
+ if (!answer.accepted) setRefused(answer.reason)
366
+ })
367
+ return true
368
+ }
369
+
370
+ // Enter and Ctrl/Cmd+Enter save an edit; the send box wires them through ComposeBox.
371
+ useEffect(() => {
372
+ if (!editor || !edit) return
373
+ const storage = (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys
374
+ if (!storage) return
375
+ storage.send = () => save.current()
376
+ return () => {
377
+ storage.send = null
378
+ }
379
+ }, [editor, edit])
380
+
381
+ if (closed) {
382
+ return (
383
+ <Card fill="inset" className={cn('flex items-start gap-3 px-4 py-3', className)}>
384
+ <IconLock size={16} stroke={1.5} className="mt-0.5 shrink-0 text-text-muted" aria-hidden />
385
+ <p className="text-body-2 text-text-secondary">{closed.reason}</p>
386
+ </Card>
387
+ )
388
+ }
389
+
390
+ const fileCards =
391
+ files.length > 0 ? (
392
+ <>
393
+ {files.map((f) => (
394
+ <AttachmentCard
395
+ key={f.id}
396
+ pending
397
+ name={f.name}
398
+ size={f.size}
399
+ contentType={f.contentType}
400
+ state={f.state}
401
+ note={f.note}
402
+ onRemove={() => setFiles((all) => all.filter((one) => one !== f))}
403
+ />
404
+ ))}
405
+ </>
406
+ ) : undefined
407
+
408
+ const refusedLine = refused && (
409
+ <FieldLine tone="error">
410
+ {edit ? `Not saved: ${refused}. Your changes are still in the box.` : `Not sent: ${refused}. Your text is back in the box.`}
411
+ </FieldLine>
412
+ )
413
+
414
+ if (edit) {
415
+ return (
416
+ <div className={cn('flex flex-col gap-1', className)}>
417
+ <div className={cn(WRITING_BOX_CLASSES, 'focus-within:border-border-strong transition-colors', sending && '[&_.ProseMirror]:text-text-muted')}>
418
+ <EditorContent editor={editor} />
419
+ {fileCards && <div className="flex flex-wrap gap-2">{fileCards}</div>}
420
+ <div className="flex items-center justify-between gap-2">
421
+ <span className="flex items-center gap-1 text-caption text-text-muted">
422
+ <Kbd>Esc</Kbd> to cancel · <Kbd>Enter</Kbd> to save
423
+ </span>
424
+ <div className="flex items-center gap-2">
425
+ <Button variant="outlined" size="small" onClick={edit.onCancel}>
426
+ Cancel
427
+ </Button>
428
+ <Button variant="primary" size="small" disabled={uploading || sending} onClick={() => save.current()}>
429
+ Save
430
+ </Button>
431
+ </div>
432
+ </div>
433
+ </div>
434
+ {sending && <FieldLine>Saving…</FieldLine>}
435
+ {refusedLine}
436
+ </div>
437
+ )
438
+ }
439
+
440
+ const onDrop = (event: DragEvent<HTMLDivElement>) => {
441
+ const dropped = Array.from(event.dataTransfer?.files ?? [])
442
+ if (dropped.length === 0 || !upload) return
443
+ event.preventDefault()
444
+ attachFiles(dropped)
445
+ }
446
+
447
+ return (
448
+ <div ref={root} className={cn('flex flex-col gap-1', className)} onDragOver={upload ? (e) => e.preventDefault() : undefined} onDrop={onDrop}>
449
+ <ComposeBox
450
+ editor={editor}
451
+ onSend={go}
452
+ placeholder={placeholder}
453
+ tools={
454
+ upload ? (
455
+ <ToolbarButton tooltip="Attach a file" aria-label="Attach a file" disabled={sending} onClick={() => picker.current?.click()}>
456
+ <IconPaperclip size={16} stroke={1.5} />
457
+ </ToolbarButton>
458
+ ) : undefined
459
+ }
460
+ attachments={fileCards}
461
+ ready={ready}
462
+ holding={uploading || sending}
463
+ selection={{ link: true }}
464
+ className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}
465
+ />
466
+ {upload && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}
467
+ {sending && <FieldLine>Sending…</FieldLine>}
468
+ {uploading && !sending && <FieldLine>Uploading… Send waits for the file.</FieldLine>}
469
+ {refusedLine}
470
+ </div>
471
+ )
472
+ }
@@ -59,13 +59,14 @@ export const ComposeKeys = Extension.create<Record<string, never>, ComposeKeysSt
59
59
  },
60
60
  })
61
61
 
62
- /** Nothing written: no text, no chip and no picture — empty lines, lists or quotes only. */
63
- function isEmptyDoc(editor: Editor): boolean {
62
+ /** Nothing written: no text, no chip and no picture — empty lines, spaces, lists or quotes only. */
63
+ export function isEmptyDoc(editor: Editor): boolean {
64
64
  const doc = editor.state.doc
65
- if (doc.textContent.length > 0) return false
65
+ if (doc.textContent.trim().length > 0) return false
66
66
  let empty = true
67
67
  doc.descendants((node) => {
68
- if (node.isAtom && node.type.name !== 'hardBreak') empty = false
68
+ // A text node is a leaf, so an atom too: only spaces are left of it here.
69
+ if (node.isAtom && !node.isText && node.type.name !== 'hardBreak') empty = false
69
70
  })
70
71
  return empty
71
72
  }
@@ -45,6 +45,8 @@ export const INLINE_CHIP_TONE_CLASSES = {
45
45
  * copy of this chip still has the 16.8px box).
46
46
  */
47
47
  quiet: 'h-[19.6px] bg-bg-active text-text-muted font-mono text-caption',
48
+ /** A file this reader cannot open — deleted, or not theirs to see: said in words, quieter than a link. */
49
+ muted: 'bg-bg-active text-text-muted',
48
50
  } as const
49
51
 
50
52
  export type InlineChipTone = keyof typeof INLINE_CHIP_TONE_CLASSES
@@ -0,0 +1,58 @@
1
+ import { Meta, Canvas, Controls } from '@storybook/addon-docs/blocks'
2
+ import * as LinkCardStories from './LinkCard.stories'
3
+
4
+ <Meta of={LinkCardStories} />
5
+
6
+ # LinkCard
7
+
8
+ A link's card: what a row cannot hold, and the changes the reader may make from it.
9
+
10
+ <Canvas of={LinkCardStories.Default} />
11
+
12
+ ## When
13
+
14
+ - **ready** — the title as the link (the icon opens it too), the key and what it is in, its summary, the items inside it, its newest conversation, and a footer: the pickers and the conversation count, or who wrote it and when. No summary, the title alone.
15
+ - **read only** — a picker the app passed no `onChange` for reads as words in the same place: the reader may not change it. `readOnly` makes every value words, as the hover preview does.
16
+ - **words a person wrote** — their face, their name, the time as the link, and the words.
17
+ - **loading** — the card it will become in bars, at its own height: `shape` from `loadingShapeOf(linked)` the last time it drew, or the kind's usual card. **LinkCardLoading**, from this file.
18
+ - **unavailable** — one line, as **LinkRow** draws it.
19
+
20
+ <Canvas of={LinkCardStories.ReadOnly} />
21
+ <Canvas of={LinkCardStories.Loading} />
22
+
23
+ ## When not
24
+
25
+ - A link alone on its line, where the card was not chosen → **LinkRow**.
26
+ - The one card under a piece of text, with its ✕ → **CardUnder**, which draws this.
27
+ - A part of something longer → **PartCard**.
28
+
29
+ ## How
30
+
31
+ ```tsx
32
+ import { LinkCard } from '@estiva-app/ui'
33
+
34
+ const linked = {
35
+ ...fromLookup,
36
+ status: { value: statusKey, options: statuses, onChange: mayChange ? setStatus : undefined },
37
+ owner: { value: ownerKey, options: people, onChange: mayChange ? setOwner : undefined },
38
+ ownerLabel: 'Owner',
39
+ }
40
+ <LinkCard link={{ state: 'ready', linked }} />
41
+ ```
42
+
43
+ - **Whether the reader may change it is the app's.** Pass `onChange` only to a reader who may; anyone else sees words.
44
+ - The picker offers only the options it is given: to let the reader set nobody as the owner, include an option for it.
45
+ - `linked.latest` is drawn whenever it is given: pass it only to a reader who may read it.
46
+ - `linked.conversation.unread` only for a member of it.
47
+
48
+ ## What it owns
49
+
50
+ | It does | So you never write |
51
+ |---|---|
52
+ | Draws the pickers, or the same values as words | a read-only variant of your own |
53
+ | Holds its own height while it loads | a placeholder height of your own |
54
+ | Opens each item inside it on its own | a row click handler |
55
+
56
+ ## Props
57
+
58
+ <Controls of={LinkCardStories.ReadOnly} />
@@ -0,0 +1,68 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite'
2
+ import { useState } from 'react'
3
+ import { LinkCard, LinkCardLoading } from './LinkCard'
4
+ import { loadingShapeOf, type Linked } from './linked'
5
+ import { GROUP, ITEM, ITEM_NO_SUMMARY, ITEM_READ_ONLY, ITEM_UNREAD, PAGE, PLACE, ready, SAID, UNAVAILABLE } from './linked.examples'
6
+
7
+ const meta = {
8
+ title: 'Components/LinkCard',
9
+ component: LinkCard,
10
+ parameters: { layout: 'padded' },
11
+ args: { link: ready(ITEM) },
12
+ decorators: [(Story) => <div className="max-w-[480px]">{Story()}</div>],
13
+ } satisfies Meta<typeof LinkCard>
14
+
15
+ export default meta
16
+ type Story = StoryObj<typeof meta>
17
+
18
+ /** Its status and owner change from the card: pick one. */
19
+ export const Default: Story = {
20
+ render: () => {
21
+ const [status, setStatus] = useState('doing')
22
+ const [owner, setOwner] = useState<string>('a')
23
+ const linked: Linked = { ...ITEM, status: { ...ITEM.status!, value: status, onChange: setStatus }, owner: { ...ITEM.owner!, value: owner, onChange: setOwner } }
24
+ return <LinkCard link={ready(linked)} />
25
+ },
26
+ }
27
+
28
+ /** To a reader who may not change it: the same two values, as words. */
29
+ export const ReadOnly: Story = { args: { link: ready(ITEM_READ_ONLY) } }
30
+
31
+ /** Something unread in its conversation, to a member: the count is brighter, with a dot. */
32
+ export const Unread: Story = { args: { link: ready(ITEM_UNREAD) } }
33
+
34
+ /** No summary: the title alone. */
35
+ export const NoSummary: Story = { args: { link: ready(ITEM_NO_SUMMARY) } }
36
+
37
+ /** A group: its progress, its lead, and each item inside, which opens on its own. */
38
+ export const WithItems: Story = { args: { link: ready(GROUP) } }
39
+
40
+ /** A place people talk: its members and its newest conversation. */
41
+ export const WithLatest: Story = { args: { link: ready(PLACE) } }
42
+
43
+ /** A page of text: who wrote it, and when. */
44
+ export const WithAuthors: Story = { args: { link: ready(PAGE) } }
45
+
46
+ /** Words a person wrote: their face, the time as the link, and the words. */
47
+ export const WordsAPersonWrote: Story = { args: { link: ready(SAID) } }
48
+
49
+ /** Still being looked up, beside the card it becomes: the same height. */
50
+ export const Loading: Story = {
51
+ render: () => (
52
+ <div className="flex flex-col gap-3">
53
+ {[ITEM, GROUP, PLACE, PAGE].map((linked) => (
54
+ // Each at a card's full width, as under a message: a narrower column wraps the summary.
55
+ <div key={linked.id} className="grid w-[968px] grid-cols-[480px_480px] items-start gap-2">
56
+ <LinkCardLoading kind={linked.kind} shape={loadingShapeOf(linked)} />
57
+ <LinkCard link={ready(linked)} />
58
+ </div>
59
+ ))}
60
+ </div>
61
+ ),
62
+ }
63
+
64
+ /** Nothing remembered of it: the kind's usual card. */
65
+ export const LoadingByKind: Story = { args: { link: { state: 'loading', kind: 'issue' } } }
66
+
67
+ /** Deleted, or not this reader's to see: one line. */
68
+ export const NotAvailable: Story = { args: { link: UNAVAILABLE } }