@estiva-app/ui 0.80.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])
@@ -314,14 +440,17 @@ export function CommentBox({
314
440
  (ed: Editor): boolean => {
315
441
  const body = ed.getJSON()
316
442
  const sent = files.filter((f) => f.state === 'ready')
443
+ const sentUnder = underOf(body)
317
444
  setRefused(null)
318
445
  const answered = (answer: Promise<SendAnswer>) => answer.catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
319
446
  if (showsAtOnce) {
320
- // 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
321
450
  setFiles((all) => all.filter((f) => f.state !== 'ready'))
322
451
  draft?.clear()
323
- onSent?.(body, sent)
324
- void answered(send(body, sent)).then((answer) => {
452
+ onSent?.(body, sent, sentUnder)
453
+ void answered(send(body, sent, sentUnder)).then((answer) => {
325
454
  if (answer.accepted) return
326
455
  onRefused?.()
327
456
  if (ed.isDestroyed) {
@@ -332,6 +461,7 @@ export function CommentBox({
332
461
  if (isEmpty(ed)) ed.commands.setContent(body)
333
462
  else ed.commands.insertContentAt(0, body.content ?? [])
334
463
  ed.commands.focus('end')
464
+ setRemoved((now) => new Set([...now, ...took]))
335
465
  setFiles((all) => [...sent, ...all])
336
466
  setRefused(answer.reason)
337
467
  })
@@ -339,28 +469,30 @@ export function CommentBox({
339
469
  }
340
470
  // Held: the words stay, shut, until the relay answers.
341
471
  setSending(true)
342
- void answered(send(body, sent)).then((answer) => {
472
+ void answered(send(body, sent, sentUnder)).then((answer) => {
343
473
  setSending(false)
344
474
  if (!answer.accepted) {
345
475
  setRefused(answer.reason)
346
476
  return
347
477
  }
348
478
  if (!ed.isDestroyed) ed.commands.clearContent(true)
479
+ setRemoved(new Set())
349
480
  setFiles((all) => all.filter((f) => !sent.includes(f)))
350
481
  draft?.clear()
351
- onSent?.(body, sent)
482
+ onSent?.(body, sent, sentUnder)
352
483
  })
353
484
  return false
354
485
  },
355
- [files, showsAtOnce, send, draft, onSent, onRefused],
486
+ [files, removed, underOf, showsAtOnce, send, draft, onSent, onRefused],
356
487
  )
357
488
 
358
489
  save.current = () => {
359
490
  if (!editor || !edit || sending || uploading) return true
360
491
  setRefused(null)
361
492
  setSending(true)
493
+ const body = editor.getJSON()
362
494
  void edit
363
- .onSave(editor.getJSON(), files)
495
+ .onSave(body, files, underOf(body))
364
496
  .catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
365
497
  .then((answer) => {
366
498
  setSending(false)
@@ -407,6 +539,19 @@ export function CommentBox({
407
539
  </>
408
540
  ) : undefined
409
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
+
410
555
  const refusedLine = refused && (
411
556
  <FieldLine tone="error">
412
557
  {edit ? `Not saved: ${refused}. Your changes are still in the box.` : `Not sent: ${refused}. Your text is back in the box.`}
@@ -433,7 +578,9 @@ export function CommentBox({
433
578
  </div>
434
579
  </div>
435
580
  </div>
436
- {sending && <FieldLine>Saving…</FieldLine>} {refusedLine}
581
+ {underBox}
582
+ {sending && <FieldLine>Saving…</FieldLine>}
583
+ {refusedLine}
437
584
  </div>
438
585
  )
439
586
  }
@@ -464,6 +611,7 @@ export function CommentBox({
464
611
  selection={{ link: true }}
465
612
  className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}
466
613
  />
614
+ {underBox}
467
615
  {upload && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}
468
616
  {sending && <FieldLine>Sending…</FieldLine>}
469
617
  {uploading && !sending && <FieldLine>Uploading… Send waits for the file.</FieldLine>}
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'