@estiva-app/ui 0.83.0 → 0.84.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,6 +1,6 @@
1
- import { Fragment, 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'
1
+ import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
2
+ import { Extension, type AnyExtension, type EditorOptions } from '@tiptap/core'
3
+ import { Editor, EditorContent, type JSONContent } from '@tiptap/react'
4
4
  import { IconLock, IconPaperclip, IconSquareRounded } from '@tabler/icons-react'
5
5
  import { AttachmentCard } from './AttachmentCard'
6
6
  import { ReferenceNode, type ReferenceViewProps } from './BlockNodes'
@@ -8,7 +8,7 @@ import { Button } from './Button'
8
8
  import { Card } from './Card'
9
9
  import { CardUnder } from './CardUnder'
10
10
  import { cn } from './cn'
11
- import { ComposeBox, ComposeKeys, COMPOSE_EDITOR_CLASSES, isEmptyDoc as isEmpty } from './ComposeBox'
11
+ import { ComposeBox, ComposeKeys, COMPOSE_EDITOR_CLASSES, COMPOSE_SCROLL_CLASSES, isEmptyDoc as isEmpty } from './ComposeBox'
12
12
  import {
13
13
  CaptionedReference,
14
14
  PersonMention,
@@ -29,6 +29,7 @@ import { Kbd } from './Kbd'
29
29
  import { BoxKit, PasteOverWords } from './links'
30
30
  import { WRITING_BOX_CLASSES } from './looks'
31
31
  import { PastedImages } from './PastedImages'
32
+ import { ScrollArea } from './ScrollArea'
32
33
  import { KeptSelection } from './SelectionToolbar'
33
34
  import { isSuggestionOpen } from './suggestionPopup'
34
35
  import { ToolbarButton } from './Toolbar'
@@ -163,6 +164,10 @@ export interface CommentBoxProps {
163
164
  onSent?: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => void
164
165
  /** Called when a send shown at once was refused, so the app takes it back. */
165
166
  onRefused?: () => void
167
+ /** The bar down the text's left edge shows while this holds, besides while an urgent mention is in the box: the app's own marks (a highlight). */
168
+ marked?: (editor: Editor) => boolean
169
+ /** Called with the box's editor once it is drawn, and with `null` as it goes: an app's launcher inserts into the box last used. */
170
+ onEditor?: (editor: Editor | null) => void
166
171
  className?: string
167
172
  }
168
173
 
@@ -205,6 +210,169 @@ const stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): Rea
205
210
  const SQUARE = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
206
211
  const SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />
207
212
 
213
+ /** What the box's editor reads as it runs: the box holding it now, swapped in when a box takes a spare. */
214
+ interface BoxLive {
215
+ edit?: CommentBoxEdit
216
+ people: readonly MentionPerson[]
217
+ references?: CommentBoxProps['references']
218
+ referencesChanged?: CommentBoxProps['referencesChanged']
219
+ referenceIcon?: CommentBoxProps['referenceIcon']
220
+ /** Takes pasted pictures; false when the box takes no files. */
221
+ attach: (files: File[]) => boolean
222
+ }
223
+
224
+ /** One editor's link to the box holding it: the live props, and the `/` sections the box refills every render. */
225
+ interface BoxHold {
226
+ current: BoxLive
227
+ sections: SlashSection[]
228
+ }
229
+
230
+ /** What an app adds to every box's editor: a spare is built only for these. */
231
+ interface BoxApp {
232
+ extensions: readonly AnyExtension[]
233
+ referenceView: ComponentType<ReferenceViewProps> | null
234
+ }
235
+
236
+ const NO_EXTENSIONS: readonly AnyExtension[] = []
237
+ const sameApp = (a: BoxApp, b: BoxApp) =>
238
+ a.referenceView === b.referenceView && a.extensions.length === b.extensions.length && a.extensions.every((one, i) => one === b.extensions[i])
239
+
240
+ function boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {
241
+ const iconFor = (uri: string | null) => hold.current.referenceIcon?.(uri)
242
+ return [
243
+ BoxKit.configure({ link: { openOnClick: false } }),
244
+ PasteOverWords,
245
+ KeptSelection,
246
+ ComposeKeys,
247
+ BoxKeys.configure({
248
+ onEscape: () => {
249
+ const editing = hold.current.edit
250
+ if (!editing) return false
251
+ editing.onCancel()
252
+ return true
253
+ },
254
+ }),
255
+ PersonMention.configure({ people: () => hold.current.people }),
256
+ // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.
257
+ UrgentPersonMention.extend({
258
+ addOptions() {
259
+ const parent = this.parent!()
260
+ return { ...parent, suggestion: { ...parent.suggestion, allow: () => !hold.current.edit } }
261
+ },
262
+ }).configure({ people: () => hold.current.people }),
263
+ CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor }),
264
+ ReferenceTrigger.configure({
265
+ items: () => [],
266
+ sections: (query) => hold.current.references?.(query) ?? [],
267
+ subscribe: (listener) => hold.current.referencesChanged?.(listener) ?? (() => {}),
268
+ ariaLabel: 'References',
269
+ sectionLabel: 'References',
270
+ icon: SQUARE,
271
+ iconFor,
272
+ }),
273
+ SlashCommands.configure({ sections: hold.sections }),
274
+ ReferenceNode.configure({ view: app.referenceView }),
275
+ PastedImages.configure({ onImages: (files: File[]) => hold.current.attach(files) }),
276
+ ...app.extensions,
277
+ ]
278
+ }
279
+
280
+ interface Held {
281
+ editor: Editor
282
+ hold: BoxHold
283
+ destroyAt?: ReturnType<typeof setTimeout>
284
+ }
285
+
286
+ function buildBox(app: BoxApp, options: Partial<EditorOptions>): Held {
287
+ const hold: BoxHold = { current: { people: [], attach: () => false }, sections: [] }
288
+ return { editor: new Editor({ ...options, extensions: boxExtensions(hold, app) }), hold }
289
+ }
290
+
291
+ /*
292
+ A box's editor, built ahead, as Peek's composer has been since 4ef41d41:
293
+ building one (schema, commands, view) is the longest single step in drawing
294
+ a box. One is built while the page is idle for the app `keepCommentBoxWarm`
295
+ names, and the next empty box with those extensions takes it and builds the
296
+ next; any other box builds its own on the spot.
297
+ */
298
+ let warmApp: BoxApp | null = null
299
+ let spare: Held | null = null
300
+ let sparing = false
301
+
302
+ function scheduleSpare() {
303
+ if (!warmApp || spare || sparing || typeof window === 'undefined' || !window.requestIdleCallback) return
304
+ sparing = true
305
+ window.requestIdleCallback(() => {
306
+ sparing = false
307
+ // No autofocus: it would fire on the detached spare. The box that takes it focuses it.
308
+ if (warmApp && !spare) spare = buildBox(warmApp, { autofocus: false })
309
+ })
310
+ }
311
+
312
+ /** Keeps an editor built ahead for the next empty box given these `extensions` and `referenceView`, so it opens at once. */
313
+ export function keepCommentBoxWarm(app: { extensions?: readonly AnyExtension[]; referenceView?: ComponentType<ReferenceViewProps> } = {}): void {
314
+ const next = { extensions: app.extensions ?? NO_EXTENSIONS, referenceView: app.referenceView ?? null }
315
+ if (warmApp && sameApp(warmApp, next)) return
316
+ warmApp = next
317
+ spare?.editor.destroy()
318
+ spare = null
319
+ scheduleSpare()
320
+ }
321
+
322
+ /** `useEditor` with no deps, taking a spare when one fits: built once, given the latest `editorProps`, destroyed when the box goes. */
323
+ function useBoxEditor(app: BoxApp, content: JSONContent | undefined, options: Pick<EditorOptions, 'editable' | 'editorProps'>): Held {
324
+ const args = useRef({ app, content, options })
325
+ args.current = { app, content, options }
326
+ const [held, setHeld] = useState(() => {
327
+ const fits = !content && spare && !spare.editor.isDestroyed && warmApp && sameApp(warmApp, app)
328
+ const taken = fits ? spare : null
329
+ if (taken) {
330
+ spare = null
331
+ taken.editor.setOptions(options)
332
+ }
333
+ const one = taken ?? buildBox(app, { ...options, content })
334
+ // A render thrown away never mounts: what it built goes with it. Later than React lets a transition run (5 s).
335
+ one.destroyAt = setTimeout(() => one.editor.destroy(), 10_000)
336
+ scheduleSpare()
337
+ return one
338
+ })
339
+ // Mounted, it is this box's until it unmounts — and not remounted at once, as in StrictMode.
340
+ useLayoutEffect(() => {
341
+ clearTimeout(held.destroyAt)
342
+ /*
343
+ Shown again after React kept its state but ran this cleanup (a Suspense boundary
344
+ that suspended again, an <Activity> that hid it): the editor went, so build one
345
+ from what the box would open with now — its draft holds what was typed.
346
+ */
347
+ if (held.editor.isDestroyed) {
348
+ const { app: now, content: opening, options: current } = args.current
349
+ setHeld(buildBox(now, { ...current, content: opening }))
350
+ return
351
+ }
352
+ return () => {
353
+ held.destroyAt = setTimeout(() => held.editor.destroy(), 1)
354
+ }
355
+ }, [held])
356
+ // The attributes are what changes after it is built: the label.
357
+ const props = useRef(options.editorProps)
358
+ props.current = options.editorProps
359
+ const attributes = JSON.stringify(options.editorProps.attributes ?? {})
360
+ useEffect(() => {
361
+ if (!held.editor.isDestroyed) held.editor.setOptions({ editorProps: props.current })
362
+ }, [held, attributes])
363
+ return held
364
+ }
365
+
366
+ /** Whether the document holds an urgent mention: the box draws its bar while one is in it. */
367
+ const holdsUrgent = (editor: Editor): boolean => {
368
+ let found = false
369
+ editor.state.doc.descendants((node) => {
370
+ if (node.type.name === 'urgentMention') found = true
371
+ return !found
372
+ })
373
+ return found
374
+ }
375
+
208
376
  let fileCount = 0
209
377
 
210
378
  export function CommentBox({
@@ -225,10 +393,12 @@ export function CommentBox({
225
393
  accept,
226
394
  closed,
227
395
  referenceView,
228
- extensions = [],
396
+ extensions = NO_EXTENSIONS,
229
397
  autoFocus,
230
398
  onSent,
231
399
  onRefused,
400
+ marked,
401
+ onEditor,
232
402
  className,
233
403
  }: CommentBoxProps) {
234
404
  const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])
@@ -239,9 +409,9 @@ export function CommentBox({
239
409
  const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set())
240
410
  const picker = useRef<HTMLInputElement>(null)
241
411
  const root = useRef<HTMLDivElement>(null)
242
- // The latest props, for the editor's callbacks, which are made once.
243
- const latest = useRef({ edit, people, references, referencesChanged, referenceIcon, upload, draft, under })
244
- latest.current = { edit, people, references, referencesChanged, referenceIcon, upload, draft, under }
412
+ // The latest props, for callbacks made once.
413
+ const latest = useRef({ edit, upload, draft, under })
414
+ latest.current = { edit, upload, draft, under }
245
415
  const save = useRef<() => boolean>(() => false)
246
416
 
247
417
  const attachFiles = useCallback((picked: File[]): boolean => {
@@ -264,53 +434,36 @@ export function CommentBox({
264
434
 
265
435
  // An edit cannot add a file or make a mention urgent, as in every app before the box; no upload, no File.
266
436
  const rows = insert.filter((c) => !((edit || !upload) && c.key === commentBoxRows.file.key) && !(edit && c.key === commentBoxRows.urgent.key))
267
- // `/` reads its sections each time it opens, from this one array: refilled every render, so a row that
268
- // comes or goes with `upload`, `insert` or `code` after the box opened is offered as it is now.
269
- const sections = useRef<SlashSection[]>([]).current
270
- sections.splice(0, sections.length, formatSection(code), ...(rows.length > 0 ? [{ label: 'Insert', commands: rows }] : []))
271
- const iconFor = useCallback((uri: string | null) => latest.current.referenceIcon?.(uri), [])
272
-
273
- const editor = useEditor({
274
- extensions: [
275
- BoxKit.configure({ link: { openOnClick: false } }),
276
- PasteOverWords,
277
- KeptSelection,
278
- ComposeKeys,
279
- BoxKeys.configure({
280
- onEscape: () => {
281
- const editing = latest.current.edit
282
- if (!editing) return false
283
- editing.onCancel()
284
- return true
285
- },
286
- }),
287
- PersonMention.configure({ people: () => latest.current.people }),
288
- // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.
289
- UrgentPersonMention.extend({
290
- addOptions() {
291
- const parent = this.parent!()
292
- return { ...parent, suggestion: { ...parent.suggestion, allow: () => !latest.current.edit } }
293
- },
294
- }).configure({ people: () => latest.current.people }),
295
- CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor }),
296
- ReferenceTrigger.configure({
297
- items: () => [],
298
- sections: (query) => latest.current.references?.(query) ?? [],
299
- subscribe: (listener) => latest.current.referencesChanged?.(listener) ?? (() => {}),
300
- ariaLabel: 'References',
301
- sectionLabel: 'References',
302
- icon: SQUARE,
303
- iconFor,
304
- }),
305
- SlashCommands.configure({ sections }),
306
- ReferenceNode.configure({ view: referenceView ?? null }),
307
- PastedImages.configure({ onImages: attachFiles }),
308
- ...extensions,
309
- ],
310
- content: edit?.body ?? draft?.read(),
437
+ const { editor, hold } = useBoxEditor({ extensions, referenceView: referenceView ?? null }, edit?.body ?? draft?.read(), {
311
438
  editable: !closed,
312
439
  editorProps: { attributes: { class: COMPOSE_EDITOR_CLASSES, role: 'textbox', 'aria-multiline': 'true', 'aria-label': label } },
313
440
  })
441
+ // The editor's callbacks are made once, with the editor: they read this box's latest props through its hold.
442
+ hold.current = { edit, people, references, referencesChanged, referenceIcon, attach: attachFiles }
443
+ // `/` reads its sections each time it opens, from this one array: refilled every render, so a row that
444
+ // comes or goes with `upload`, `insert` or `code` after the box opened is offered as it is now.
445
+ hold.sections.splice(0, hold.sections.length, formatSection(code), ...(rows.length > 0 ? [{ label: 'Insert', commands: rows }] : []))
446
+
447
+ // The bar down the text's left edge, while an urgent mention or the app's own mark is in the box.
448
+ const [marking, setMarking] = useState(false)
449
+ const markedBy = useRef(marked)
450
+ markedBy.current = marked
451
+ // Before paint: an edit or a draft opening with an urgent mention draws its bar in its first frame.
452
+ useLayoutEffect(() => {
453
+ const read = () => setMarking(holdsUrgent(editor) || !!markedBy.current?.(editor))
454
+ read()
455
+ editor.on('update', read)
456
+ return () => {
457
+ editor.off('update', read)
458
+ }
459
+ }, [editor])
460
+
461
+ const handOut = useRef(onEditor)
462
+ handOut.current = onEditor
463
+ useEffect(() => {
464
+ handOut.current?.(editor)
465
+ return () => handOut.current?.(null)
466
+ }, [editor])
314
467
 
315
468
  // Drafts: every change is kept, and an empty box is no draft.
316
469
  useEffect(() => {
@@ -508,7 +661,11 @@ export function CommentBox({
508
661
  return (
509
662
  <div className={cn('flex flex-col gap-1', className)}>
510
663
  <div className={cn(WRITING_BOX_CLASSES, 'focus-within:border-border-strong transition-colors', sending && '[&_.ProseMirror]:text-text-muted')}>
511
- <EditorContent editor={editor} />
664
+ <div data-composer-editor data-marked={marking || undefined} className={cn('relative min-h-[20px]', marking && 'border-l-4 border-border-strong pl-2')}>
665
+ <ScrollArea className={COMPOSE_SCROLL_CLASSES.area} viewportClassName={COMPOSE_SCROLL_CLASSES.viewport} contentClassName={COMPOSE_SCROLL_CLASSES.content}>
666
+ <EditorContent editor={editor} />
667
+ </ScrollArea>
668
+ </div>
512
669
  {fileCards && <div className="flex flex-wrap gap-2">{fileCards}</div>}
513
670
  <div className="flex items-center justify-between gap-2">
514
671
  <span className="flex items-center gap-1 text-caption text-text-muted">
@@ -553,6 +710,7 @@ export function CommentBox({
553
710
  }
554
711
  attachments={fileCards}
555
712
  ready={ready}
713
+ marked={marking}
556
714
  holding={uploading || failed > 0 || sending}
557
715
  selection={{ link: true }}
558
716
  className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}
@@ -6,6 +6,7 @@ import { IconButton } from './IconButton'
6
6
  import { Toolbar } from './Toolbar'
7
7
  import { cn } from './cn'
8
8
  import { richTextClassName } from './RichText'
9
+ import { ScrollArea } from './ScrollArea'
9
10
  import { WRITING_BOX_CLASSES } from './looks'
10
11
  import { SelectionToolbar, type SelectionToolbarProps } from './SelectionToolbar'
11
12
  import { isSuggestionActive } from './suggestionPopup'
@@ -19,8 +20,22 @@ import { isSuggestionActive } from './suggestionPopup'
19
20
  */
20
21
 
21
22
  /** The editor's own classes inside the box: Peek's, rich text with no outline. Put them in `editorProps.attributes.class`. */
23
+ /** The classes the box's editor wears: rich text with no outline. It never scrolls itself; the box does, in a `ScrollArea`. */
22
24
  export const COMPOSE_EDITOR_CLASSES = richTextClassName('default', 'outline-none w-full bg-transparent min-h-[20px] [&>p+p]:-mt-1')
23
25
 
26
+ /**
27
+ * A long draft stops at half the window and scrolls inside the box, so its
28
+ * first line can be reached (PEE-59). The package's `ScrollArea` scrolls it,
29
+ * not the browser: its bar, and one that shows while there is more (Katerina,
30
+ * 21 Oct: the browser's bar, and none at all in some browsers).
31
+ *
32
+ * The region reaches into the box's right padding (the box's `p-3`) and its
33
+ * content gives it back, so the text ends where it did and the bar sits 3px
34
+ * from the box's edge, as every other box's bar does (Katerina, 21 Oct: the gap
35
+ * on the right; measured 15px before, 3px after).
36
+ */
37
+ export const COMPOSE_SCROLL_CLASSES = { area: '-mr-3', viewport: 'max-h-[50vh]', content: 'pr-3' }
38
+
24
39
  type ComposeKeysStorage = { send: (() => boolean) | null }
25
40
 
26
41
  /**
@@ -137,8 +152,10 @@ export function ComposeBox({ editor, onSend, placeholder, tools, attachments, re
137
152
  return (
138
153
  <div className={cn('relative', className)}>
139
154
  <div className={cn(WRITING_BOX_CLASSES, 'focus-within:border-border-strong transition-colors')}>
140
- <div data-composer-editor className={cn('relative min-h-[20px] transition-all', marked && 'border-l-4 border-border-strong pl-2')}>
141
- <EditorContent editor={editor} />
155
+ <div data-composer-editor data-marked={marked || undefined} className={cn('relative min-h-[20px] transition-all', marked && 'border-l-4 border-border-strong pl-2')}>
156
+ <ScrollArea className={COMPOSE_SCROLL_CLASSES.area} viewportClassName={COMPOSE_SCROLL_CLASSES.viewport} contentClassName={COMPOSE_SCROLL_CLASSES.content}>
157
+ <EditorContent editor={editor} />
158
+ </ScrollArea>
142
159
  <SelectionToolbar editor={editor} {...selection} />
143
160
  {empty && (
144
161
  <div className="pointer-events-none absolute inset-0 flex flex-wrap items-center gap-1 text-body-2 text-text-muted">{placeholder}</div>
package/src/links.ts CHANGED
@@ -43,7 +43,10 @@ export const PasteOverWords = Extension.create({
43
43
  return false
44
44
  })
45
45
  if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
46
- view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })))
46
+ // The caret goes after the link: left selected, the words open the selection strip's Link field,
47
+ // which takes focus and the next Enter, so a box needed two to send (COMM-8).
48
+ const tr = state.tr.addMark(from, to, schema.marks.link.create({ href: url }))
49
+ view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to)).removeStoredMark(schema.marks.link))
47
50
  return true
48
51
  }
49
52
  const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '')