@estiva-app/ui 0.79.0 → 0.81.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.
@@ -1,5 +1,6 @@
1
- import { useCallback, useEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
1
+ import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
2
2
  import { Extension, type AnyExtension } from '@tiptap/core'
3
+ import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
3
4
  import { EditorContent, useEditor, type Editor, type JSONContent } from '@tiptap/react'
4
5
  import StarterKit from '@tiptap/starter-kit'
5
6
  import { IconLock, IconPaperclip, IconSquareRounded } from '@tabler/icons-react'
@@ -7,6 +8,7 @@ import { AttachmentCard } from './AttachmentCard'
7
8
  import { ReferenceNode, type ReferenceViewProps } from './BlockNodes'
8
9
  import { Button } from './Button'
9
10
  import { Card } from './Card'
11
+ import { CardUnder } from './CardUnder'
10
12
  import { cn } from './cn'
11
13
  import { ComposeBox, ComposeKeys, COMPOSE_EDITOR_CLASSES, isEmptyDoc as isEmpty } from './ComposeBox'
12
14
  import {
@@ -84,7 +86,36 @@ export interface CommentBoxEdit {
84
86
  files?: BoxFile[]
85
87
  onCancel: () => void
86
88
  /** Save; the box holds the words until the answer, and a refusal is said under it. */
87
- onSave: (body: JSONContent, files: BoxFile[]) => Promise<SendAnswer>
89
+ onSave: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>
90
+ }
91
+
92
+ /**
93
+ * What a draft shows under the box, as the app reads it from the box's
94
+ * document — `@estiva-app/conversation`'s `boxReadOf`, which reads it as the
95
+ * message will be sent (why:
96
+ * https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md).
97
+ */
98
+ export interface BoxUnderRead {
99
+ /** The one card, before any ✕: what it names, and the app's own view of it, drawn as it draws a sent one. */
100
+ card?: { value: string; view: ReactNode }
101
+ /** The live parts, drawn as the app draws them under a sent message. An edit carries none, so the edit box shows none. */
102
+ parts?: readonly { key: string; view: ReactNode }[]
103
+ /** Everything the draft names. A ✕ is forgotten once what it took off is no longer named, so a link put back gets its card again. */
104
+ names: readonly string[]
105
+ }
106
+
107
+ /** What the box shows under itself while something is written. */
108
+ export interface BoxUnder {
109
+ /** Read on every change, and once more as it is sent. */
110
+ read: (body: JSONContent) => BoxUnderRead
111
+ /** Called with a listener; call it when `read` would answer differently (what a link names came back). */
112
+ changed?: (listener: () => void) => () => void
113
+ }
114
+
115
+ /** What was under the box as it was sent or saved. */
116
+ export interface BoxSentUnder {
117
+ /** The card still shown, by what it names: absent when there was none, or ✕ took it off. */
118
+ card?: string
88
119
  }
89
120
 
90
121
  export interface CommentBoxProps {
@@ -100,8 +131,10 @@ export interface CommentBoxProps {
100
131
  insert?: readonly SlashCommand[]
101
132
  /** `/` → Code: a mark inside the line, or a block. */
102
133
  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>
134
+ /** Send what is written, with the files that are ready and the card still shown; resolves with the relay's answer. */
135
+ send: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>
136
+ /** The card and parts under the box while something is written, with ✕ on the card. Absent, nothing shows under it. */
137
+ under?: BoxUnder
105
138
  /**
106
139
  * The app shows a send before the relay answers: the box empties at once,
107
140
  * and a refusal puts the words back. Otherwise the box holds the words, shut,
@@ -128,7 +161,7 @@ export interface CommentBoxProps {
128
161
  extensions?: readonly AnyExtension[]
129
162
  autoFocus?: boolean
130
163
  /** Called with what was sent once it went out: at once when `showsAtOnce`, else on the answer. */
131
- onSent?: (body: JSONContent, files: BoxFile[]) => void
164
+ onSent?: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => void
132
165
  /** Called when a send shown at once was refused, so the app takes it back. */
133
166
  onRefused?: () => void
134
167
  className?: string
@@ -165,6 +198,64 @@ const BoxKeys = Extension.create<{ onEscape: () => boolean }>({
165
198
  },
166
199
  })
167
200
 
201
+ /** A link a message can carry on words, `[words](url)`: no `)` and no space in it (conversation's `composerText`). */
202
+ const LINK_ON_WORDS_TARGET = /^https?:\/\/[^\s)]+$/
203
+
204
+ /**
205
+ * A URL pasted over words links them, as in Peek, when the message can carry
206
+ * them as a link on words: plain words on one line, no chip, no line break, no
207
+ * bracket, no code. Otherwise the words stay and the URL goes in after them,
208
+ * so neither is lost. Ahead of StarterKit's own link-on-paste.
209
+ */
210
+ const PasteOverWords = Extension.create({
211
+ name: 'commentBoxPasteOverWords',
212
+ priority: 1001,
213
+ addProseMirrorPlugins() {
214
+ return [
215
+ new Plugin({
216
+ key: new PluginKey('commentBoxPasteOverWords'),
217
+ props: {
218
+ handlePaste: (view, event) => {
219
+ // A URL copied with the end of its sentence names what it names without it, as LinkChips reads one.
220
+ const url = (event.clipboardData?.getData('text/plain').trim() ?? '').replace(/[.,;:!?]+$/, '')
221
+ const { state } = view
222
+ const { schema } = state
223
+ if (state.selection.empty || !schema.marks.link || !/^https?:\/\/\S+$/.test(url)) return false
224
+ // Select-all spans the document itself: read it as the text it holds.
225
+ const { $from, $to, from, to } = TextSelection.between(state.selection.$from, state.selection.$to)
226
+ let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code
227
+ state.doc.nodesBetween(from, to, (node) => {
228
+ if (node.isTextblock) return true
229
+ if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) plain = false
230
+ return false
231
+ })
232
+ if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
233
+ view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })))
234
+ return true
235
+ }
236
+ const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '')
237
+ const inserted = before && !/\s/.test(before) ? ` ${url}` : url
238
+ const tr = state.tr.insertText(inserted, to)
239
+ view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to + inserted.length)).scrollIntoView())
240
+ return true
241
+ },
242
+ },
243
+ }),
244
+ ]
245
+ },
246
+ })
247
+
248
+ /** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */
249
+ const BoxKit = StarterKit.extend({
250
+ addExtensions() {
251
+ return (this.parent?.() ?? []).map((extension) => (extension.name === 'link' ? extension.extend({ inclusive: () => false }) : extension))
252
+ },
253
+ })
254
+
255
+ /** What `removed` still holds of what the draft names; the same set when nothing was forgotten. */
256
+ const stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): ReadonlySet<string> =>
257
+ [...removed].every((value) => names.includes(value)) ? removed : new Set([...removed].filter((value) => names.includes(value)))
258
+
168
259
  const SQUARE = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
169
260
  const SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />
170
261
 
@@ -178,6 +269,7 @@ export function CommentBox({
178
269
  insert = [],
179
270
  code = 'block',
180
271
  send,
272
+ under,
181
273
  showsAtOnce = false,
182
274
  label,
183
275
  placeholder,
@@ -196,11 +288,14 @@ export function CommentBox({
196
288
  const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])
197
289
  const [sending, setSending] = useState(false)
198
290
  const [refused, setRefused] = useState<string | null>(null)
291
+ // What shows under the box, and what ✕ took off.
292
+ const [reading, setReading] = useState<BoxUnderRead | undefined>(undefined)
293
+ const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set())
199
294
  const picker = useRef<HTMLInputElement>(null)
200
295
  const root = useRef<HTMLDivElement>(null)
201
296
  // 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 }
297
+ const latest = useRef({ edit, people, references, referencesChanged, referenceIcon, upload, draft, under })
298
+ latest.current = { edit, people, references, referencesChanged, referenceIcon, upload, draft, under }
204
299
  const save = useRef<() => boolean>(() => false)
205
300
 
206
301
  const attachFiles = useCallback((picked: File[]): boolean => {
@@ -231,7 +326,8 @@ export function CommentBox({
231
326
 
232
327
  const editor = useEditor({
233
328
  extensions: [
234
- StarterKit.configure({ link: { openOnClick: false } }),
329
+ BoxKit.configure({ link: { openOnClick: false } }),
330
+ PasteOverWords,
235
331
  KeptSelection,
236
332
  ComposeKeys,
237
333
  BoxKeys.configure({
@@ -285,6 +381,36 @@ export function CommentBox({
285
381
  }
286
382
  }, [editor, edit])
287
383
 
384
+ // What shows under the box, read on every change and whenever the app's answers change.
385
+ const reads = !!under
386
+ useEffect(() => {
387
+ if (!editor || !reads) {
388
+ setReading(undefined)
389
+ return
390
+ }
391
+ const read = () => {
392
+ const now = latest.current.under?.read(editor.getJSON())
393
+ setReading(now)
394
+ setRemoved((was) => stillNamed(was, now?.names ?? []))
395
+ }
396
+ read()
397
+ editor.on('update', read)
398
+ const unsubscribe = latest.current.under?.changed?.(read)
399
+ return () => {
400
+ editor.off('update', read)
401
+ unsubscribe?.()
402
+ }
403
+ }, [editor, reads])
404
+
405
+ // What goes with a send or a save: read from what is sent, minus what ✕ took off.
406
+ const underOf = useCallback(
407
+ (body: JSONContent): BoxSentUnder => {
408
+ const card = latest.current.under?.read(body).card?.value
409
+ return card && !removed.has(card) ? { card } : {}
410
+ },
411
+ [removed],
412
+ )
413
+
288
414
  useEffect(() => {
289
415
  editor?.setEditable(!closed && !sending)
290
416
  }, [editor, closed, sending])
@@ -306,20 +432,25 @@ export function CommentBox({
306
432
  }, [upload, edit])
307
433
 
308
434
  const uploading = files.some((f) => f.state === 'uploading')
435
+ // A file that did not upload holds Send until its ✕ takes it off, so it is never sent without it unnoticed.
436
+ const failed = files.filter((f) => f.state === 'failed').length
309
437
  const ready = files.some((f) => f.state === 'ready')
310
438
 
311
439
  const go = useCallback(
312
440
  (ed: Editor): boolean => {
313
441
  const body = ed.getJSON()
314
442
  const sent = files.filter((f) => f.state === 'ready')
443
+ const sentUnder = underOf(body)
315
444
  setRefused(null)
316
445
  const answered = (answer: Promise<SendAnswer>) => answer.catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
317
446
  if (showsAtOnce) {
318
- // Shown at once: the box empties now (ComposeBox clears it); a refusal puts the words back above anything written since.
447
+ // Shown at once: the box empties now (ComposeBox clears it); a refusal puts the words back above anything written since,
448
+ // and what ✕ took off with them.
449
+ const took = removed
319
450
  setFiles((all) => all.filter((f) => f.state !== 'ready'))
320
451
  draft?.clear()
321
- onSent?.(body, sent)
322
- void answered(send(body, sent)).then((answer) => {
452
+ onSent?.(body, sent, sentUnder)
453
+ void answered(send(body, sent, sentUnder)).then((answer) => {
323
454
  if (answer.accepted) return
324
455
  onRefused?.()
325
456
  if (ed.isDestroyed) {
@@ -330,6 +461,7 @@ export function CommentBox({
330
461
  if (isEmpty(ed)) ed.commands.setContent(body)
331
462
  else ed.commands.insertContentAt(0, body.content ?? [])
332
463
  ed.commands.focus('end')
464
+ setRemoved((now) => new Set([...now, ...took]))
333
465
  setFiles((all) => [...sent, ...all])
334
466
  setRefused(answer.reason)
335
467
  })
@@ -337,28 +469,30 @@ export function CommentBox({
337
469
  }
338
470
  // Held: the words stay, shut, until the relay answers.
339
471
  setSending(true)
340
- void answered(send(body, sent)).then((answer) => {
472
+ void answered(send(body, sent, sentUnder)).then((answer) => {
341
473
  setSending(false)
342
474
  if (!answer.accepted) {
343
475
  setRefused(answer.reason)
344
476
  return
345
477
  }
346
478
  if (!ed.isDestroyed) ed.commands.clearContent(true)
479
+ setRemoved(new Set())
347
480
  setFiles((all) => all.filter((f) => !sent.includes(f)))
348
481
  draft?.clear()
349
- onSent?.(body, sent)
482
+ onSent?.(body, sent, sentUnder)
350
483
  })
351
484
  return false
352
485
  },
353
- [files, showsAtOnce, send, draft, onSent, onRefused],
486
+ [files, removed, underOf, showsAtOnce, send, draft, onSent, onRefused],
354
487
  )
355
488
 
356
489
  save.current = () => {
357
490
  if (!editor || !edit || sending || uploading) return true
358
491
  setRefused(null)
359
492
  setSending(true)
493
+ const body = editor.getJSON()
360
494
  void edit
361
- .onSave(editor.getJSON(), files)
495
+ .onSave(body, files, underOf(body))
362
496
  .catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
363
497
  .then((answer) => {
364
498
  setSending(false)
@@ -405,6 +539,19 @@ export function CommentBox({
405
539
  </>
406
540
  ) : undefined
407
541
 
542
+ // Under the box, outside its border: the card with its ✕, then the live parts (none in an edit, which carries none).
543
+ const card = reading?.card && !removed.has(reading.card.value) ? reading.card : undefined
544
+ const parts = edit ? [] : (reading?.parts ?? [])
545
+ const underBox =
546
+ card || parts.length > 0 ? (
547
+ <div data-box-under className="mt-1 flex flex-col gap-2">
548
+ {card && <CardUnder onRemove={() => setRemoved((was) => new Set([...was, card.value]))}>{card.view}</CardUnder>}
549
+ {parts.map((part) => (
550
+ <Fragment key={part.key}>{part.view}</Fragment>
551
+ ))}
552
+ </div>
553
+ ) : undefined
554
+
408
555
  const refusedLine = refused && (
409
556
  <FieldLine tone="error">
410
557
  {edit ? `Not saved: ${refused}. Your changes are still in the box.` : `Not sent: ${refused}. Your text is back in the box.`}
@@ -431,6 +578,7 @@ export function CommentBox({
431
578
  </div>
432
579
  </div>
433
580
  </div>
581
+ {underBox}
434
582
  {sending && <FieldLine>Saving…</FieldLine>}
435
583
  {refusedLine}
436
584
  </div>
@@ -459,13 +607,17 @@ export function CommentBox({
459
607
  }
460
608
  attachments={fileCards}
461
609
  ready={ready}
462
- holding={uploading || sending}
610
+ holding={uploading || failed > 0 || sending}
463
611
  selection={{ link: true }}
464
612
  className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}
465
613
  />
614
+ {underBox}
466
615
  {upload && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}
467
616
  {sending && <FieldLine>Sending…</FieldLine>}
468
617
  {uploading && !sending && <FieldLine>Uploading… Send waits for the file.</FieldLine>}
618
+ {failed > 0 && !uploading && !sending && (
619
+ <FieldLine>{failed === 1 ? 'Remove the file that did not upload to send.' : 'Remove the files that did not upload to send.'}</FieldLine>
620
+ )}
469
621
  {refusedLine}
470
622
  </div>
471
623
  )
package/src/editor.ts CHANGED
@@ -17,6 +17,9 @@ export {
17
17
  type CommentBoxEdit,
18
18
  type BoxFile,
19
19
  type BoxFileState,
20
+ type BoxUnder,
21
+ type BoxUnderRead,
22
+ type BoxSentUnder,
20
23
  type SendAnswer,
21
24
  type UploadAnswer,
22
25
  } from './CommentBox'