@estiva-app/ui 0.91.2 → 0.92.1

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 (106) 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/Button.d.ts +11 -1
  8. package/dist/Button.d.ts.map +1 -1
  9. package/dist/CommentBox.d.ts +9 -2
  10. package/dist/CommentBox.d.ts.map +1 -1
  11. package/dist/ComposerTriggers.d.ts +11 -2
  12. package/dist/ComposerTriggers.d.ts.map +1 -1
  13. package/dist/DocumentEditor.d.ts.map +1 -1
  14. package/dist/LinkCard.d.ts.map +1 -1
  15. package/dist/LinkChip.d.ts.map +1 -1
  16. package/dist/LinkChips.d.ts +2 -1
  17. package/dist/LinkChips.d.ts.map +1 -1
  18. package/dist/LinkParts.d.ts +6 -1
  19. package/dist/LinkParts.d.ts.map +1 -1
  20. package/dist/LinkPlaces.d.ts +7 -0
  21. package/dist/LinkPlaces.d.ts.map +1 -1
  22. package/dist/LinkRow.d.ts +29 -6
  23. package/dist/LinkRow.d.ts.map +1 -1
  24. package/dist/PartCard.d.ts +9 -2
  25. package/dist/PartCard.d.ts.map +1 -1
  26. package/dist/ReferenceCards.d.ts +9 -39
  27. package/dist/ReferenceCards.d.ts.map +1 -1
  28. package/dist/ReferenceMenu.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/index.d.ts +2 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +211 -97
  36. package/dist/index.js.map +3 -3
  37. package/dist/linked.d.ts +48 -3
  38. package/dist/linked.d.ts.map +1 -1
  39. package/dist/linked.examples.d.ts +6 -0
  40. package/dist/linked.examples.d.ts.map +1 -1
  41. package/dist/linkedFrom.d.ts +7 -3
  42. package/dist/linkedFrom.d.ts.map +1 -1
  43. package/package.json +1 -1
  44. package/registry.json +65 -56
  45. package/src/AppProvider.mdx +7 -5
  46. package/src/AppProvider.test.tsx +15 -1
  47. package/src/AppProvider.tsx +13 -4
  48. package/src/AttachedCard.mdx +2 -1
  49. package/src/AttachedCard.test.tsx +28 -0
  50. package/src/AttachedCard.tsx +12 -2
  51. package/src/BlockNodes.mdx +8 -1
  52. package/src/BlockNodes.tsx +98 -11
  53. package/src/Button.mdx +25 -3
  54. package/src/Button.stories.tsx +15 -1
  55. package/src/Button.test.tsx +33 -0
  56. package/src/Button.tsx +65 -49
  57. package/src/CommentBox.mdx +8 -2
  58. package/src/CommentBox.stories.tsx +28 -1
  59. package/src/CommentBox.test.tsx +64 -1
  60. package/src/CommentBox.tsx +44 -5
  61. package/src/ComposerTriggers.mdx +1 -0
  62. package/src/ComposerTriggers.tsx +34 -15
  63. package/src/DocumentEditor.mdx +1 -1
  64. package/src/DocumentEditor.stories.tsx +2 -2
  65. package/src/DocumentEditor.test.tsx +37 -7
  66. package/src/DocumentEditor.tsx +2 -1
  67. package/src/LinkCard.mdx +9 -5
  68. package/src/LinkCard.stories.tsx +17 -2
  69. package/src/LinkCard.test.tsx +21 -0
  70. package/src/LinkCard.tsx +35 -16
  71. package/src/LinkChip.mdx +6 -1
  72. package/src/LinkChip.stories.tsx +7 -1
  73. package/src/LinkChip.test.tsx +12 -0
  74. package/src/LinkChip.tsx +6 -2
  75. package/src/LinkChips.mdx +4 -3
  76. package/src/LinkChips.stories.tsx +2 -2
  77. package/src/LinkChips.test.tsx +1 -2
  78. package/src/LinkChips.ts +2 -1
  79. package/src/LinkParts.mdx +3 -2
  80. package/src/LinkParts.stories.tsx +8 -0
  81. package/src/LinkParts.tsx +40 -6
  82. package/src/LinkPlaces.mdx +3 -0
  83. package/src/LinkPlaces.ts +19 -0
  84. package/src/LinkRow.mdx +8 -2
  85. package/src/LinkRow.stories.tsx +14 -2
  86. package/src/LinkRow.test.tsx +31 -1
  87. package/src/LinkRow.tsx +69 -25
  88. package/src/PartCard.mdx +9 -1
  89. package/src/PartCard.stories.tsx +9 -0
  90. package/src/PartCard.test.tsx +13 -0
  91. package/src/PartCard.tsx +19 -5
  92. package/src/ReferenceCards.test.tsx +4 -35
  93. package/src/ReferenceCards.ts +10 -119
  94. package/src/ReferenceMenu.mdx +6 -4
  95. package/src/ReferenceMenu.test.tsx +67 -5
  96. package/src/ReferenceMenu.tsx +18 -7
  97. package/src/editor.ts +0 -3
  98. package/src/index.ts +4 -1
  99. package/src/linked.examples.ts +6 -0
  100. package/src/linked.test.ts +35 -1
  101. package/src/linked.ts +108 -3
  102. package/src/linkedFrom.test.tsx +42 -2
  103. package/src/linkedFrom.ts +15 -7
  104. package/src/registry/registry.test.ts +25 -6
  105. package/src/ReferenceCards.mdx +0 -86
  106. package/src/ReferenceCards.stories.tsx +0 -66
@@ -5,15 +5,14 @@
5
5
  * after its line and keeps its element while the line lives.
6
6
  */
7
7
  import { afterEach, describe, expect, it } from 'vitest'
8
- import { act, cleanup, render } from '@testing-library/react'
9
- import { createPortal } from 'react-dom'
8
+ import { cleanup } from '@testing-library/react'
10
9
  import { Editor } from '@tiptap/core'
11
10
  import { NodeSelection, TextSelection } from '@tiptap/pm/state'
12
11
  import StarterKit from '@tiptap/starter-kit'
13
12
  import { BlockId, ReferenceNode } from './BlockNodes'
14
- import { ReferenceCards, referenceAtSelection, referenceCardPlacements, setReferenceCard, useReferenceCards } from './ReferenceCards'
13
+ import { referenceAtSelection, referenceCardPlacements, setReferenceCard } from './ReferenceCards'
15
14
 
16
- const EXTENSIONS = [StarterKit, BlockId, ReferenceNode, ReferenceCards]
15
+ const EXTENSIONS = [StarterKit, BlockId, ReferenceNode]
17
16
  const V = 'nostr:naddr1example'
18
17
  const W = 'nostr:naddr1other'
19
18
 
@@ -55,7 +54,7 @@ describe('ReferenceNode keeps the card', () => {
55
54
  })
56
55
 
57
56
  describe('referenceCardPlacements', () => {
58
- it('asks for a slot after each line whose chips chose a card, keyed by block id', () => {
57
+ it('finds each line whose chips chose a card, keyed by block id', () => {
59
58
  editor = new Editor({ extensions: EXTENSIONS, content: DOCUMENT })
60
59
  const placements = referenceCardPlacements(editor.state.doc)
61
60
  expect(placements.map((p) => [p.key, p.cards])).toEqual([
@@ -64,14 +63,6 @@ describe('referenceCardPlacements', () => {
64
63
  ['b:i1', [{ uri: W, layout: 'compact' }]],
65
64
  ])
66
65
  })
67
-
68
- it('draws an empty, non-editable slot inside the line', () => {
69
- editor = new Editor({ extensions: EXTENSIONS, content: DOCUMENT })
70
- const slot = editor.view.dom.querySelector('[data-reference-cards="b:p1"]')
71
- expect(slot?.getAttribute('contenteditable')).toBe('false')
72
- expect(slot?.closest('p')?.textContent).toContain('for now')
73
- expect(editor.view.dom.querySelectorAll('[data-reference-cards]')).toHaveLength(2)
74
- })
75
66
  })
76
67
 
77
68
  describe('choosing a card', () => {
@@ -119,25 +110,3 @@ describe('choosing a card', () => {
119
110
  expect(setReferenceCard(editor, 'compact')).toBe(false)
120
111
  })
121
112
  })
122
-
123
- describe('useReferenceCards', () => {
124
- function Cards({ ed }: { ed: Editor }) {
125
- const slots = useReferenceCards(ed)
126
- return <>{slots.map((s) => createPortal(<span data-card={s.cards.map((c) => c.layout).join(',')} />, s.element, s.key))}</>
127
- }
128
-
129
- it('portals the app\'s cards into the slots, and typing keeps the slot\'s element', () => {
130
- editor = new Editor({ extensions: EXTENSIONS, content: DOCUMENT })
131
- const ed = editor
132
- render(<Cards ed={ed} />)
133
- const before = ed.view.dom.querySelector('[data-reference-cards="b:p1"]')
134
- expect(before?.querySelector('[data-card="detailed"]')).not.toBeNull()
135
-
136
- act(() => {
137
- ed.commands.insertContentAt(1, 'Still ')
138
- })
139
- const after = ed.view.dom.querySelector('[data-reference-cards="b:p1"]')
140
- expect(after).toBe(before)
141
- expect(after?.querySelector('[data-card="detailed"]')).not.toBeNull()
142
- })
143
- })
@@ -1,28 +1,16 @@
1
1
  /**
2
- * The cards a block document's writer chose, drawn after the line that holds
3
- * each reference — SPEC §13.3, "A reference's card".
2
+ * The card a block document's writer chose for a reference — SPEC §13.3, "A
3
+ * reference's card": `embed` on the `reference` node (`ReferenceNode`), so the
4
+ * card moves and goes with its chip. `ReferenceMenu` writes it (Show as Row or
5
+ * Card) and `LinkPlaces` draws it in the row's place.
4
6
  *
5
- * The choice is `embed` on the `reference` node (`ReferenceNode`), so the card
6
- * moves and goes with its chip. What a card looks like is the app's — it knows
7
- * how to resolve an object and draw its row or its card — so this extension
8
- * draws nothing itself: after every textblock whose chips ask for a card it
9
- * places one empty, non-editable slot, and `useReferenceCards` hands the app
10
- * those slots to portal its cards into. A portal, rather than a React root per
11
- * slot, keeps the app's providers around the card.
12
- *
13
- * **A slot keeps its element while its block lives.** It is keyed by the
14
- * nearest block id (the `blockId` attribute), so typing above a card does not
15
- * re-make its element, and the card does not reload on every keystroke.
16
- *
17
- * The slot sits at the end of the textblock, inside it: a paragraph's card is
18
- * under the paragraph, a list item's under the item at its indent, a table
19
- * cell's in the cell.
7
+ * The extension that placed a slot after each line for the app's card, and its
8
+ * hook, were deprecated by `LinkPlaces` and are gone (Katerina's widget review,
9
+ * 30 Oct): no app used them. What stays reads and writes the choice.
20
10
  */
21
- import { Extension, type Editor } from '@tiptap/core'
11
+ import type { Editor } from '@tiptap/core'
22
12
  import type { Node as PmNode } from '@tiptap/pm/model'
23
- import { NodeSelection, Plugin, PluginKey, type EditorState } from '@tiptap/pm/state'
24
- import { Decoration, DecorationSet } from '@tiptap/pm/view'
25
- import { useEffect, useState } from 'react'
13
+ import { NodeSelection, type EditorState } from '@tiptap/pm/state'
26
14
 
27
15
  /** A layout a writer can choose; `none` is no card. */
28
16
  export type ReferenceCardLayout = 'none' | 'compact' | 'detailed'
@@ -33,16 +21,9 @@ export interface ReferenceCard {
33
21
  layout: Exclude<ReferenceCardLayout, 'none'>
34
22
  }
35
23
 
36
- /** One slot: where an app draws the cards of one line. */
37
- export interface ReferenceCardSlot {
38
- key: string
39
- element: HTMLElement
40
- cards: ReferenceCard[]
41
- }
42
-
43
24
  interface Placement {
44
25
  key: string
45
- /** The end of the textblock's content, where the slot goes. */
26
+ /** The end of the textblock's content. */
46
27
  pos: number
47
28
  cards: ReferenceCard[]
48
29
  }
@@ -79,96 +60,6 @@ export function referenceCardPlacements(doc: PmNode): Placement[] {
79
60
  return out
80
61
  }
81
62
 
82
- interface ReferenceCardsStorage {
83
- /** One element per slot key, made once and reused, so the app's portal stays put. */
84
- elements: Map<string, HTMLElement>
85
- }
86
-
87
- const key = new PluginKey<DecorationSet>('referenceCards')
88
-
89
- function elementFor(storage: ReferenceCardsStorage, slotKey: string): HTMLElement {
90
- let element = storage.elements.get(slotKey)
91
- if (!element) {
92
- element = document.createElement('div')
93
- element.setAttribute('data-reference-cards', slotKey)
94
- element.setAttribute('contenteditable', 'false')
95
- storage.elements.set(slotKey, element)
96
- }
97
- return element
98
- }
99
-
100
- function storageOf(editor: Editor): ReferenceCardsStorage | undefined {
101
- return (editor.storage as unknown as { referenceCards?: ReferenceCardsStorage }).referenceCards
102
- }
103
-
104
- /**
105
- * Places a slot after each line whose chips ask for a card. Pair it with
106
- * `ReferenceNode`, and draw the cards with `useReferenceCards`.
107
- */
108
- export const ReferenceCards = Extension.create<Record<string, never>, ReferenceCardsStorage>({
109
- name: 'referenceCards',
110
- addStorage() {
111
- return { elements: new Map() }
112
- },
113
- addProseMirrorPlugins() {
114
- const storage = this.storage
115
- const decorate = (doc: PmNode) =>
116
- DecorationSet.create(
117
- doc,
118
- referenceCardPlacements(doc).map((p) =>
119
- Decoration.widget(p.pos, () => elementFor(storage, p.key), {
120
- key: p.key,
121
- side: 1,
122
- ignoreSelection: true,
123
- // A click on a card is the card's, not a caret placement in the line.
124
- stopEvent: () => true,
125
- }),
126
- ),
127
- )
128
- return [
129
- new Plugin<DecorationSet>({
130
- key,
131
- state: {
132
- init: (_, state) => decorate(state.doc),
133
- apply: (tr, set) => (tr.docChanged ? decorate(tr.doc) : set),
134
- },
135
- props: { decorations: (state) => key.getState(state) },
136
- }),
137
- ]
138
- },
139
- })
140
-
141
- /**
142
- * The slots to draw cards into, kept current as the document changes. Draw
143
- * each with `createPortal(<cards/>, slot.element)`, keyed by `slot.key`.
144
- */
145
- export function useReferenceCards(editor: Editor | null): ReferenceCardSlot[] {
146
- const [slots, setSlots] = useState<ReferenceCardSlot[]>([])
147
- useEffect(() => {
148
- if (!editor) return
149
- const storage = storageOf(editor)
150
- if (!storage) return
151
- let last = ''
152
- const read = () => {
153
- if (editor.isDestroyed) return
154
- const next = referenceCardPlacements(editor.state.doc).map((p) => ({ key: p.key, element: elementFor(storage, p.key), cards: p.cards }))
155
- // Only a change in what is drawn re-renders the app; typing does not.
156
- const signature = JSON.stringify(next.map((s) => [s.key, s.cards]))
157
- if (signature === last) return
158
- last = signature
159
- const live = new Set(next.map((s) => s.key))
160
- for (const k of storage.elements.keys()) if (!live.has(k)) storage.elements.delete(k)
161
- setSlots(next)
162
- }
163
- read()
164
- editor.on('transaction', read)
165
- return () => {
166
- editor.off('transaction', read)
167
- }
168
- }, [editor])
169
- return slots
170
- }
171
-
172
63
  /**
173
64
  * The chip the person has selected, with what it names and its card — or null.
174
65
  *
@@ -48,8 +48,9 @@ const editor = useEditor({
48
48
 
49
49
  - **A click on a link while editing** — its chip, row or card — opens the menu
50
50
  under it, instead of following it. Not editing, the click follows it. A
51
- card's own controls (its status, its owner) take their click while editing
52
- too.
51
+ card's own links and controls take their click while editing too: its title
52
+ opens the file, its count the conversation, its status and owner change it.
53
+ Only a click on the card's empty space opens the menu.
53
54
  - **A link just put in alone on its line** — pasted, picked with `[`, or a
54
55
  pasted URL becoming its chip — opens the menu by itself. It takes no focus:
55
56
  typing on closes it, and nothing is written. In a sentence it does not open:
@@ -60,8 +61,9 @@ const editor = useEditor({
60
61
  - **Open** does what a click on the link does when reading: the app's link gets
61
62
  the click. A link with nothing to click opens its URL in a new tab.
62
63
  - Open is offered only when there is something to open: the link's own
63
- control, or its URL. A link in a sentence with neither has no menu, and a
64
- click goes on to it.
64
+ control as the app drew it, or its URL. A person, and a link still loading
65
+ or not available, have neither: no Open. A link in a sentence with neither
66
+ has no menu, and a click goes on to it.
65
67
  - The menu closes when the editor loses focus, so a card is never chosen after
66
68
  the editor has saved on leaving.
67
69
  - Choosing Row or Card is an undo step; the menu closes.
@@ -260,13 +260,14 @@ describe('ReferenceMenu', () => {
260
260
  })
261
261
 
262
262
  describe('ReferenceMenuView', () => {
263
- /** The app's drawing: a link, named by its place, that follows on a click. */
263
+ /** The app's drawing: a link, named by its place, that follows on a click; a card has room around its link. */
264
264
  function Linked({ uri, place = 'chip' }: ReferenceViewProps) {
265
- return (
265
+ const link = (
266
266
  <a href={`/o/${uri}`} data-place={place} onClick={(event) => (followed(uri), event.preventDefault())}>
267
267
  Item
268
268
  </a>
269
269
  )
270
+ return place === 'card' ? <span data-testid="card">{link} Summary</span> : link
270
271
  }
271
272
  const followed = vi.fn()
272
273
 
@@ -323,7 +324,8 @@ describe('ReferenceMenuView', () => {
323
324
  await waitFor(() => expect(screen.getByRole('link', { name: 'Item' }).getAttribute('data-place')).toBe('card'))
324
325
  await waitFor(() => expect(screen.queryByRole('menu', { name: 'Link' })).toBeNull())
325
326
 
326
- fireEvent.click(screen.getByRole('link', { name: 'Item' }))
327
+ // On a card, its empty space opens the menu; its own link takes the click (below).
328
+ fireEvent.click(screen.getByTestId('card'))
327
329
  expect((await screen.findByRole('menuitemradio', { name: 'Card' })).getAttribute('aria-checked')).toBe('true')
328
330
  fireEvent.mouseDown(screen.getByRole('menuitemradio', { name: 'Row' }))
329
331
  // Row writes no `embed` at all, not `none`.
@@ -370,17 +372,77 @@ describe('ReferenceMenuView', () => {
370
372
  expect(isReferenceMenuOpen(editor!.state)).toBe(false)
371
373
  })
372
374
 
373
- it('offers Open at once on a link picked on an empty line, before the app has drawn it', async () => {
375
+ it('offers Open on a link picked on an empty line once the app has drawn it', async () => {
374
376
  render(<Harness content={para()} />)
375
377
  await screen.findByRole('textbox')
376
378
  act(() => {
377
- editor!.commands.focus('end')
379
+ editor!.commands.setTextSelection(editor!.state.doc.content.size - 1)
378
380
  editor!.commands.insertContent([ref(V), { type: 'text', text: ' ' }])
379
381
  })
380
382
  expect((await screen.findAllByRole('menuitem', { name: 'Open' })).length).toBe(1)
381
383
  expect(screen.getByRole('menuitemradio', { name: 'Row' }).getAttribute('aria-checked')).toBe('true')
382
384
  })
383
385
 
386
+ it('follows a click on a card\'s own link while editing; its empty space opens the menu', async () => {
387
+ followed.mockClear()
388
+ render(<Harness content={para(ref(V, 'detailed'))} />)
389
+ fireEvent.click(await screen.findByRole('link', { name: 'Item' }))
390
+ expect(followed).toHaveBeenCalledWith(V)
391
+ expect(isReferenceMenuOpen(editor!.state)).toBe(false)
392
+ fireEvent.click(screen.getByTestId('card'))
393
+ expect(followed).toHaveBeenCalledTimes(1)
394
+ await screen.findByRole('menuitemradio', { name: 'Card' })
395
+ })
396
+
397
+ it('keeps a press on a card\'s picker from the text, so the caret does not take it and close the picker', async () => {
398
+ function WithPicker({ place = 'chip' }: ReferenceViewProps) {
399
+ return place === 'card' ? (
400
+ <span>
401
+ <button type="button">
402
+ <span>Status</span>
403
+ </button>
404
+ <span>Summary</span>
405
+ </span>
406
+ ) : (
407
+ <span>Item</span>
408
+ )
409
+ }
410
+ function PickerHarness() {
411
+ const e = useEditor({ extensions: [StarterKit.configure({ link: false }), BlockId, ReferenceNode.configure({ view: WithPicker }), LinkPlaces, ReferenceMenu], content: para(ref(V, 'detailed')) })
412
+ editor = e ?? undefined
413
+ return <EditorContent editor={e} />
414
+ }
415
+ render(<PickerHarness />)
416
+ // fireEvent answers false when the press's default was prevented, which ProseMirror leaves alone.
417
+ expect(fireEvent.mouseDown(await screen.findByText('Status'))).toBe(false)
418
+ })
419
+
420
+ it('offers no Open on a link the app draws with nothing to click (a person, loading, not available), and no menu in a sentence', async () => {
421
+ // As the kit's chip draws a link still loading or not available, and a person with no page: words, no link.
422
+ const Words = () => <span>Item</span>
423
+ function WordsHarness({ content }: { content: Record<string, unknown> }) {
424
+ const e = useEditor({ extensions: [StarterKit.configure({ link: false }), BlockId, ReferenceNode.configure({ view: Words }), LinkPlaces, ReferenceMenu], content })
425
+ editor = e ?? undefined
426
+ return (
427
+ <>
428
+ <EditorContent editor={e} />
429
+ <ReferenceMenuView editor={e} />
430
+ </>
431
+ )
432
+ }
433
+ render(<WordsHarness content={para(ref(V))} />)
434
+ fireEvent.click(await screen.findByText('Item'))
435
+ await screen.findByRole('menuitemradio', { name: 'Card' })
436
+ expect(screen.queryByRole('menuitem', { name: 'Open' })).toBeNull()
437
+ cleanup()
438
+ editor?.destroy()
439
+
440
+ render(<WordsHarness content={para({ type: 'text', text: 'See ' }, ref(V))} />)
441
+ fireEvent.click(await screen.findByText('Item'))
442
+ expect(isReferenceMenuOpen(editor!.state)).toBe(false)
443
+ expect(screen.queryByRole('menu', { name: 'Link' })).toBeNull()
444
+ })
445
+
384
446
  it('lets a click follow the link when the editor is not editable', async () => {
385
447
  followed.mockClear()
386
448
  render(<Harness content={para(ref(V))} />)
@@ -19,7 +19,9 @@
19
19
  *
20
20
  * Open does what a click on the chip does when reading: the app's own chip
21
21
  * gets the click, so it opens where the app opens it. A chip with nothing to
22
- * click opens its URL in a new tab.
22
+ * click opens its URL in a new tab; one with neither — a person, a link still
23
+ * loading or not available — offers no Open, and a menu left with nothing in
24
+ * it does not open.
23
25
  *
24
26
  * Two parts: the extension `ReferenceMenu` holds which chip the menu is open
25
27
  * on, and `ReferenceMenuView` draws it beside `EditorContent`. Pair them with
@@ -27,7 +29,7 @@
27
29
  *
28
30
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md
29
31
  */
30
- import { useCallback } from 'react'
32
+ import { useCallback, useEffect, useReducer } from 'react'
31
33
  import { Extension, type Editor } from '@tiptap/core'
32
34
  import { useEditorState } from '@tiptap/react'
33
35
  import { NodeSelection, Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state'
@@ -74,13 +76,13 @@ function webHref(view: EditorView, pos: number): string {
74
76
 
75
77
  /**
76
78
  * The menu's rows: Open when there is something to open — the link's own
77
- * control, or its URL — and Row and Card when it is alone on its line and is
78
- * neither a person nor a Folder (`linkPlaceAt`).
79
+ * control as the app drew it, or its URL — and Row and Card when it is alone
80
+ * on its line and is neither a person nor a Folder (`linkPlaceAt`). A person,
81
+ * and a link still loading or not available, draw nothing to click: no Open
82
+ * (Katerina, 30 Oct). The view asks again as the app's drawing changes.
79
83
  */
80
84
  function rowsOf(view: EditorView, pos: number): Row[] {
81
- // A link the app draws has its own control even before React has drawn it, as right after a `[` pick.
82
- const drawn = !!view.state.doc.nodeAt(pos)?.attrs.uri && !!view.someProp('nodeViews', (views) => views?.reference)
83
- const open: Row[] = drawn || chipTarget(view, pos) || webHref(view, pos) ? ['open'] : []
85
+ const open: Row[] = chipTarget(view, pos) || webHref(view, pos) ? ['open'] : []
84
86
  return linkPlaceAt(view.state.doc, pos) === 'chip' ? open : [...open, ...SHOW_AS.map((show) => show.as)]
85
87
  }
86
88
 
@@ -290,6 +292,15 @@ export function ReferenceMenuView({ editor }: ReferenceMenuViewProps) {
290
292
  const live = shown && editor && !editor.isDestroyed ? editor : null
291
293
  const dom = live && shown ? live.view.nodeDOM(shown.pos) : null
292
294
  const anchor = dom instanceof HTMLElement ? dom : null
295
+ // Whether there is something to open is the app's drawing, which can arrive after the menu (right after a `[` pick)
296
+ // or change under it (a link that loads): the rows are asked again when it does.
297
+ const [, redraw] = useReducer((count: number) => count + 1, 0)
298
+ useEffect(() => {
299
+ if (!anchor || typeof MutationObserver === 'undefined') return
300
+ const observer = new MutationObserver(redraw)
301
+ observer.observe(anchor, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] })
302
+ return () => observer.disconnect()
303
+ }, [anchor])
293
304
  const rows = live && shown ? rowsOf(live.view, shown.pos) : []
294
305
  const opens = rows[0] === 'open'
295
306
  const showAs = rows.includes('card')
package/src/editor.ts CHANGED
@@ -103,15 +103,12 @@ export {
103
103
  type AttachmentViewProps,
104
104
  } from './BlockNodes'
105
105
  export {
106
- ReferenceCards,
107
- useReferenceCards,
108
106
  referenceAtSelection,
109
107
  referenceCardPlacements,
110
108
  setReferenceCard,
111
109
  setReferenceCardAt,
112
110
  type ReferenceCard,
113
111
  type ReferenceCardLayout,
114
- type ReferenceCardSlot,
115
112
  } from './ReferenceCards'
116
113
  export { LinkChips, findLinkChips, refreshLinkChips, type LinkChipsOptions, type PastedRange } from './LinkChips'
117
114
  export { LinkPlaces, linkPlaceAt, staysChip, type LinkPlace } from './LinkPlaces'
package/src/index.ts CHANGED
@@ -87,6 +87,7 @@ export { Toolbar, ToolbarButton, ToolbarInput, ToolbarLink, ToolbarSeparator, ty
87
87
  export { PreviewCard, type PreviewCardProps } from './PreviewCard'
88
88
  // How a link draws, wherever it sits: one kit for every app (Widgets 2).
89
89
  export {
90
+ cardShapeMemory,
90
91
  chosenOf,
91
92
  inTheBox,
92
93
  loadingShapeOf,
@@ -98,6 +99,8 @@ export {
98
99
  type LinkedPerson,
99
100
  type LinkedPicker,
100
101
  type LinkedStatus,
102
+ type CardShape,
103
+ type CardShapeMemory,
101
104
  type LinkState,
102
105
  type LoadingShape,
103
106
  type PickerOption,
@@ -120,7 +123,7 @@ export { LinkRow, LinkUnavailable, type LinkRowProps, type LinkUnavailableProps
120
123
  export { LinkCard, LinkCardLoading, type LinkCardProps, type LinkCardLoadingProps } from './LinkCard'
121
124
  export { LinkPreview, LinkPreviewOpen, useCanHover, type LinkPreviewProps } from './LinkPreview'
122
125
  export { AttachedCard, type AttachedCardProps } from './AttachedCard'
123
- export { PartCard, type PartCardProps } from './PartCard'
126
+ export { PartCard, type PartCardProps, type PartCardState } from './PartCard'
124
127
  export { Person, type PersonProps } from './Person'
125
128
  export { Rail, type RailProps } from './Rail'
126
129
  export { RailItem, type RailItemProps } from './RailItem'
@@ -105,3 +105,9 @@ export const SAID: Linked = {
105
105
  export const ready = (linked: Linked): LinkState => ({ state: 'ready', linked })
106
106
  export const LOADING: LinkState = { state: 'loading', kind: 'issue' }
107
107
  export const UNAVAILABLE: LinkState = { state: 'unavailable', kind: 'issue', noun: 'Issue', openIn: { app: 'App one', href: '#elsewhere' } }
108
+ /** Deleted, as a trusted deletion naming its address says: told apart from not available (SPEC §13.6.1). */
109
+ export const DELETED: LinkState = { state: 'unavailable', kind: 'issue', noun: 'Issue', deleted: true }
110
+ /** Written as a URL that cannot be shown: it stays that URL. */
111
+ export const WRITTEN_AS_A_URL: LinkState = { state: 'unavailable', kind: 'issue', noun: 'Issue', url: 'https://app.example/item/one' }
112
+ /** The item, archived: its row and card say so, and its values read as words. */
113
+ export const ITEM_ARCHIVED: Linked = { ...ITEM_READ_ONLY, archived: true }
@@ -5,10 +5,44 @@
5
5
  * when the link can be read again or at sign-out.
6
6
  */
7
7
  import { afterEach, describe, expect, it } from 'vitest'
8
- import { unavailableMemory } from './linked'
8
+ import { cardShapeMemory, unavailableMemory } from './linked'
9
9
 
10
10
  afterEach(() => localStorage.clear())
11
11
 
12
+ describe('cardShapeMemory', () => {
13
+ const SHAPE = { subtitle: true, summary: true, rows: 2, latest: false, ring: true, footer: 'pickers' as const, height: 180 }
14
+
15
+ it('remembers the shape a card drew at across a reload, and nothing for one never drawn', () => {
16
+ cardShapeMemory('test.shapes').note('a', SHAPE)
17
+ expect(cardShapeMemory('test.shapes').of('a', 'issue')).toEqual(SHAPE)
18
+ expect(cardShapeMemory('test.shapes').of('b', 'issue')).toBeUndefined()
19
+ })
20
+
21
+ it('answers the app’s first shape for a kind it has not drawn yet', () => {
22
+ const memory = cardShapeMemory('test.shapes', { firstDraw: { issue: { summary: false, footer: 'pickers' } } })
23
+ expect(memory.of('b', 'issue')).toEqual({ summary: false, footer: 'pickers' })
24
+ expect(memory.of('b', 'project')).toBeUndefined()
25
+ })
26
+
27
+ it('keeps only the parts a placeholder draws, and a bad stored value draws no page of bars', () => {
28
+ localStorage.setItem('test.shapes', JSON.stringify([['a', { rows: 9999, footer: 'nonsense', height: -4, extra: 'x' }], ['b', 'not a shape'], 'junk']))
29
+ expect(cardShapeMemory('test.shapes').of('a', 'issue')).toEqual({ subtitle: false, summary: false, rows: 10, latest: false, ring: false, footer: 'line' })
30
+ expect(cardShapeMemory('test.shapes').of('b', 'issue')).toBeUndefined()
31
+ })
32
+
33
+ it('keeps only the newest, up to its limit, and forgets everything at sign-out', () => {
34
+ const memory = cardShapeMemory('test.shapes', { limit: 2 })
35
+ memory.note('a', SHAPE)
36
+ memory.note('b', SHAPE)
37
+ memory.note('c', SHAPE)
38
+ const next = cardShapeMemory('test.shapes', { limit: 2 })
39
+ expect(next.of('a', 'issue')).toBeUndefined()
40
+ expect(next.of('c', 'issue')).toEqual(SHAPE)
41
+ next.clear()
42
+ expect(cardShapeMemory('test.shapes').of('c', 'issue')).toBeUndefined()
43
+ })
44
+ })
45
+
12
46
  describe('unavailableMemory', () => {
13
47
  it('remembers a link it could not show across a reload', () => {
14
48
  unavailableMemory('test.unavailable').note('a', false)
package/src/linked.ts CHANGED
@@ -91,8 +91,14 @@ export interface Linked {
91
91
  href: string
92
92
  /** What the reader calls it, quietly before the title: "ABC-2". */
93
93
  key?: string
94
- /** What the app calls it, from its description of its files: "Issue", "Project", "Topic", "Document". Absent, the kind's own word. */
94
+ /**
95
+ * What it is, in a word, from its app's description of its files: "Issue", "Project", "Topic", "Document"; the app's
96
+ * name when its type has none (record a-file-is-labelled-by-its-type-not-its-app; `linkedFrom` does both). Absent,
97
+ * the kind's own word.
98
+ */
95
99
  noun?: string
100
+ /** Archived: its row and card say "Archived" in the line under the title, and its values read as words. */
101
+ archived?: boolean
96
102
  /** The line under a card's title: what it is in. Drawn after the key. */
97
103
  subtitle?: string
98
104
  /** Its short summary, a sentence or two. Without one a card shows the title alone. */
@@ -136,8 +142,10 @@ export interface LoadingShape {
136
142
 
137
143
  /**
138
144
  * Where a link's lookup stands. `loading` knows the kind from the address, and
139
- * a shape when the app remembers one; `unavailable` is deleted or not the
140
- * reader's to see, which read the same (Miky, 15 Oct).
145
+ * a shape when the app remembers one; `unavailable` is not the reader's to see
146
+ * ("Issue not available"), or `deleted` ("Issue deleted"), which a reader tells
147
+ * apart by a deletion naming the address (SPEC §13.6.1: deleted is not
148
+ * not-permitted). Written as a URL, it is that URL either way (`url`).
141
149
  */
142
150
  export type LinkState =
143
151
  | { state: 'loading'; kind: LinkedKind; shape?: LoadingShape }
@@ -148,6 +156,13 @@ export type LinkState =
148
156
  noun: string
149
157
  /** Where it may still open for someone who can: the app that owns it, and its address. */
150
158
  openIn?: { app: string; href: string }
159
+ /** Deleted, as a trusted deletion naming its address says (SPEC §13.6.1): "Issue deleted", with no way out. */
160
+ deleted?: boolean
161
+ /**
162
+ * The URL it was written as: drawn as that URL, a plain link, in place of "not available" or "deleted" (SPEC
163
+ * §13.1, C21). Those words are only for a link with no URL to fall back on, a `nostr:` reference.
164
+ */
165
+ url?: string
151
166
  }
152
167
  | { state: 'ready'; linked: Linked }
153
168
 
@@ -168,6 +183,96 @@ export function loadingShapeOf(linked: Linked): LoadingShape {
168
183
  }
169
184
  }
170
185
 
186
+ /** A card's shape, and the height it drew at in px: the height holds what the shape cannot say, a summary of two lines. */
187
+ export type CardShape = LoadingShape & { height?: number }
188
+
189
+ /**
190
+ * The shape each card last drew at on this device, so its placeholder the next
191
+ * time is the card's own height and nothing around it moves as it loads
192
+ * (Peek's peek#533 and #534, then Ship's copy). One per app, under its own
193
+ * key, in localStorage because the first paint reads it synchronously; the app
194
+ * clears it with the rest of the device's copy at sign-out.
195
+ */
196
+ export interface CardShapeMemory {
197
+ /** The shape the card for `id` took the last time this device drew it; before that, `firstDraw`'s for its kind, if any. */
198
+ of: (id: string, kind: LinkedKind) => CardShape | undefined
199
+ /** The shape a card just drew at: `loadingShapeOf(linked)`, and the height it measured. */
200
+ note: (id: string, shape: CardShape) => void
201
+ /** Sign-out. */
202
+ clear: () => void
203
+ }
204
+
205
+ const FOOTERS: readonly LoadingFooter[] = ['pickers', 'people', 'line', 'none']
206
+
207
+ /** A stored shape read back, only the parts a placeholder draws; anything else stored there is dropped. */
208
+ function storedCardShape(value: unknown): CardShape | undefined {
209
+ if (!value || typeof value !== 'object') return undefined
210
+ const { subtitle, summary, rows, latest, ring, footer, height } = value as Record<string, unknown>
211
+ return {
212
+ subtitle: subtitle === true,
213
+ summary: summary === true,
214
+ // A card lists a few of its items; a bad number must not draw a page of bars.
215
+ rows: typeof rows === 'number' && Number.isInteger(rows) ? Math.min(Math.max(rows, 0), 10) : 0,
216
+ latest: latest === true,
217
+ ring: ring === true,
218
+ footer: FOOTERS.find((one) => one === footer) ?? 'line',
219
+ ...(typeof height === 'number' && height > 0 && height < 2000 ? { height: Math.round(height) } : {}),
220
+ }
221
+ }
222
+
223
+ /**
224
+ * The device's memory of the shapes its cards drew at, under the app's own
225
+ * `storageKey`, keeping the newest `limit`. `firstDraw` is a kind's shape for
226
+ * a card this device has not drawn yet, where the kit's own placeholder for
227
+ * the kind is not the app's usual card. Peek's and Ship's `cardShapes`, lifted
228
+ * here for Leaf, the third app to need one.
229
+ */
230
+ export function cardShapeMemory(storageKey: string, options: { limit?: number; firstDraw?: Partial<Record<LinkedKind, LoadingShape>> } = {}): CardShapeMemory {
231
+ const { limit = 300, firstDraw = {} } = options
232
+ // Read once per page: a screen of cards asks many times.
233
+ let held: Map<string, CardShape> | undefined
234
+ const shapes = () => {
235
+ if (held) return held
236
+ held = new Map()
237
+ try {
238
+ const stored: unknown = JSON.parse(localStorage.getItem(storageKey) ?? '[]')
239
+ for (const entry of Array.isArray(stored) ? stored : []) {
240
+ const shape = Array.isArray(entry) && typeof entry[0] === 'string' ? storedCardShape(entry[1]) : undefined
241
+ if (shape) held.set(entry[0] as string, shape)
242
+ }
243
+ } catch {
244
+ held = new Map()
245
+ }
246
+ return held
247
+ }
248
+ return {
249
+ of: (id, kind) => shapes().get(id) ?? firstDraw[kind],
250
+ note: (id, shape) => {
251
+ const current = shapes()
252
+ // Already the card drawn last, as it is now: nothing to move or write.
253
+ if ([...current.keys()].at(-1) === id && JSON.stringify(current.get(id)) === JSON.stringify(shape)) return
254
+ const next = new Map(current)
255
+ // Newest last, so the limit drops the cards drawn longest ago.
256
+ next.delete(id)
257
+ next.set(id, shape)
258
+ held = new Map([...next].slice(-limit))
259
+ try {
260
+ localStorage.setItem(storageKey, JSON.stringify([...held]))
261
+ } catch {
262
+ // Full or blocked storage: the shape is still held for this page.
263
+ }
264
+ },
265
+ clear: () => {
266
+ held = undefined
267
+ try {
268
+ localStorage.removeItem(storageKey)
269
+ } catch {
270
+ // Nothing to clear where storage is blocked.
271
+ }
272
+ },
273
+ }
274
+ }
275
+
171
276
  /**
172
277
  * What this device last found it could not show, kept so the next open draws
173
278
  * "not available." from the first paint instead of a card's height that then