@estiva-app/ui 0.91.1 → 0.92.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 (108) hide show
  1. package/dist/AppProvider.d.ts +7 -3
  2. package/dist/AppProvider.d.ts.map +1 -1
  3. package/dist/AttachedCard.d.ts +5 -1
  4. package/dist/AttachedCard.d.ts.map +1 -1
  5. package/dist/BlockNodes.d.ts +14 -1
  6. package/dist/BlockNodes.d.ts.map +1 -1
  7. package/dist/CommentBox.d.ts +9 -2
  8. package/dist/CommentBox.d.ts.map +1 -1
  9. package/dist/ComposerTriggers.d.ts +11 -2
  10. package/dist/ComposerTriggers.d.ts.map +1 -1
  11. package/dist/DocumentEditor.d.ts.map +1 -1
  12. package/dist/LinkCard.d.ts.map +1 -1
  13. package/dist/LinkChip.d.ts.map +1 -1
  14. package/dist/LinkChips.d.ts +2 -1
  15. package/dist/LinkChips.d.ts.map +1 -1
  16. package/dist/LinkParts.d.ts +6 -1
  17. package/dist/LinkParts.d.ts.map +1 -1
  18. package/dist/LinkPlaces.d.ts +7 -0
  19. package/dist/LinkPlaces.d.ts.map +1 -1
  20. package/dist/LinkRow.d.ts +29 -6
  21. package/dist/LinkRow.d.ts.map +1 -1
  22. package/dist/PartCard.d.ts +9 -2
  23. package/dist/PartCard.d.ts.map +1 -1
  24. package/dist/ReferenceCards.d.ts +9 -39
  25. package/dist/ReferenceCards.d.ts.map +1 -1
  26. package/dist/ReferenceMenu.d.ts.map +1 -1
  27. package/dist/Select.d.ts +7 -1
  28. package/dist/Select.d.ts.map +1 -1
  29. package/dist/editor.d.ts +1 -1
  30. package/dist/editor.d.ts.map +1 -1
  31. package/dist/editor.js +204 -183
  32. package/dist/editor.js.map +3 -3
  33. package/dist/eslint/index.js +1 -1
  34. package/dist/eslint/index.js.map +2 -2
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +172 -52
  38. package/dist/index.js.map +3 -3
  39. package/dist/linked.d.ts +48 -3
  40. package/dist/linked.d.ts.map +1 -1
  41. package/dist/linked.examples.d.ts +6 -0
  42. package/dist/linked.examples.d.ts.map +1 -1
  43. package/dist/linkedFrom.d.ts +7 -3
  44. package/dist/linkedFrom.d.ts.map +1 -1
  45. package/package.json +1 -1
  46. package/registry.json +78 -65
  47. package/src/AppProvider.mdx +7 -5
  48. package/src/AppProvider.test.tsx +15 -1
  49. package/src/AppProvider.tsx +13 -4
  50. package/src/AttachedCard.mdx +2 -1
  51. package/src/AttachedCard.test.tsx +28 -0
  52. package/src/AttachedCard.tsx +12 -2
  53. package/src/BlockNodes.mdx +8 -1
  54. package/src/BlockNodes.tsx +98 -11
  55. package/src/CommentBox.mdx +8 -2
  56. package/src/CommentBox.stories.tsx +28 -1
  57. package/src/CommentBox.test.tsx +64 -1
  58. package/src/CommentBox.tsx +44 -5
  59. package/src/ComposerTriggers.mdx +1 -0
  60. package/src/ComposerTriggers.tsx +34 -15
  61. package/src/DocumentEditor.mdx +1 -1
  62. package/src/DocumentEditor.stories.tsx +2 -2
  63. package/src/DocumentEditor.test.tsx +37 -7
  64. package/src/DocumentEditor.tsx +2 -1
  65. package/src/LinkCard.mdx +9 -5
  66. package/src/LinkCard.stories.tsx +17 -2
  67. package/src/LinkCard.test.tsx +21 -0
  68. package/src/LinkCard.tsx +35 -16
  69. package/src/LinkChip.mdx +6 -1
  70. package/src/LinkChip.stories.tsx +7 -1
  71. package/src/LinkChip.test.tsx +12 -0
  72. package/src/LinkChip.tsx +6 -2
  73. package/src/LinkChips.mdx +4 -3
  74. package/src/LinkChips.stories.tsx +2 -2
  75. package/src/LinkChips.test.tsx +1 -2
  76. package/src/LinkChips.ts +2 -1
  77. package/src/LinkParts.mdx +3 -2
  78. package/src/LinkParts.stories.tsx +8 -0
  79. package/src/LinkParts.tsx +43 -6
  80. package/src/LinkPlaces.mdx +3 -0
  81. package/src/LinkPlaces.ts +19 -0
  82. package/src/LinkRow.mdx +8 -2
  83. package/src/LinkRow.stories.tsx +14 -2
  84. package/src/LinkRow.test.tsx +31 -1
  85. package/src/LinkRow.tsx +69 -25
  86. package/src/PartCard.mdx +9 -1
  87. package/src/PartCard.stories.tsx +9 -0
  88. package/src/PartCard.test.tsx +13 -0
  89. package/src/PartCard.tsx +19 -5
  90. package/src/ReferenceCards.test.tsx +4 -35
  91. package/src/ReferenceCards.ts +10 -119
  92. package/src/ReferenceMenu.mdx +6 -4
  93. package/src/ReferenceMenu.test.tsx +67 -5
  94. package/src/ReferenceMenu.tsx +18 -7
  95. package/src/Select.mdx +4 -0
  96. package/src/Select.stories.tsx +11 -1
  97. package/src/Select.tsx +10 -2
  98. package/src/editor.ts +0 -3
  99. package/src/eslint/no-restyled-part.ts +1 -1
  100. package/src/index.ts +4 -1
  101. package/src/linked.examples.ts +6 -0
  102. package/src/linked.test.ts +35 -1
  103. package/src/linked.ts +108 -3
  104. package/src/linkedFrom.test.tsx +42 -2
  105. package/src/linkedFrom.ts +15 -7
  106. package/src/registry/registry.test.ts +25 -6
  107. package/src/ReferenceCards.mdx +0 -86
  108. package/src/ReferenceCards.stories.tsx +0 -66
@@ -78,7 +78,14 @@ const editor = useEditor({
78
78
  `tableCell` nodes, and ProseMirror drops a node its schema does not have —
79
79
  the save would delete the table.
80
80
  - `ReferenceNode`'s `view` gets the `uri` and draws the thing it points at,
81
- resolved by the app. Without one, the URI is drawn as text.
81
+ resolved by the app. Without one, the URI is drawn as text. It is told
82
+ `editing` while the editor is editable; with `editingLine` (a document),
83
+ only while the caret is on its line, so a link elsewhere on the page can
84
+ show its hover preview.
85
+ - **A card's own links and controls work while editing.** A click on its
86
+ title, its count or a picker goes to them, and a press on a picker keeps the
87
+ caret where it was, so the picker opens; only a click on the card's empty
88
+ space is the link's menu (`ReferenceMenu`).
82
89
  - `AttachmentNode`'s `view` gets the block's `imeta` fields as `attrs`.
83
90
  Without one, the file's name is drawn as text.
84
91
  - `UnknownBlock` draws a block the editor has no design for as its text, in a
@@ -3,7 +3,7 @@ import { Extension, InputRule, Node, type Editor } from '@tiptap/core'
3
3
  import { DOMSerializer, type Node as ProseMirrorNode, type Slice } from '@tiptap/pm/model'
4
4
  import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state'
5
5
  import { Mapping, ReplaceAroundStep } from '@tiptap/pm/transform'
6
- import type { EditorView, NodeView } from '@tiptap/pm/view'
6
+ import { Decoration, DecorationSet, type EditorView, type NodeView } from '@tiptap/pm/view'
7
7
  import { NodeViewWrapper, ReactNodeViewRenderer, ReactRenderer, type ReactNodeViewProps } from '@tiptap/react'
8
8
  import { Checkbox, type CheckboxProps } from './Checkbox'
9
9
  import { calloutLook } from './RichText'
@@ -380,7 +380,11 @@ export interface ReferenceViewProps {
380
380
  * editor without `LinkPlaces`.
381
381
  */
382
382
  place?: LinkPlace
383
- /** Being edited: a click opens its menu rather than it, so a row or card shows no hover preview. */
383
+ /**
384
+ * Being edited, so a chip or a row shows no hover preview: a click on it opens its menu, or does nothing in a box
385
+ * being written in. In a box, always while it can be written in; in a document (`editingLine`), only while the
386
+ * caret is on its line, so a link elsewhere on the page previews on hover.
387
+ */
384
388
  editing?: boolean
385
389
  }
386
390
 
@@ -390,6 +394,58 @@ export interface ReferenceNodeOptions {
390
394
  * knows how to resolve it. Without one, the URI is drawn as text.
391
395
  */
392
396
  view: ComponentType<ReferenceViewProps> | null
397
+ /**
398
+ * A link counts as being edited (`editing`) only while the caret is on its
399
+ * line: its textblock, between the hard breaks either side, while the editor
400
+ * has focus. `DocumentEditor` sets it, so a page that is always editable
401
+ * still previews the links its writer is not working on (Katerina, 30 Oct).
402
+ * Off, every link is being edited while the editor is editable, as in a
403
+ * message's box.
404
+ */
405
+ editingLine: boolean
406
+ }
407
+
408
+ /** A card's own controls: a press on one stays theirs, see `keepCardPresses`. */
409
+ const CARD_CONTROLS = 'button, [role="combobox"]'
410
+
411
+ /** What a click in a card goes on to: its links (the title, the count) and its controls. Its empty space opens the menu. */
412
+ const CARD_CLICKS = `a[href], input, select, ${CARD_CONTROLS}`
413
+
414
+ /**
415
+ * ProseMirror sees a press before React does and takes the caret into the
416
+ * text, which closed a card's picker before it opened (Leaf's fix, moved here
417
+ * so every app has it). It leaves alone a press whose default is prevented.
418
+ */
419
+ function keepCardPresses(element: HTMLElement | null): (() => void) | undefined {
420
+ if (!element) return undefined
421
+ const keep = (event: globalThis.MouseEvent) => {
422
+ if (event.target instanceof Element && event.target.closest(CARD_CONTROLS)) event.preventDefault()
423
+ }
424
+ element.addEventListener('mousedown', keep)
425
+ return () => element.removeEventListener('mousedown', keep)
426
+ }
427
+
428
+ /** Every reference on the caret's line: the textblock it is in, between the hard breaks either side of it. */
429
+ function caretLineReferences(state: EditorState): { pos: number; size: number }[] {
430
+ const { $head } = state.selection
431
+ const block = $head.parent
432
+ if (!block.isTextblock) return []
433
+ const start = $head.start()
434
+ const at = $head.parentOffset
435
+ const lines: { from: number; to: number; references: { pos: number; size: number }[] }[] = [{ from: 0, to: block.content.size, references: [] }]
436
+ block.forEach((child, offset) => {
437
+ const line = lines[lines.length - 1]
438
+ if (child.type.name === 'hardBreak') {
439
+ line.to = offset
440
+ lines.push({ from: offset + child.nodeSize, to: block.content.size, references: [] })
441
+ } else if (child.type.name === 'reference') line.references.push({ pos: start + offset, size: child.nodeSize })
442
+ })
443
+ return lines.find((line) => at >= line.from && at <= line.to)?.references ?? []
444
+ }
445
+
446
+ /** Whether a node view's decorations put it on the caret's line. */
447
+ function onCaretLine(decorations: readonly Decoration[] | undefined): boolean {
448
+ return (decorations ?? []).some((decoration) => (decoration.spec as { caretLine?: boolean }).caretLine === true)
393
449
  }
394
450
 
395
451
  /**
@@ -420,7 +476,26 @@ export const ReferenceNode = Node.create<ReferenceNodeOptions>({
420
476
  selectable: true,
421
477
  draggable: false,
422
478
  addOptions() {
423
- return { view: null }
479
+ return { view: null, editingLine: false }
480
+ },
481
+ addProseMirrorPlugins() {
482
+ if (!this.options.editingLine) return []
483
+ const editor = this.editor
484
+ return [
485
+ new Plugin({
486
+ key: new PluginKey('referenceCaretLine'),
487
+ props: {
488
+ // Read on every update, a focus and a blur included (Tiptap sends a transaction for each), so it follows the caret.
489
+ decorations: (state) =>
490
+ editor.isFocused && editor.isEditable
491
+ ? DecorationSet.create(
492
+ state.doc,
493
+ caretLineReferences(state).map(({ pos, size }) => Decoration.node(pos, pos + size, {}, { caretLine: true })),
494
+ )
495
+ : null,
496
+ },
497
+ }),
498
+ ]
424
499
  },
425
500
  addAttributes() {
426
501
  return {
@@ -452,15 +527,19 @@ export const ReferenceNode = Node.create<ReferenceNodeOptions>({
452
527
  addNodeView() {
453
528
  const View = this.options.view
454
529
  if (!View) return null
530
+ const { editingLine } = this.options
455
531
  return ReactNodeViewRenderer(({ node, editor, getPos, decorations }: ReactNodeViewProps) => {
456
532
  const uri = String(node.attrs.uri ?? '')
457
533
  const href = typeof node.attrs.href === 'string' && node.attrs.href ? node.attrs.href : undefined
458
534
  const place = placeOf(decorations)
535
+ const editing = editor.isEditable && (!editingLine || onCaretLine(decorations))
459
536
  return (
460
537
  <NodeViewWrapper
461
538
  as="span"
462
539
  // A row or a card is the whole line.
463
540
  className={place === 'chip' ? 'inline' : 'block w-full'}
541
+ // A card keeps its pickers while the text is edited too (Katerina, 30 Oct): a press on one is not the text's.
542
+ ref={place === 'card' ? keepCardPresses : undefined}
464
543
  // While editing, a click opens the chip's menu (`ReferenceMenu`) rather than following the chip.
465
544
  onClickCapture={(event: MouseEvent) => {
466
545
  // A click in something the view portals out — a picker's list, a hover card — reaches here through React's
@@ -470,21 +549,29 @@ export const ReferenceNode = Node.create<ReferenceNodeOptions>({
470
549
  // (`Node` here is Tiptap's; a click's target is an Element.)
471
550
  const own = editor.view.nodeDOM(pos)
472
551
  if (!(event.target instanceof Element) || !own || !own.contains(event.target)) return
473
- // A card's own controls — its status, its owner — change it from the card, while editing too.
474
- if (place === 'card' && event.target.closest('button, input, select, [role="combobox"]')) return
475
- if (!referenceMenuClick(editor, pos)) return
476
- event.preventDefault()
477
- event.stopPropagation()
552
+ // A card's own links and controls take the click, while editing too: its title opens the file, its count the
553
+ // conversation, its status and owner change it. Only its empty space opens the menu (Katerina, 30 Oct).
554
+ if (place === 'card' && event.target.closest(CARD_CLICKS)) return
555
+ if (referenceMenuClick(editor, pos)) {
556
+ event.preventDefault()
557
+ event.stopPropagation()
558
+ return
559
+ }
560
+ // Being written with no menu to open — a message's box: a click on the link does not leave the draft
561
+ // (Katerina, 30 Oct: a chip in the box does not follow a click).
562
+ if (!editingLine && editor.isEditable && event.target.closest('a[href]')) event.preventDefault()
478
563
  }}
479
564
  >
480
565
  {/* A URL chip not resolved yet reads as the URL it was written as. */}
481
- {uri ? <View uri={uri} {...(href ? { href } : {})} place={place} editing={editor.isEditable} /> : <span>{href}</span>}
566
+ {uri ? <View uri={uri} {...(href ? { href } : {})} place={place} editing={editing} /> : <span>{href}</span>}
482
567
  </NodeViewWrapper>
483
568
  )
484
569
  }, {
485
- // Words typed beside a link leave its node as it was, and Tiptap then skips the redraw; its place has changed (code review).
570
+ // Words typed beside a link leave its node as it was, and Tiptap then skips the redraw; its place has changed (code
571
+ // review), or the caret came onto its line or left it.
486
572
  update: ({ oldNode, newNode, oldDecorations, newDecorations, updateProps }) => {
487
- if (oldNode !== newNode || placeOf(oldDecorations) !== placeOf(newDecorations)) updateProps()
573
+ const moved = placeOf(oldDecorations) !== placeOf(newDecorations) || onCaretLine(oldDecorations) !== onCaretLine(newDecorations)
574
+ if (oldNode !== newNode || moved) updateProps()
488
575
  return true
489
576
  },
490
577
  })
@@ -15,7 +15,8 @@ The one box every app writes a comment, a reply and a line of a conversation in:
15
15
  - `showsAtOnce` when the app shows a send before the relay answers: the box empties at once, and a refusal puts the words back. Without it the box holds the words, shut, until the answer.
16
16
  - `edit` to change something already sent: the same box with Cancel and Save, its keys on the left, and the same selection strip over selected words. Its files can be taken off, and with `upload` and `edit.writesFiles` (the app's save writes them) more added. An app that closes the box as Save is pressed and reopens it on a refusal passes `edit.refused`, which is said under the box as it opens.
17
17
  - `upload` to offer files: the paperclip, `/` → Upload, a pasted picture and a dropped file. The edit box has no paperclip, since it shows only its keys; the other three work there too.
18
- - `under` to show, while something is written, the one card it will be sent with and the live part of each block link. They sit inside the box with the files, on the files' fill; the card's ✕ is a file's, on hover, and its values read as words until it is sent. An edit box shows the card and no part.
18
+ - `under` to show, while something is written, the one card it will be sent with and the live part of each block link. They sit inside the box with the files, on the files' fill; the card's ✕ is a file's, on hover, and its values and links read as words until it is sent, so a click on it never leaves the draft. An edit box shows the card and no part.
19
+ - `referenceView` to draw every link the box holds — a pasted app URL once it names something, a pasted `nostr:` address of a file or a message, and a `[` pick — as the app draws a link, with the kit's **LinkChip**: one chip look in every box. It is told it is being edited, so it shows no preview, and a click on it stays in the draft.
19
20
  - `closed` where nothing can be written (archived, signed out): a line saying why, in the box's place. No greyed box.
20
21
  - `marked` when the app has its own reason for the bar down the text, besides an urgent mention, which always draws it.
21
22
  - `onEditor` when something outside the box writes into it: the app keeps the editor it is handed and inserts into the box last used.
@@ -30,6 +31,8 @@ The one box every app writes a comment, a reply and a line of a conversation in:
30
31
 
31
32
  <Canvas of={CommentBoxStories.WithACard} />
32
33
 
34
+ <Canvas of={CommentBoxStories.WithLinkChips} />
35
+
33
36
  ## When not
34
37
 
35
38
  - Writing a document in place → the editor itself, with **EditorBlockHandle** and **SelectionToolbar**. Nothing is sent.
@@ -68,7 +71,8 @@ const draft = composerDraft(createDraftStore(localStorage), draftKeys.thread(roo
68
71
  - A send shown at once and refused after its box went away writes the words into its draft instead.
69
72
  - **`under.read` is the app's reading of the draft**: `@estiva-app/conversation`'s `boxReadOf(body, context)` says which file gets the card and which parts show; the app adds its own view of each. Call `under.changed`'s listener when what a link names comes back. `send`'s third argument is `{ card }`, the card still shown, which the app writes with `embedsToSend` (or `embedsToEdit` for `onSave`).
70
73
  - **An edit box's `read` passes `previous: namedBefore(<the message's text>)`**, so only a file the edit names first gets a card. A card the message already has, or one taken off with ✕ before or after sending, never shows again in the edit box, and Save leaves it as it was.
71
- - **A link chip for a pasted app URL** is the app's `LinkChips`, passed in `extensions`.
74
+ - **A link chip for a pasted app URL** is the app's `LinkChips`, passed in `extensions`. A pasted `nostr:` address needs nothing: with a `referenceView`, the box makes it its link itself. A person's (`npub`) stays text; `@` names a person.
75
+ - **`referenceIcon` is optional.** Without it, `[`'s rows wear the kit's icon for the kind each address names (**LinkedIcon**: a message, an issue, a project, a topic, a document, another app's file), and a neutral square for one that names none.
72
76
  - **`keepCommentBoxWarm({ extensions, referenceView })`**, called once as the app starts, builds an editor while the page is idle, and the next empty box given those same `extensions` and `referenceView` (the same objects, in the same order) takes it, so it opens at once. A box opening with a draft or an edit, or with other extensions, builds its own. Keep `extensions` a module constant: a new array per render never matches.
73
77
  - **`onEditor` gets `null` as the box goes**, so a launcher never writes into a box that is gone.
74
78
 
@@ -79,6 +83,8 @@ It does these by itself. Write none of them around it.
79
83
  | It does | So you never write |
80
84
  |---|---|
81
85
  | `@`, `!@`, `[` and `/`, with their lists and chips | the triggers and their extensions |
86
+ | A `[` pick, a pasted link and a pasted `nostr:` address drawn alike, through `referenceView`; none previews while written, and a click on one, or on the card in the box, stays in the draft | a chip of your own for the box, a click guard |
87
+ | `[`'s rows wear the icon of the kind each address names | an icon lookup |
82
88
  | Enter and Ctrl/Cmd+Enter send; Escape cancels an edit | key handlers |
83
89
  | Holding the words until the answer, or showing the send at once | a sending state |
84
90
  | A refusal: the words back, and a line under the box | a toast, or putting text back |
@@ -10,7 +10,8 @@ import type { CaptionedItem, MentionPerson, ReferenceSection, SlashCommand } fro
10
10
  import { InlineChip } from './InlineChip'
11
11
  import { Kbd } from './Kbd'
12
12
  import { LinkCard } from './LinkCard'
13
- import { ITEM, ready } from './linked.examples'
13
+ import { LinkChip } from './LinkChip'
14
+ import { ITEM, ITEM_NO_SUMMARY, ready } from './linked.examples'
14
15
  import { PartCard } from './PartCard'
15
16
  import { RichText } from './RichText'
16
17
 
@@ -302,6 +303,32 @@ export const EditingWithACard: Story = {
302
303
  },
303
304
  }
304
305
 
306
+ /** The app's view of a link the box holds: the kit's chip, with no preview while it is written. */
307
+ const KitChip = ({ uri, editing }: ReferenceViewProps) => <LinkChip link={ready(uri === ITEMS[0].uri ? ITEM : ITEM_NO_SUMMARY)} preview={!editing} />
308
+
309
+ const WITH_LINKS: JSONContent = {
310
+ type: 'doc',
311
+ content: [
312
+ {
313
+ type: 'paragraph',
314
+ content: [
315
+ { type: 'text', text: 'Picked with [: ' },
316
+ { type: 'captionedReference', attrs: { id: ITEMS[0].id, label: 'Label', snippet: 'Item one', uri: ITEMS[0].uri } },
317
+ { type: 'text', text: ' and pasted: ' },
318
+ { type: 'reference', attrs: { uri: ITEMS[1].uri } },
319
+ ],
320
+ },
321
+ ],
322
+ }
323
+
324
+ /**
325
+ * Every link in the box is the kit's chip, through the app's `referenceView`: a
326
+ * `[` pick and a pasted link alike, each with its key, its title cut short and
327
+ * its status as a mark. Neither previews while written, and a click on one
328
+ * stays in the box. Type `[` to pick another.
329
+ */
330
+ export const WithLinkChips: Story = { render: () => <Live start={WITH_LINKS} referenceView={KitChip} /> }
331
+
305
332
  /** An app's own `/` rows, after the kit's: each puts a label at the start of the box, which the app marks. */
306
333
  const OWN_ROWS: SlashCommand[] = ['one', 'two', 'three', 'four', 'five'].map((n) => ({
307
334
  key: `own-${n}`,
@@ -10,8 +10,10 @@ import { cleanup, fireEvent, render, screen, within } from '@testing-library/rea
10
10
  import { Extension, type Editor } from '@tiptap/core'
11
11
  import { Fragment, Slice } from '@tiptap/pm/model'
12
12
  import type { JSONContent } from '@tiptap/react'
13
+ import { encodeNaddr, encodeNevent } from '@estiva-app/protocol'
14
+ import type { ReferenceViewProps } from './BlockNodes'
13
15
  import { CommentBox, commentBoxRows, keepCommentBoxWarm, type BoxUnder, type CommentBoxDraft, type CommentBoxEdit, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
14
- import type { MentionPerson } from './ComposerTriggers'
16
+ import type { MentionPerson, ReferenceSection } from './ComposerTriggers'
15
17
 
16
18
  const PEOPLE: MentionPerson[] = [{ id: 'one', name: 'Person one', pubkey: 'b'.repeat(64) }]
17
19
  const INSERT = [commentBoxRows.file, commentBoxRows.mention, commentBoxRows.urgent, commentBoxRows.reference]
@@ -668,6 +670,67 @@ describe('a box built ahead', () => {
668
670
  })
669
671
  })
670
672
 
673
+ describe('a link in the box', () => {
674
+ const ISSUE = `nostr:${encodeNaddr({ kind: 30851, pubkey: 'a'.repeat(64), identifier: 'item-one', relays: [] })}`
675
+ const MESSAGE = `nostr:${encodeNevent({ id: 'e'.repeat(64), relays: [] })}`
676
+ /** The app's view of a link: the kit's chip would be a link to it. */
677
+ const View = ({ uri, editing }: ReferenceViewProps) => (
678
+ <a href={`/o/${uri}`} data-uri={uri} data-editing={String(!!editing)}>
679
+ Linked
680
+ </a>
681
+ )
682
+ const drawn = () => [...document.querySelectorAll('[data-uri]')].map((el) => el.getAttribute('data-uri'))
683
+ const inline = () => ((editorOf().getJSON() as JSONContent).content?.[0].content ?? []).map((n) => n.type)
684
+
685
+ it('draws a [ pick, and a draft opening with one, as the app draws every other link in the box, being edited', async () => {
686
+ render(<Box referenceView={View} />)
687
+ await act(async () => {
688
+ editorOf()
689
+ .chain()
690
+ .focus('end')
691
+ .insertContent([{ type: 'captionedReference', attrs: { id: ISSUE, label: 'Item one', snippet: '', uri: ISSUE } }, { type: 'text', text: ' and ' }, { type: 'reference', attrs: { uri: MESSAGE } }])
692
+ .run()
693
+ })
694
+ expect(drawn()).toEqual([ISSUE, MESSAGE])
695
+ expect([...document.querySelectorAll('[data-editing]')].map((el) => el.getAttribute('data-editing'))).toEqual(['true', 'true'])
696
+ // The caption's own chip is not drawn beside it.
697
+ expect(screen.queryByText('Item one')).toBeNull()
698
+ })
699
+
700
+ it('never leaves the draft for a click on a link in it', async () => {
701
+ render(<Box referenceView={View} />)
702
+ await act(async () => {
703
+ editorOf()
704
+ .chain()
705
+ .focus('end')
706
+ .insertContent([{ type: 'captionedReference', attrs: { id: ISSUE, label: 'Item one', snippet: '', uri: ISSUE } }, { type: 'text', text: ' ' }, { type: 'reference', attrs: { uri: MESSAGE } }])
707
+ .run()
708
+ })
709
+ for (const link of screen.getAllByRole('link', { name: 'Linked' })) expect(fireEvent.click(link)).toBe(false)
710
+ })
711
+
712
+ it('makes a pasted nostr: address of a file or a message its link at once; a person stays text', async () => {
713
+ const PERSON = 'nostr:npub1' + 'q'.repeat(58)
714
+ render(<Box referenceView={View} />)
715
+ await act(async () => {
716
+ editorOf().commands.focus('end')
717
+ editorOf().view.pasteText(`see ${ISSUE} and ${MESSAGE} and ${PERSON}`, new Event('paste') as ClipboardEvent)
718
+ })
719
+ expect(drawn()).toEqual([ISSUE, MESSAGE])
720
+ expect(inline()).toEqual(['text', 'reference', 'text', 'reference', 'text'])
721
+ expect(editorOf().getText()).toContain(PERSON)
722
+ })
723
+
724
+ it('gives a [ row the icon of the kind its address names when the app gives none', async () => {
725
+ const sections: ReferenceSection[] = [{ label: 'Files', items: [{ id: 'one', label: 'Item one', snippet: '', uri: ISSUE }] }]
726
+ render(<Box references={() => sections} />)
727
+ await type(' [')
728
+ const row = within(screen.getByRole('listbox')).getByRole('option')
729
+ expect(row.querySelector('svg')?.getAttribute('class')).toContain('tabler-icon-list-details')
730
+ await press('Escape')
731
+ })
732
+ })
733
+
671
734
  describe('a long draft', () => {
672
735
  const said: JSONContent = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Said before' }] }] }
673
736
 
@@ -1,5 +1,5 @@
1
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'
2
+ import { Extension, nodePasteRule, type AnyExtension, type EditorOptions } from '@tiptap/core'
3
3
  import { Editor, type JSONContent } from '@tiptap/react'
4
4
  import { IconLock, IconPaperclip, IconSquareRounded } from '@tabler/icons-react'
5
5
  import { AttachedCard } from './AttachedCard'
@@ -27,6 +27,8 @@ import { FieldLine } from './Field'
27
27
  import { FilePicker } from './FilePicker'
28
28
  import { Kbd } from './Kbd'
29
29
  import { inTheBox } from './linked'
30
+ import { LinkedIcon } from './LinkParts'
31
+ import { linkedKindOfReference } from './LinkPlaces'
30
32
  import { BoxKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'
31
33
  import { PastedImages } from './PastedImages'
32
34
  import { KeptSelection } from './SelectionToolbar'
@@ -131,7 +133,10 @@ export interface CommentBoxProps {
131
133
  references?: (query: string) => readonly ReferenceSection[]
132
134
  /** Called with a listener while `[` is open; call it when `references` would answer differently (a search landed). */
133
135
  referencesChanged?: (listener: () => void) => () => void
134
- /** A `[` row's and chip's 16px icon from what it points at; absent, a neutral square. */
136
+ /**
137
+ * A `[` row's and chip's 16px icon from what it points at. Absent, the kit's icon for the kind its address names
138
+ * (`LinkedIcon`), and a neutral square for an address that names none.
139
+ */
135
140
  referenceIcon?: (uri: string | null) => ReactNode | undefined
136
141
  /** The app's own `/` Insert rows, after the shared Format section: {@link commentBoxRows} and its own. */
137
142
  insert?: readonly SlashCommand[]
@@ -161,7 +166,11 @@ export interface CommentBoxProps {
161
166
  accept?: string
162
167
  /** The box cannot write here (an archived file, signed out): a line saying why takes its place. */
163
168
  closed?: { reason: ReactNode }
164
- /** How a `nostr:` reference the box holds is drawn — the app's own chip. Absent, as its URI. */
169
+ /**
170
+ * How a link the box holds is drawn — a pasted one, a pasted `nostr:` address, and a `[` pick alike: the app's view
171
+ * of the kit's `LinkChip`, told it is being edited (no preview; a click stays in the draft). Absent, a `nostr:`
172
+ * reference reads as its URI and a `[` pick as its caption.
173
+ */
165
174
  referenceView?: ComponentType<ReferenceViewProps>
166
175
  /** The app's own extra editor extensions: link chips, highlights. */
167
176
  extensions?: readonly AnyExtension[]
@@ -216,6 +225,32 @@ const stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): Rea
216
225
  const SQUARE = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
217
226
  const SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />
218
227
 
228
+ /** The kit's icon for the kind a `nostr:` address names, at a row's or a chip's size; nothing for one that names none. */
229
+ function kindIconOf(uri: string | null, size: 14 | 16): ReactNode | undefined {
230
+ const kind = uri ? linkedKindOfReference(uri) : undefined
231
+ return kind ? <LinkedIcon kind={kind} size={size} /> : undefined
232
+ }
233
+
234
+ /**
235
+ * A `nostr:` address pasted into the box becomes its link at once, as a pasted app URL does (Katerina, 30 Oct): a file
236
+ * (`naddr`) or a message (`nevent`, `note`), drawn by the app's `referenceView`. A person's (`npub`) stays the text
237
+ * it is; `@` names a person.
238
+ */
239
+ const PastedAddresses = Extension.create({
240
+ name: 'pastedAddresses',
241
+ addPasteRules() {
242
+ const type = this.editor.schema.nodes.reference
243
+ if (!type) return []
244
+ return [
245
+ nodePasteRule({
246
+ find: /nostr:(?:naddr1|nevent1|note1)[023456789acdefghjklmnpqrstuvwxyz]+/g,
247
+ type,
248
+ getAttributes: (match) => ({ uri: match[0] }),
249
+ }),
250
+ ]
251
+ },
252
+ })
253
+
219
254
  /** What the box's editor reads as it runs: the box holding it now, swapped in when a box takes a spare. */
220
255
  interface BoxLive {
221
256
  edit?: CommentBoxEdit
@@ -244,7 +279,9 @@ const sameApp = (a: BoxApp, b: BoxApp) =>
244
279
  a.referenceView === b.referenceView && a.extensions.length === b.extensions.length && a.extensions.every((one, i) => one === b.extensions[i])
245
280
 
246
281
  function boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {
247
- const iconFor = (uri: string | null) => hold.current.referenceIcon?.(uri)
282
+ // The app's icons when it gives them; the kit's for the kind each address names otherwise (Katerina, 30 Oct).
283
+ const own = (uri: string | null, size: 14 | 16) => (hold.current.referenceIcon ? hold.current.referenceIcon(uri) : kindIconOf(uri, size))
284
+ const iconFor = (uri: string | null) => own(uri, 16)
248
285
  return [
249
286
  // A link drawn as one, as in a document: it read as plain words in the box before (Katerina, 29 Oct).
250
287
  BoxKit.configure({ link: { openOnClick: false, HTMLAttributes: LINK_MARK_ATTRIBUTES } }),
@@ -274,7 +311,8 @@ function boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {
274
311
  return { ...parent, suggestion: { ...parent.suggestion, allow: () => !hold.current.edit } }
275
312
  },
276
313
  }).configure({ people: () => hold.current.people }),
277
- CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor }),
314
+ // A `[` pick draws as the app draws every other link in the box (Katerina, 30 Oct: one chip look in every box).
315
+ CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor: (uri) => own(uri, 14), view: app.referenceView }),
278
316
  ReferenceTrigger.configure({
279
317
  items: () => [],
280
318
  sections: (query) => hold.current.references?.(query) ?? [],
@@ -286,6 +324,7 @@ function boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {
286
324
  }),
287
325
  SlashCommands.configure({ sections: hold.sections }),
288
326
  ReferenceNode.configure({ view: app.referenceView }),
327
+ ...(app.referenceView ? [PastedAddresses] : []),
289
328
  PastedImages.configure({ onImages: (files: File[]) => hold.current.attach(files) }),
290
329
  ...app.extensions,
291
330
  ]
@@ -101,6 +101,7 @@ const urgent = editor ? urgentPubkeys(editor) : undefined
101
101
 
102
102
  <Canvas of={ComposerTriggersStories.ReferencesOfSeveralKinds} />
103
103
 
104
+ - **`CaptionedReference`'s `view`** draws a chip with a `uri` as the app draws its other links (a `referenceView`, the kit's **LinkChip**), told it is being edited; a click on it stays in the draft. `CommentBox` passes its `referenceView`, so a `[` pick looks like a pasted link.
104
105
  - **An app's own node name:** `CaptionedReference.extend({ name: 'yourName' })`
105
106
  and `ReferenceTrigger.configure({ nodeName: 'yourName' })`. The chip's HTML
106
107
  attribute follows the name (`data-your-name`).
@@ -1,10 +1,11 @@
1
- import type { ReactNode } from 'react'
1
+ import type { ComponentType, MouseEvent, ReactNode } from 'react'
2
2
  import { Extension, type Editor } from '@tiptap/core'
3
3
  import { PluginKey } from '@tiptap/pm/state'
4
4
  import Mention, { type MentionOptions } from '@tiptap/extension-mention'
5
5
  import Suggestion from '@tiptap/suggestion'
6
6
  import { NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from '@tiptap/react'
7
7
  import { Avatar } from './Avatar'
8
+ import type { ReferenceViewProps } from './BlockNodes'
8
9
  import { EnterHint } from './Menu'
9
10
  import { inlineChipClassName } from './InlineChip'
10
11
  import { WithTooltip } from './Tooltip'
@@ -343,13 +344,26 @@ export interface CaptionedReferenceOptions {
343
344
  * The same answer the list's row gave (Katerina, 7 October).
344
345
  */
345
346
  iconFor?: (uri: string | null) => ReactNode | undefined
347
+ /**
348
+ * Draws the chip as the box's other links are drawn — the app's `referenceView`,
349
+ * the kit's `LinkChip` — told it is being edited, so it shows no preview and a
350
+ * click on it stays in the draft. Absent, or for a chip with no `uri`, the
351
+ * caption with `icon`.
352
+ */
353
+ view?: ComponentType<ReferenceViewProps> | null
354
+ }
355
+
356
+ /** A click on a link inside a chip being written: the draft is not left for it (Katerina, 30 Oct). */
357
+ function stayInDraft(event: MouseEvent) {
358
+ if (event.target instanceof Element && event.target.closest('a[href]')) event.preventDefault()
346
359
  }
347
360
 
348
361
  /**
349
362
  * A reference mid-sentence, drawn as `label: snippet` and written as its `uri`
350
363
  * verbatim (SPEC §13.1). The caption is the snapshot it was picked with — a
351
364
  * caption, never parsed. Inserted by {@link ReferenceTrigger}, a paste or a
352
- * draft; it opens no list of its own.
365
+ * draft; it opens no list of its own. With `view` it draws as the app draws
366
+ * any other link in the box, so a `[` pick and a pasted link look alike.
353
367
  */
354
368
  export const CaptionedReference = Mention.extend<MentionOptions & CaptionedReferenceOptions>({
355
369
  name: 'captionedReference',
@@ -357,7 +371,7 @@ export const CaptionedReference = Mention.extend<MentionOptions & CaptionedRefer
357
371
  inline: true,
358
372
  atom: true,
359
373
  addOptions() {
360
- return { ...this.parent!(), HTMLAttributes: {}, icon: null, iconFor: undefined, suggestion: { char: '\0', items: () => [] } }
374
+ return { ...this.parent!(), HTMLAttributes: {}, icon: null, iconFor: undefined, view: null, suggestion: { char: '\0', items: () => [] } }
361
375
  },
362
376
  addAttributes() {
363
377
  return {
@@ -378,19 +392,24 @@ export const CaptionedReference = Mention.extend<MentionOptions & CaptionedRefer
378
392
  return [{ tag: `span[data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}]` }]
379
393
  },
380
394
  addNodeView() {
381
- const { icon, iconFor } = this.options
395
+ const { icon, iconFor, view: View } = this.options
382
396
  return ReactNodeViewRenderer(
383
- ({ node }: ReactNodeViewProps) => (
384
- // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) — as Peek's sent chip has it.
385
- <NodeViewWrapper as="span">
386
- <WithTooltip inline label={captionOf(node.attrs.label, node.attrs.snippet)}>
387
- <span className={inlineChipClassName('neutral', 'max-w-[24ch] cursor-default')}>
388
- <span className="flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary">{iconFor?.(node.attrs.uri ?? null) ?? icon}</span>
389
- <span className="truncate">{captionOf(node.attrs.label, node.attrs.snippet)}</span>
390
- </span>
391
- </WithTooltip>
392
- </NodeViewWrapper>
393
- ),
397
+ ({ node }: ReactNodeViewProps) =>
398
+ View && node.attrs.uri ? (
399
+ <NodeViewWrapper as="span" onClickCapture={stayInDraft}>
400
+ <View uri={String(node.attrs.uri)} place="chip" editing />
401
+ </NodeViewWrapper>
402
+ ) : (
403
+ // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) — as Peek's sent chip has it.
404
+ <NodeViewWrapper as="span">
405
+ <WithTooltip inline label={captionOf(node.attrs.label, node.attrs.snippet)}>
406
+ <span className={inlineChipClassName('neutral', 'max-w-[24ch] cursor-default')}>
407
+ <span className="flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary">{iconFor?.(node.attrs.uri ?? null) ?? icon}</span>
408
+ <span className="truncate">{captionOf(node.attrs.label, node.attrs.snippet)}</span>
409
+ </span>
410
+ </WithTooltip>
411
+ </NodeViewWrapper>
412
+ ),
394
413
  { as: 'span' },
395
414
  )
396
415
  },
@@ -76,7 +76,7 @@ const codec: DocumentCodec = {
76
76
  - **`label` is required**: the editor's accessible name.
77
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.
78
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`.
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`.
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. A link is `editing` only while the caret is on its line: give the chip and row no hover preview then, as a click opens the link's menu; anywhere else on the page they preview on hover. A card keeps its pickers while the text is edited, and its title and count follow a click. A person or a Folder alone on its line is a `chip`.
80
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.
81
81
 
82
82
  ## What it owns
@@ -100,8 +100,8 @@ function useLinked(uri: string): Linked | undefined {
100
100
 
101
101
  /**
102
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.
103
+ * link kit's chip, row or card. On the caret's line a click is the menu's, so
104
+ * a chip or row there shows no hover card; elsewhere on the page it does.
105
105
  */
106
106
  function Chip({ uri, href, place = 'chip', editing = false }: ReferenceViewProps) {
107
107
  const linked = useLinked(uri)
@@ -11,9 +11,11 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
11
11
  import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
12
12
  import type { Editor } from '@tiptap/core'
13
13
  import { Fragment, Slice } from '@tiptap/pm/model'
14
+ import { TextSelection } from '@tiptap/pm/state'
14
15
  import type { JSONContent } from '@tiptap/react'
15
16
  import { documentForEditing, encodeNpub, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
16
17
  import { newlyNamedPeople } from '@estiva-app/conversation'
18
+ import type { ReferenceViewProps } from './BlockNodes'
17
19
  import type { MentionPerson, ReferenceSection } from './ComposerTriggers'
18
20
  import { DocumentEditor, type DocumentCodec, type DocumentEditorProps, type HeldTyping } from './DocumentEditor'
19
21
 
@@ -531,13 +533,40 @@ describe('blocks', () => {
531
533
 
532
534
  describe('a link, by where it sits', () => {
533
535
  const run = (uri: string, embed?: string) => ({ type: 'text', text: uri, marks: [{ type: 'reference', attrs: { uri, ...(embed ? { embed } : {}) } }] })
534
- /** The app's drawing of a link: says where it sits. */
535
- const Placed = ({ uri, place }: { uri: string; place?: string }) => (
536
- <a href={`/o/${uri}`} data-place={place ?? 'none'} onClick={(event) => event.preventDefault()}>
537
- Item
538
- </a>
539
- )
536
+ /** The app's drawing of a link: says where it sits, and whether it is being edited; a card has room around its link. */
537
+ const Placed = ({ uri, place, editing }: ReferenceViewProps) => {
538
+ const link = (
539
+ <a href={`/o/${uri}`} data-place={place ?? 'none'} data-editing={String(!!editing)} onClick={(event) => event.preventDefault()}>
540
+ Item
541
+ </a>
542
+ )
543
+ return place === 'card' ? <span data-testid="card">{link} Summary</span> : link
544
+ }
540
545
  const places = () => [...document.querySelectorAll('[data-place]')].map((el) => el.getAttribute('data-place'))
546
+ const editing = () => [...document.querySelectorAll('[data-editing]')].map((el) => el.getAttribute('data-editing'))
547
+
548
+ it('is being edited only while the caret is on its line: elsewhere, and once the editor is left, it can preview', async () => {
549
+ const value = doc(
550
+ { type: 'paragraph', id: 'a1', content: [{ type: 'text', text: 'See ' }, run(ITEM_URI)] },
551
+ { type: 'paragraph', id: 'a2', content: [{ type: 'text', text: 'And ' }, run(ITEM_URI)] },
552
+ )
553
+ render(<Doc value={value} referenceView={Placed} />)
554
+ await screen.findAllByRole('link', { name: 'Item' })
555
+ expect(editing()).toEqual(['false', 'false'])
556
+ // The caret placed at once, focused: Tiptap's own `focus` command focuses a frame later, which could land after `leave`.
557
+ const caretAt = (at: (size: number) => number) =>
558
+ act(async () => {
559
+ const { view, state } = editorOf()
560
+ view.focus()
561
+ view.dispatch(state.tr.setSelection(TextSelection.create(state.doc, at(state.doc.content.size))))
562
+ })
563
+ await caretAt(() => 2)
564
+ expect(editing()).toEqual(['true', 'false'])
565
+ await caretAt((size) => size - 1)
566
+ expect(editing()).toEqual(['false', 'true'])
567
+ await leave()
568
+ expect(editing()).toEqual(['false', 'false'])
569
+ })
541
570
 
542
571
  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 () => {
543
572
  const value = doc(
@@ -565,7 +594,8 @@ describe('a link, by where it sits', () => {
565
594
  render(<Doc value={doc({ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] })} referenceView={Placed} onCommit={onCommit} />)
566
595
  const choose = async (label: 'Row' | 'Card') => {
567
596
  await act(async () => editorOf().view.focus())
568
- fireEvent.click(await screen.findByRole('link', { name: 'Item' }))
597
+ // A card's own link follows; its empty space opens the menu.
598
+ fireEvent.click(screen.queryByTestId('card') ?? (await screen.findByRole('link', { name: 'Item' })))
569
599
  fireEvent.mouseDown(await screen.findByRole('menuitemradio', { name: label }))
570
600
  await leave()
571
601
  }