@estiva-app/ui 0.82.1 → 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.
Files changed (44) hide show
  1. package/dist/BlockNodes.d.ts +16 -5
  2. package/dist/BlockNodes.d.ts.map +1 -1
  3. package/dist/CommentBox.d.ts +11 -2
  4. package/dist/CommentBox.d.ts.map +1 -1
  5. package/dist/ComposeBox.d.ts +17 -0
  6. package/dist/ComposeBox.d.ts.map +1 -1
  7. package/dist/DocumentEditor.d.ts +5 -4
  8. package/dist/DocumentEditor.d.ts.map +1 -1
  9. package/dist/LinkPlaces.d.ts +51 -0
  10. package/dist/LinkPlaces.d.ts.map +1 -0
  11. package/dist/ReferenceMenu.d.ts.map +1 -1
  12. package/dist/editor.d.ts +1 -0
  13. package/dist/editor.d.ts.map +1 -1
  14. package/dist/editor.js +392 -178
  15. package/dist/editor.js.map +4 -4
  16. package/dist/linked.examples.d.ts.map +1 -1
  17. package/dist/links.d.ts.map +1 -1
  18. package/package.json +1 -1
  19. package/registry.json +75 -12
  20. package/src/BlockNodes.tsx +36 -9
  21. package/src/CommentBox.mdx +11 -1
  22. package/src/CommentBox.stories.tsx +75 -2
  23. package/src/CommentBox.test.tsx +170 -3
  24. package/src/CommentBox.tsx +211 -53
  25. package/src/ComposeBox.tsx +19 -2
  26. package/src/DocumentEditor.mdx +7 -2
  27. package/src/DocumentEditor.stories.tsx +101 -15
  28. package/src/DocumentEditor.test.tsx +49 -0
  29. package/src/DocumentEditor.tsx +17 -10
  30. package/src/LinkPlaces.mdx +59 -0
  31. package/src/LinkPlaces.stories.tsx +60 -0
  32. package/src/LinkPlaces.test.ts +134 -0
  33. package/src/LinkPlaces.ts +169 -0
  34. package/src/ReferenceCards.mdx +4 -0
  35. package/src/ReferenceMenu.mdx +32 -24
  36. package/src/ReferenceMenu.stories.tsx +15 -16
  37. package/src/ReferenceMenu.test.tsx +161 -57
  38. package/src/ReferenceMenu.tsx +48 -44
  39. package/src/editor.ts +1 -0
  40. package/src/linked.examples.ts +4 -3
  41. package/src/links.ts +4 -1
  42. package/src/pages.test.ts +2 -2
  43. package/src/registry/registry.test.ts +6 -6
  44. package/stories/Choosing.mdx +3 -2
@@ -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>
@@ -17,6 +17,9 @@ One document's text as one surface that is always an editor, the same in every a
17
17
  - `onCommentOnSelection` to offer Comment on what is selected, and draw where comments are. Without it, neither.
18
18
  - `blockRows` for the app's rows in a block's menu: Copy link, Comment on the block.
19
19
  - `readOnly` for reading: the same drawing, nothing typed or saved. Chips open, and Comment on a selection stays where it is on.
20
+ - `referenceView` for links: the app's chip, row or card, by `place`.
21
+
22
+ <Canvas of={DocumentEditorStories.Links} />
20
23
 
21
24
  <Canvas of={DocumentEditorStories.WithFiles} />
22
25
 
@@ -53,7 +56,7 @@ const codec: DocumentCodec = {
53
56
  references={{ sections: sectionsFor, ariaLabel: 'Items', sectionLabel: 'Items' }}
54
57
  mentions={{ people: () => people, uriOf: (person) => `nostr:${encodeNpub(person.pubkey)}` }}
55
58
  upload={uploadOne}
56
- referenceView={chipView}
59
+ referenceView={linkView}
57
60
  attachmentView={fileView}
58
61
  onCommit={async (value, contentFormat, editedFrom) => {
59
62
  const adds = mentionAddsFor(me, Date.now(), {
@@ -73,7 +76,8 @@ const codec: DocumentCodec = {
73
76
  - **`label` is required**: the editor's accessible name.
74
77
  - **Give the editor a `key` per document.** The editor and which of `[`, `@`, File, comments and markdown it has are made once, as it opens; the lists, the upload and the people are read as they are each time.
75
78
  - **`hold` is the app's held-typing store.** `register` must not forget what is held when it is called again for the same key during an ending; the editor registers once per `holdKey`.
76
- - **The cards a chip asks for** are drawn by the app's `cards`, after the text, until the kit has its own.
79
+ - **A link draws where it sits** (**LinkPlaces**): `referenceView` is handed `place` — `chip` in a sentence, `row` alone on its line, `card` in the row's place — and draws the kit's **LinkChip**, **LinkRow** or **LinkCard** for what it names. While `editing`, give the chip and row no hover preview: a click opens the link's menu. A person or a Folder alone on its line is a `chip`.
80
+ - **A link's menu** (**ReferenceMenu**) offers Open, and alone on its line Show as Row or Card; it opens by itself after a paste or a `[` pick on a line of its own.
77
81
 
78
82
  ## What it owns
79
83
 
@@ -90,6 +94,7 @@ It does these by itself. Write none of them around it.
90
94
  | A URL pasted over plain words links them; typing after linked words is not linked; a link keeps the keys this version does not know | a paste handler, a link schema |
91
95
  | A bare address drawn as a link, opened by a click, and saved as the text it is | a link decoration |
92
96
  | Each block's id through editing, so what is anchored to it stays on it | an id plugin |
97
+ | Where each link sits — chip, row, or card in the row's place — kept current as you type, and its menu: Open, Show as Row or Card | a line rule, a card slot, a link menu |
93
98
  | A pasted picture uploaded and placed; the file dialog's blur is not leaving | an upload state |
94
99
  | Read only: no caret, no `/`, `[` or `@`, no format buttons; still focusable, so a selection's Comment shows | a reading view |
95
100
 
@@ -1,9 +1,9 @@
1
1
  import type { Meta, StoryObj } from '@storybook/react-vite'
2
- import { useEffect, useRef, useState } from 'react'
2
+ import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
3
3
  import type { Editor } from '@tiptap/react'
4
4
  import type { JSONContent } from '@tiptap/react'
5
5
  import { IconSquareRounded } from '@tabler/icons-react'
6
- import { descriptionTextToBlockDocument, documentForEditing, encodeNpub, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
6
+ import { descriptionTextToBlockDocument, documentForEditing, encodeNaddr, encodeNpub, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
7
7
  import { newlyNamedPeople } from '@estiva-app/conversation'
8
8
  import { AttachmentCard } from './AttachmentCard'
9
9
  import type { HandleBlock } from './BlockHandle'
@@ -13,6 +13,11 @@ import { setCommentAnchors, type CommentAnchor, type SelectionAnchor } from './C
13
13
  import type { CaptionedItem, MentionPerson, ReferenceSection } from './ComposerTriggers'
14
14
  import { DocumentEditor, type DocumentCodec, type DocumentEditorProps, type HeldTyping } from './DocumentEditor'
15
15
  import { InlineChip } from './InlineChip'
16
+ import { LinkCard } from './LinkCard'
17
+ import { LinkChip } from './LinkChip'
18
+ import { LinkRow } from './LinkRow'
19
+ import type { Linked } from './linked'
20
+ import { GROUP, ITEM, ITEM_NO_SUMMARY, ready } from './linked.examples'
16
21
  import { MenuItem } from './Menu'
17
22
 
18
23
  /**
@@ -45,23 +50,73 @@ const npubOf = (person: MentionPerson) => (person.pubkey ? `nostr:${encodeNpub(p
45
50
  const nameOfKey = (key: string) => PEOPLE.find((person) => person.pubkey === key)?.name ?? 'Someone'
46
51
 
47
52
  const APP_LINK = 'https://app.example/item/one'
48
- const ITEMS: CaptionedItem[] = ['one', 'two', 'three'].map((n) => ({ id: `item-${n}`, label: `Item ${n}`, snippet: '', uri: `nostr:naddr1item${n}` }))
53
+ const APP_GROUP_LINK = 'https://app.example/group/one'
54
+ const naddr = (kind: number, identifier: string) => `nostr:${encodeNaddr({ kind, pubkey: 'a'.repeat(64), identifier, relays: [] })}`
55
+ /** What the app resolves each address to: the link kit's placeholder items and a group with a key. */
56
+ const LINKED: { uri: string; linked: Linked }[] = [
57
+ { uri: naddr(30851, 'item-one'), linked: { ...ITEM, title: 'Item one' } },
58
+ { uri: naddr(30851, 'item-two'), linked: ITEM_NO_SUMMARY },
59
+ { uri: naddr(30850, 'group-one'), linked: { ...GROUP, key: 'ABC' } },
60
+ ]
61
+ /** A place that holds items: alone on its line it stays a chip. */
62
+ const PLACE_URI = naddr(39000, 'place-one')
63
+ const ITEMS: CaptionedItem[] = LINKED.map(({ uri, linked }) => ({ id: linked.id, label: linked.title, snippet: '', uri }))
49
64
  const sections = (query: string): ReferenceSection[] => [{ label: 'Items', items: ITEMS.filter((item) => item.label.toLowerCase().includes(query.toLowerCase())) }]
50
- const linkChips = { referenceOf: (url: string) => (url === APP_LINK ? ITEMS[0].uri : undefined), ask: null, limit: 24 }
65
+ const APP_LINKS = new Map([
66
+ [APP_LINK, LINKED[0].uri],
67
+ [APP_GROUP_LINK, LINKED[2].uri],
68
+ ])
69
+ const linkChips = { referenceOf: (url: string) => APP_LINKS.get(url), ask: null, limit: 24 }
51
70
 
52
71
  const SQUARE = <IconSquareRounded size={14} stroke={1.5} />
53
72
  const ROW_ICON = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
54
73
 
55
- /** A chip as the app draws it: a person by name, an item by its label; it opens where it leads. */
56
- function Chip({ uri, href }: ReferenceViewProps) {
74
+ /** The app's side of a card's status and owner: a change from the card is kept here, and every drawing of it reads it back. */
75
+ const picked = new Map<string, { status?: string; owner?: string }>()
76
+ const pickListeners = new Set<() => void>()
77
+ let pickVersion = 0
78
+ function pick(uri: string, change: { status?: string; owner?: string }) {
79
+ picked.set(uri, { ...picked.get(uri), ...change })
80
+ pickVersion++
81
+ for (const listener of pickListeners) listener()
82
+ }
83
+ const subscribePicks = (listener: () => void) => {
84
+ pickListeners.add(listener)
85
+ return () => void pickListeners.delete(listener)
86
+ }
87
+
88
+ /** What `uri` names, with its status and owner as last picked; undefined for what the app does not know. */
89
+ function useLinked(uri: string): Linked | undefined {
90
+ useSyncExternalStore(subscribePicks, () => pickVersion)
91
+ const found = LINKED.find((one) => one.uri === uri)?.linked
92
+ if (!found) return undefined
93
+ const now = picked.get(uri)
94
+ return {
95
+ ...found,
96
+ ...(found.status && { status: { ...found.status, value: now?.status ?? found.status.value, onChange: (status: string) => pick(uri, { status }) } }),
97
+ ...(found.owner && { owner: { ...found.owner, value: now?.owner ?? found.owner.value, onChange: (owner: string) => pick(uri, { owner }) } }),
98
+ }
99
+ }
100
+
101
+ /**
102
+ * A link as the app draws it, where it sits: a person by name; an item as the
103
+ * link kit's chip, row or card. While editing, a click is the menu's, so a
104
+ * chip or row shows no hover card.
105
+ */
106
+ function Chip({ uri, href, place = 'chip', editing = false }: ReferenceViewProps) {
107
+ const linked = useLinked(uri)
57
108
  const person = PEOPLE.find((one) => npubOf(one) === uri)
58
- if (person) return <InlineChip tone="person">{`@${person.name}`}</InlineChip>
59
- const item = ITEMS.find((one) => one.uri === uri)
60
- return (
61
- <InlineChip icon={SQUARE} href={href ?? 'https://example.com/item'} target="_blank" rel="noreferrer">
62
- {item?.label ?? 'Item'}
63
- </InlineChip>
64
- )
109
+ if (person) return <InlineChip tone="person" href={`#${person.id}`}>{`@${person.name}`}</InlineChip>
110
+ if (!linked) {
111
+ return (
112
+ <InlineChip icon={SQUARE} href={href ?? 'https://example.com/item'} target="_blank" rel="noreferrer">
113
+ {uri === PLACE_URI ? 'Place one' : 'Item'}
114
+ </InlineChip>
115
+ )
116
+ }
117
+ if (place === 'card') return <LinkCard link={ready(linked)} />
118
+ if (place === 'row') return <LinkRow link={ready(linked)} preview={!editing} />
119
+ return <LinkChip link={ready(linked)} preview={!editing} />
65
120
  }
66
121
 
67
122
  function PlacedFile({ attrs }: AttachmentViewProps) {
@@ -99,6 +154,24 @@ const START = JSON.stringify({
99
154
  ],
100
155
  })
101
156
 
157
+ const reference = (uri: string, embed?: string) => ({ type: 'text', text: uri, marks: [{ type: 'reference', attrs: { uri, ...(embed ? { embed } : {}) } }] })
158
+ const lone = (id: string, uri: string, embed?: string) => ({ type: 'paragraph', id, content: [reference(uri, embed)] })
159
+
160
+ /** Links where they sit: in a sentence, alone on a line, alone with its card chosen, and a person and a place alone. */
161
+ const LINKS_START = JSON.stringify({
162
+ type: 'doc',
163
+ content: [
164
+ { type: 'paragraph', id: 'l1', content: [{ type: 'text', text: 'A sentence that names ' }, reference(LINKED[0].uri), { type: 'text', text: ' in passing.' }] },
165
+ lone('l2', LINKED[2].uri),
166
+ lone('l3', LINKED[0].uri, 'detailed'),
167
+ lone('l4', LINKED[1].uri),
168
+ lone('l5', `nostr:${encodeNpub(PEOPLE[0].pubkey!)}`),
169
+ lone('l6', PLACE_URI),
170
+ { type: 'paragraph', id: 'l7', content: [{ type: 'text', text: `On an empty line, paste ${APP_GROUP_LINK} or type [.` }] },
171
+ { type: 'paragraph', id: 'l8', content: [] },
172
+ ],
173
+ })
174
+
102
175
  /** An app's held-typing store: what each open editor holds is read when the sign-in ends. */
103
176
  function heldStore() {
104
177
  const held = new Map<string, string>()
@@ -156,11 +229,13 @@ type Bench = Pick<DocumentEditorProps, 'readOnly' | 'upload' | 'linkChips' | 're
156
229
  comments?: boolean
157
230
  /** The block handle's rows: Copy link, and Comment on the block. */
158
231
  rows?: boolean
232
+ /** The saved document it opens on. */
233
+ start?: string
159
234
  }
160
235
 
161
236
  /** The editor and the app around it. */
162
- function Workbench({ lists = true, comments = false, rows = false, readOnly = false, ...rest }: Bench) {
163
- const [value, setValue] = useState(START)
237
+ function Workbench({ lists = true, comments = false, rows = false, readOnly = false, start = START, ...rest }: Bench) {
238
+ const [value, setValue] = useState(start)
164
239
  const [changedBy, setChangedBy] = useState<{ name: string } | null>(null)
165
240
  const [opened, setOpened] = useState(0)
166
241
  const [signedIn, setSignedIn] = useState(true)
@@ -289,6 +364,17 @@ export const WithFiles: Story = {
289
364
  render: () => <Workbench rows upload={upload} linkChips={linkChips} readMarkdown={readMarkdown} />,
290
365
  }
291
366
 
367
+ /**
368
+ * Links where they sit: a chip in a sentence, a row alone on its line, and the
369
+ * card in the row's place. Click a link for its menu: Open, and alone on its
370
+ * line Show as Row or Card. A person or a place alone stays a chip, and its
371
+ * menu has Open only. On an empty line, a pasted link or a `[` pick opens the
372
+ * menu by itself. A card's status and owner change from the card.
373
+ */
374
+ export const Links: Story = {
375
+ render: () => <Workbench start={LINKS_START} linkChips={linkChips} />,
376
+ }
377
+
292
378
  /** Nothing of the app's but its chips: no `[`, no `@`, no rows, no comments. */
293
379
  export const Plain: Story = {
294
380
  render: () => <Workbench lists={false} linkChips={linkChips} />,
@@ -501,6 +501,55 @@ describe('blocks', () => {
501
501
  })
502
502
  })
503
503
 
504
+ describe('a link, by where it sits', () => {
505
+ const run = (uri: string, embed?: string) => ({ type: 'text', text: uri, marks: [{ type: 'reference', attrs: { uri, ...(embed ? { embed } : {}) } }] })
506
+ /** The app's drawing of a link: says where it sits. */
507
+ const Placed = ({ uri, place }: { uri: string; place?: string }) => (
508
+ <a href={`/o/${uri}`} data-place={place ?? 'none'} onClick={(event) => event.preventDefault()}>
509
+ Item
510
+ </a>
511
+ )
512
+ const places = () => [...document.querySelectorAll('[data-place]')].map((el) => el.getAttribute('data-place'))
513
+
514
+ it('draws as its row alone on its line, its chip in a sentence, and its card in the row\'s place once chosen', async () => {
515
+ const value = doc(
516
+ { type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] },
517
+ { type: 'paragraph', id: 'a2', content: [{ type: 'text', text: 'See ' }, run(ITEM_URI)] },
518
+ { type: 'paragraph', id: 'a3', content: [run(ITEM_URI, 'detailed')] },
519
+ )
520
+ render(<Doc value={value} referenceView={Placed} />)
521
+ await screen.findAllByRole('link', { name: 'Item' })
522
+ expect(places()).toEqual(['row', 'chip', 'card'])
523
+ })
524
+
525
+ it('turns from its row into its chip as words are typed before it, and back when they are taken away', async () => {
526
+ render(<Doc value={doc({ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] })} referenceView={Placed} />)
527
+ await screen.findByRole('link', { name: 'Item' })
528
+ expect(places()).toEqual(['row'])
529
+ await act(async () => editorOf().chain().focus().insertContentAt(1, 'See ').run())
530
+ expect(places()).toEqual(['chip'])
531
+ await act(async () => editorOf().chain().focus().deleteRange({ from: 1, to: 5 }).run())
532
+ expect(places()).toEqual(['row'])
533
+ })
534
+
535
+ it('Show as Card on a lone link saves its card, and Show as Row saves it without one', async () => {
536
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
537
+ render(<Doc value={doc({ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] })} referenceView={Placed} onCommit={onCommit} />)
538
+ const choose = async (label: 'Row' | 'Card') => {
539
+ await act(async () => editorOf().view.focus())
540
+ fireEvent.click(await screen.findByRole('link', { name: 'Item' }))
541
+ fireEvent.mouseDown(await screen.findByRole('menuitemradio', { name: label }))
542
+ await leave()
543
+ }
544
+ await choose('Card')
545
+ expect(places()).toEqual(['card'])
546
+ expect(saved(onCommit.mock.calls[0][0])[0].runs[0].marks).toEqual([{ type: 'reference', attrs: { uri: ITEM_URI, embed: 'detailed' } }])
547
+ await choose('Row')
548
+ expect(places()).toEqual(['row'])
549
+ expect(saved(onCommit.mock.calls[1][0])[0].runs[0].marks).toEqual([{ type: 'reference', attrs: { uri: ITEM_URI } }])
550
+ })
551
+ })
552
+
504
553
  describe('reading', () => {
505
554
  it('read only, nothing can be typed or saved, and the text is drawn the same', async () => {
506
555
  const onCommit = vi.fn(async () => true)