@estiva-app/ui 0.101.0 → 0.102.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 (52) hide show
  1. package/dist/AskedBlocks.d.ts +30 -0
  2. package/dist/AskedBlocks.d.ts.map +1 -0
  3. package/dist/DeletedNotice.d.ts +17 -0
  4. package/dist/DeletedNotice.d.ts.map +1 -0
  5. package/dist/DocumentEditor.d.ts +39 -6
  6. package/dist/DocumentEditor.d.ts.map +1 -1
  7. package/dist/LinkRow.d.ts +9 -10
  8. package/dist/LinkRow.d.ts.map +1 -1
  9. package/dist/NoAccessNotice.d.ts +13 -0
  10. package/dist/NoAccessNotice.d.ts.map +1 -0
  11. package/dist/PartCard.d.ts +3 -3
  12. package/dist/PartCard.d.ts.map +1 -1
  13. package/dist/editor.d.ts +1 -1
  14. package/dist/editor.d.ts.map +1 -1
  15. package/dist/editor.js +311 -8
  16. package/dist/editor.js.map +4 -4
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +117 -82
  20. package/dist/index.js.map +4 -4
  21. package/dist/linked.d.ts +4 -2
  22. package/dist/linked.d.ts.map +1 -1
  23. package/dist/linkedFrom.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/registry.json +83 -7
  26. package/src/AskedBlocks.ts +158 -0
  27. package/src/DeletedNotice.mdx +43 -0
  28. package/src/DeletedNotice.stories.tsx +29 -0
  29. package/src/DeletedNotice.test.tsx +46 -0
  30. package/src/DeletedNotice.tsx +47 -0
  31. package/src/DocumentEditor.mdx +5 -1
  32. package/src/DocumentEditor.stories.tsx +84 -0
  33. package/src/DocumentEditor.test.tsx +188 -0
  34. package/src/DocumentEditor.tsx +294 -14
  35. package/src/LinkCard.test.tsx +4 -6
  36. package/src/LinkCard.tsx +1 -1
  37. package/src/LinkRow.mdx +1 -1
  38. package/src/LinkRow.stories.tsx +3 -3
  39. package/src/LinkRow.test.tsx +2 -2
  40. package/src/LinkRow.tsx +13 -20
  41. package/src/NoAccessNotice.mdx +40 -0
  42. package/src/NoAccessNotice.stories.tsx +17 -0
  43. package/src/NoAccessNotice.tsx +18 -0
  44. package/src/PartCard.test.tsx +2 -2
  45. package/src/PartCard.tsx +5 -4
  46. package/src/editor.ts +1 -0
  47. package/src/index.ts +2 -0
  48. package/src/linked.ts +4 -2
  49. package/src/linkedFrom.test.tsx +9 -7
  50. package/src/linkedFrom.ts +4 -3
  51. package/src/registry/registry.test.ts +4 -4
  52. package/stories/Choosing.mdx +2 -0
@@ -212,6 +212,194 @@ describe("someone else's save", () => {
212
212
  await settle()
213
213
  expect(screen.queryByText('Person two saved a newer version.')).toBeNull()
214
214
  })
215
+
216
+ it('with merges, waits with no line: leaving saves yours to be merged onto it', async () => {
217
+ const onCommit = vi.fn(async () => true)
218
+ const { rerender } = render(<Doc merges onCommit={onCommit} />)
219
+ await type(' mine')
220
+ rerender(<Doc merges onCommit={onCommit} value={doc(para('a1', 'Their line'))} changedBy={{ name: 'Person two' }} />)
221
+ await settle()
222
+ expect(screen.queryByText(/saved a newer version/)).toBeNull()
223
+ expect(screen.queryByRole('button', { name: 'Load it' })).toBeNull()
224
+ expect(editorOf().getText()).toBe('First line mine')
225
+ await leave()
226
+ expect(onCommit).toHaveBeenCalledTimes(1)
227
+ })
228
+ })
229
+
230
+ describe('a block you both changed', () => {
231
+ // You and they started from the same text; they saved first.
232
+ const START = doc(para('b1', 'One as written.'), para('b2', 'Two as written.'), para('b3', 'Three as written.'))
233
+ const THEIRS = doc(para('b1', 'One as written.'), para('b2', 'Two: their words.'), para('b3', 'Three: theirs too.'))
234
+ const MINE = doc(para('b1', 'One: my words.'), para('b2', 'Two: my words.'), para('b3', 'Three as written.'))
235
+ // The app's merge as far as it goes: your first block in, their third, and their words in the second, which asks.
236
+ const HELD = doc(para('b1', 'One: my words.'), para('b2', 'Two: their words.'), para('b3', 'Three: theirs too.'))
237
+ const asks = (extra: object = {}) => ({ value: HELD, theirs: THEIRS, mine: MINE, blocks: ['b2'], ...extra })
238
+
239
+ /** You change the first two blocks and leave; the save asks. */
240
+ async function saveThatAsks(onCommit: DocumentEditorProps['onCommit'], props: Partial<DocumentEditorProps> = {}) {
241
+ const view = render(<Doc value={START} onCommit={onCommit} {...props} />)
242
+ await act(async () => {
243
+ const editor = editorOf()
244
+ editor.commands.setContent(codec.read(MINE, 'blocks'))
245
+ })
246
+ await leave()
247
+ await settle()
248
+ return view
249
+ }
250
+ const textNow = () => editorOf().getText({ blockSeparator: '|' })
251
+ const yourVersion = () => document.querySelector('[data-your-version]') as HTMLElement | null
252
+
253
+ it('holds their words in that block and yours beside it, keeps your other changes, and saves nothing until you choose', async () => {
254
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => asks())
255
+ await saveThatAsks(onCommit)
256
+ expect(textNow()).toBe('One: my words.|Two: their words.|Three: theirs too.')
257
+ expect(within(yourVersion()!).getByText('Your version')).toBeTruthy()
258
+ expect(within(yourVersion()!).getByText('Two: my words.')).toBeTruthy()
259
+ expect(document.querySelector('[data-asked-block="b2"]')?.textContent).toContain('Two: their words.')
260
+ // Typing more and leaving again sends nothing while the block asks.
261
+ await type(' More.')
262
+ await leave()
263
+ expect(onCommit).toHaveBeenCalledTimes(1)
264
+ })
265
+
266
+ it('Use mine puts yours in its place and saves after their text', async () => {
267
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>().mockResolvedValueOnce(asks()).mockResolvedValue(true)
268
+ await saveThatAsks(onCommit)
269
+ await act(async () => {
270
+ fireEvent.click(within(yourVersion()!).getByRole('button', { name: 'Use mine' }))
271
+ })
272
+ await settle()
273
+ expect(onCommit).toHaveBeenCalledTimes(2)
274
+ const [value, , editedFrom] = onCommit.mock.calls[1]
275
+ expect(saved(value).map((b) => `${b.id}:${b.runs[0].text}`)).toEqual(['b1:One: my words.', 'b2:Two: my words.', 'b3:Three: theirs too.'])
276
+ expect(editedFrom).toBe(THEIRS)
277
+ expect(yourVersion()).toBeNull()
278
+ })
279
+
280
+ it('Dismiss keeps theirs in that block and saves the rest of yours', async () => {
281
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>().mockResolvedValueOnce(asks()).mockResolvedValue(true)
282
+ await saveThatAsks(onCommit)
283
+ await act(async () => {
284
+ fireEvent.click(within(yourVersion()!).getByRole('button', { name: 'Dismiss' }))
285
+ })
286
+ await settle()
287
+ expect(onCommit).toHaveBeenCalledTimes(2)
288
+ expect(saved(onCommit.mock.calls[1][0]).map((b) => `${b.id}:${b.runs[0].text}`)).toEqual(['b1:One: my words.', 'b2:Two: their words.', 'b3:Three: theirs too.'])
289
+ expect(document.querySelector('[data-asked-block]')).toBeNull()
290
+ })
291
+
292
+ /** You leave with MINE; while that save is out you type `typedSince`; then it asks. */
293
+ async function typedWhileItIsOut(typedSince: ReturnType<typeof doc>) {
294
+ let answer: (asked: ReturnType<typeof asks>) => void = () => {}
295
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(() => new Promise((resolve) => (answer = resolve)))
296
+ render(<Doc value={START} onCommit={onCommit} />)
297
+ await act(async () => {
298
+ editorOf().commands.setContent(codec.read(MINE, 'blocks'))
299
+ })
300
+ await leave()
301
+ await act(async () => {
302
+ editorOf().commands.setContent(codec.read(typedSince, 'blocks'))
303
+ })
304
+ await act(async () => answer(asks()))
305
+ await settle()
306
+ return onCommit
307
+ }
308
+ const yourVersions = () => [...document.querySelectorAll('[data-your-version]')].map((card) => card.textContent)
309
+
310
+ it('what you typed while the save was out stays: in the merge, and as your version of the block that asks', async () => {
311
+ const onCommit = await typedWhileItIsOut(
312
+ doc(para('b1', 'One: my words, and more.'), para('b2', 'Two: my words, and more.'), para('b3', 'Three as written.'), para('b4', 'Four, new.')),
313
+ )
314
+ expect(textNow()).toBe('One: my words, and more.|Two: their words.|Three: theirs too.|Four, new.')
315
+ expect(yourVersions().length).toBeGreaterThan(0)
316
+ expect(yourVersions().every((words) => words?.includes('Two: my words, and more.'))).toBe(true)
317
+ expect(onCommit).toHaveBeenCalledTimes(1)
318
+ })
319
+
320
+ it('a block they changed that you typed in while the save was out asks too', async () => {
321
+ await typedWhileItIsOut(doc(para('b1', 'One: my words.'), para('b2', 'Two: my words.'), para('b3', 'Three: typed while out.')))
322
+ expect(textNow()).toBe('One: my words.|Two: their words.|Three: theirs too.')
323
+ expect(document.querySelector('[data-asked-block="b3"]')).not.toBeNull()
324
+ expect(yourVersions().some((words) => words?.includes('Three: typed while out.'))).toBe(true)
325
+ })
326
+
327
+ it('Copy puts your version on the clipboard and keeps it there to choose', async () => {
328
+ const writeText = vi.fn(async () => {})
329
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
330
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => asks())
331
+ await saveThatAsks(onCommit)
332
+ await act(async () => {
333
+ fireEvent.click(within(yourVersion()!).getByRole('button', { name: 'Copy' }))
334
+ })
335
+ expect(writeText).toHaveBeenCalledWith('Two: my words.')
336
+ expect(within(yourVersion()!).getByRole('button', { name: 'Copied' })).toBeTruthy()
337
+ expect(onCommit).toHaveBeenCalledTimes(1)
338
+ Reflect.deleteProperty(navigator, 'clipboard')
339
+ })
340
+
341
+ it('Load it while a block asks takes theirs whole, and nothing asks after it', async () => {
342
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => asks())
343
+ const { rerender } = await saveThatAsks(onCommit)
344
+ rerender(<Doc value={doc(para('b1', 'Newest.'))} onCommit={onCommit} changedBy={{ name: 'Person two' }} />)
345
+ await settle()
346
+ await act(async () => {
347
+ fireEvent.click(screen.getByRole('button', { name: 'Load it' }))
348
+ })
349
+ await settle()
350
+ expect(textNow()).toBe('Newest.')
351
+ expect(yourVersion()).toBeNull()
352
+ })
353
+
354
+ it('Use mine on a block the text no longer holds brings it back', async () => {
355
+ const theirs = doc(para('b1', 'One as written.'), para('b3', 'Three as written.'))
356
+ const held = doc(para('b1', 'One: my words.'), para('b3', 'Three as written.'))
357
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>().mockResolvedValueOnce({ value: held, theirs, mine: MINE, blocks: ['b2'] }).mockResolvedValue(true)
358
+ await saveThatAsks(onCommit)
359
+ await act(async () => {
360
+ fireEvent.click(within(yourVersion()!).getByRole('button', { name: 'Use mine' }))
361
+ })
362
+ await settle()
363
+ expect(saved(onCommit.mock.calls[1][0]).map((b) => `${b.id}:${b.runs[0].text}`)).toContain('b2:Two: my words.')
364
+ })
365
+
366
+ it('a block they deleted that you changed: Dismiss takes it out', async () => {
367
+ const theirs = doc(para('b1', 'One as written.'), para('b3', 'Three as written.'))
368
+ const held = doc(para('b1', 'One: my words.'), para('b2', 'Two: my words.'), para('b3', 'Three as written.'))
369
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>().mockResolvedValueOnce({ value: held, theirs, mine: MINE, blocks: ['b2'] }).mockResolvedValue(true)
370
+ await saveThatAsks(onCommit)
371
+ await act(async () => {
372
+ fireEvent.click(within(yourVersion()!).getByRole('button', { name: 'Dismiss' }))
373
+ })
374
+ await settle()
375
+ expect(saved(onCommit.mock.calls[1][0]).map((b) => b.id)).toEqual(['b1', 'b3'])
376
+ })
377
+
378
+ it('leaving the page before choosing saves nothing, and hands the app your text with your version of the block', async () => {
379
+ const onLeftUnsaved = vi.fn<(unsaved?: string) => void>()
380
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => asks())
381
+ const { unmount } = await saveThatAsks(onCommit, { onLeftUnsaved })
382
+ unmount()
383
+ await settle()
384
+ expect(onCommit).toHaveBeenCalledTimes(1)
385
+ expect(onLeftUnsaved).toHaveBeenCalledTimes(1)
386
+ expect(saved(onLeftUnsaved.mock.calls[0][0]!).map((b) => `${b.id}:${b.runs[0].text}`)).toEqual(['b1:One: my words.', 'b2:Two: my words.', 'b3:Three: theirs too.'])
387
+ })
388
+
389
+ it('their save showing up afterwards does not replace what you are choosing in', async () => {
390
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => asks())
391
+ const { rerender } = await saveThatAsks(onCommit)
392
+ rerender(<Doc value={THEIRS} onCommit={onCommit} />)
393
+ await settle()
394
+ expect(textNow()).toBe('One: my words.|Two: their words.|Three: theirs too.')
395
+ expect(yourVersion()).toBeTruthy()
396
+ })
397
+
398
+ it('a page opened before the text changed says so above it, in the same shape', async () => {
399
+ await saveThatAsks(async () => asks({ sinceOpened: true }))
400
+ expect(screen.getByText('This page changed since you opened it.')).toBeTruthy()
401
+ expect(yourVersion()).toBeTruthy()
402
+ })
215
403
  })
216
404
 
217
405
  describe('the sign-in ending', () => {
@@ -1,12 +1,16 @@
1
1
  import { useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'
2
+ // @estiva-escape(estiva/no-hand-rolled-behaviour): "Your version" is drawn into the text, in the slot ProseMirror's decoration places at its block's end; nothing floats, so no Base UI part has it.
3
+ import { createPortal } from 'react-dom'
2
4
  import type { AnyExtension } from '@tiptap/core'
3
5
  import { TextSelection } from '@tiptap/pm/state'
4
6
  import { EditorContent, useEditor, useEditorState, type Editor, type JSONContent } from '@tiptap/react'
5
7
  import { TableKit } from '@tiptap/extension-table'
6
- import { IconMessagePlus } from '@tabler/icons-react'
8
+ import { IconCheck, IconCopy, IconMessagePlus } from '@tabler/icons-react'
9
+ import { ASKED_BLOCK_CLASSES, AskedBlocks, blockAt, setAskedBlocks, type AskedSlot } from './AskedBlocks'
7
10
  import type { HandleBlock } from './BlockHandle'
8
11
  import { AttachmentNode, BlockId, Callout, Checklist, ReferenceNode, UnknownBlock, isChecklistTick, type AttachmentViewProps, type ReferenceViewProps } from './BlockNodes'
9
12
  import { Button } from './Button'
13
+ import { Card } from './Card'
10
14
  import { cn } from './cn'
11
15
  import { CodeBlockColours } from './CodeBlockColours'
12
16
  import { CommentHighlights, anchorOfSelection, type SelectionAnchor } from './CommentHighlights'
@@ -23,6 +27,7 @@ import { LinkPlaces } from './LinkPlaces'
23
27
  import { EDITOR_SELECTION_CLASSES } from './looks'
24
28
  import { ReferenceMenu, ReferenceMenuView, isReferenceMenuOpen } from './ReferenceMenu'
25
29
  import { richTextClassName } from './RichText'
30
+ import { SectionLabel } from './SectionLabel'
26
31
  import { KeptSelection, SelectionToolbar } from './SelectionToolbar'
27
32
  import { isSuggestionOpen } from './suggestionPopup'
28
33
 
@@ -88,9 +93,16 @@ export interface DocumentEditorProps {
88
93
  /**
89
94
  * Save. Called when you leave, never while typing, with the text, its format,
90
95
  * and the saved text this edit started from — so the app can tell whom the
91
- * save names anew. Answer whether it was saved.
96
+ * save names anew. Answer whether it was saved, or, when someone changed a
97
+ * block you changed too, what asks ({@link DocumentAsks}).
92
98
  */
93
- onCommit: (value: string, contentFormat: string | undefined, editedFrom: string) => Promise<boolean> | boolean
99
+ onCommit: (value: string, contentFormat: string | undefined, editedFrom: string) => Promise<boolean | DocumentAsks> | boolean | DocumentAsks
100
+ /**
101
+ * Your saves are merged with someone else's (the app merges them by blocks):
102
+ * a newer save arriving while you are in the editor waits with no line, and
103
+ * leaving saves yours merged onto it. Without it, the line with Load it.
104
+ */
105
+ merges?: boolean
94
106
  /** The editor's accessible name. */
95
107
  label: string
96
108
  /** Muted words over an empty editor. */
@@ -99,8 +111,11 @@ export interface DocumentEditorProps {
99
111
  readOnly?: boolean
100
112
  /** Who saved the text last, when it was not you: named in "… saved a newer version". */
101
113
  changedBy?: { name: string } | null
102
- /** A save refused after the editor closed, with nothing left on screen to say it. */
103
- onLeftUnsaved?: () => void
114
+ /**
115
+ * A save refused after the editor closed, with nothing left on screen to say it. Closed while blocks ask, it is
116
+ * handed the text with your version of each, in the saved format, for the app to keep.
117
+ */
118
+ onLeftUnsaved?: (unsaved?: string) => void
104
119
  /** Where text typed when the sign-in ends is held, under `holdKey`. */
105
120
  hold?: HeldTyping
106
121
  holdKey?: string
@@ -135,6 +150,141 @@ export interface DocumentEditorProps {
135
150
  extensions?: readonly AnyExtension[]
136
151
  }
137
152
 
153
+ /**
154
+ * A save refused because someone changed a block you changed too, merged as far
155
+ * as it goes. Nothing of yours is saved until every block that asks is chosen.
156
+ */
157
+ export interface DocumentAsks {
158
+ /** The text to hold now, unsaved: theirs, with every change of yours that did not clash in it, and their words in each block that asks. */
159
+ value: string
160
+ /** Their saved text, which `value` follows: the next save's `editedFrom`. */
161
+ theirs: string
162
+ /** Your text as you saved it: "Your version" of each block is read from it. */
163
+ mine: string
164
+ /** The ids of the blocks that ask: changed by both, or changed by one and deleted by the other. */
165
+ blocks: readonly string[]
166
+ /** The text changed since this page was opened, and the app could not merge it: said above the text. */
167
+ sinceOpened?: boolean
168
+ }
169
+
170
+ const isAsks = (answer: boolean | DocumentAsks): answer is DocumentAsks => typeof answer === 'object' && answer !== null
171
+
172
+ /** The node of the block with this id in a document of the editor's, or `null` when it holds none. */
173
+ function blockOf(doc: JSONContent, id: string): JSONContent | null {
174
+ if (doc.attrs?.blockId === id) return doc
175
+ for (const child of doc.content ?? []) {
176
+ const found = blockOf(child, id)
177
+ if (found) return found
178
+ }
179
+ return null
180
+ }
181
+
182
+ /** The words of a block of the editor's document, as "Your version" shows them: a line per block inside it (a list's items). */
183
+ const wordsOf = (node: JSONContent): string => {
184
+ const children = node.content ?? []
185
+ const inline = children.every((child) => child.text !== undefined || !child.content)
186
+ return (node.text ?? '') + children.map(wordsOf).join(inline ? '' : '\n')
187
+ }
188
+
189
+ /** A document with each of these blocks as `from` has it, or taken out where `from` has none: your text with your version of each block that asks. */
190
+ function withBlocksFrom(doc: JSONContent, ids: readonly string[], from: JSONContent): JSONContent {
191
+ if (!doc.content) return doc
192
+ return {
193
+ ...doc,
194
+ content: doc.content.flatMap((child) => {
195
+ const id = child.attrs?.blockId as string | undefined
196
+ if (id && ids.includes(id)) return blockOf(from, id) ?? []
197
+ return [withBlocksFrom(child, ids, from)]
198
+ }),
199
+ }
200
+ }
201
+
202
+ /** The top-level blocks `to` has changed, added or taken out since `from`. */
203
+ function blocksChanged(from: JSONContent, to: JSONContent): string[] {
204
+ if (from === to) return []
205
+ const before = new Map((from.content ?? []).map((child) => [child.attrs?.blockId as string | undefined, JSON.stringify(child)]))
206
+ const after = new Set<string>()
207
+ const changed: string[] = []
208
+ for (const child of to.content ?? []) {
209
+ const id = child.attrs?.blockId as string | undefined
210
+ if (!id) continue
211
+ after.add(id)
212
+ if (before.get(id) !== JSON.stringify(child)) changed.push(id)
213
+ }
214
+ for (const id of before.keys()) if (id && !after.has(id)) changed.push(id)
215
+ return changed
216
+ }
217
+
218
+ /**
219
+ * The merge with these blocks as you typed them since the save went: changed in place, taken out where you took them
220
+ * out, and a new one after the nearest block before it in your text that the merge still holds.
221
+ */
222
+ function withTypedSince(merged: JSONContent, typedNow: JSONContent, ids: readonly string[]): JSONContent {
223
+ if (ids.length === 0) return merged
224
+ const yours = typedNow.content ?? []
225
+ const content = (merged.content ?? []).flatMap((child) => {
226
+ const id = child.attrs?.blockId as string | undefined
227
+ return id && ids.includes(id) ? (yours.find((block) => block.attrs?.blockId === id) ?? []) : [child]
228
+ })
229
+ yours.forEach((block, i) => {
230
+ const id = block.attrs?.blockId as string | undefined
231
+ if (!id || !ids.includes(id) || content.some((child) => child.attrs?.blockId === id)) return
232
+ let at = 0
233
+ for (let j = i - 1; j >= 0 && at === 0; j--) {
234
+ const before = yours[j].attrs?.blockId as string | undefined
235
+ at = content.findIndex((child) => child.attrs?.blockId === before) + 1
236
+ }
237
+ content.splice(at, 0, block)
238
+ })
239
+ return { ...merged, content }
240
+ }
241
+
242
+ /** Whose version of a block that asks is chosen. */
243
+ type Side = 'mine' | 'theirs'
244
+
245
+ /** What the editor holds while blocks ask. */
246
+ interface Asking {
247
+ blocks: readonly string[]
248
+ mine: JSONContent
249
+ theirs: JSONContent
250
+ sinceOpened: boolean
251
+ }
252
+
253
+ /**
254
+ * Your version, beside the block you both changed. Use mine puts yours in its place; Copy puts yours on the clipboard
255
+ * and keeps it here, so you can paste it and still choose; Dismiss keeps theirs. None of them takes focus from the text.
256
+ */
257
+ function YourVersion({ words, onUseMine, onDismiss }: { words: string; onUseMine: () => void; onDismiss: () => void }) {
258
+ const [copied, setCopied] = useState(false)
259
+ const keep = (event: { preventDefault: () => void }) => event.preventDefault()
260
+ return (
261
+ <Card fill="inset" className="flex flex-col gap-2 p-3" data-your-version="">
262
+ <SectionLabel>Your version</SectionLabel>
263
+ <p className="whitespace-pre-wrap text-body-2 text-text-primary">{words}</p>
264
+ <div className="flex flex-wrap items-center gap-1">
265
+ <Button variant="outlined" size="small" onMouseDown={keep} onClick={onUseMine}>
266
+ Use mine
267
+ </Button>
268
+ <Button
269
+ variant="muted"
270
+ size="small"
271
+ leadingIcon={copied ? <IconCheck size={14} stroke={1.5} /> : <IconCopy size={14} stroke={1.5} />}
272
+ onMouseDown={keep}
273
+ onClick={() => {
274
+ void navigator.clipboard?.writeText(words).catch(() => undefined)
275
+ setCopied(true)
276
+ }}
277
+ >
278
+ {copied ? 'Copied' : 'Copy'}
279
+ </Button>
280
+ <Button variant="muted" size="small" onMouseDown={keep} onClick={onDismiss}>
281
+ Dismiss
282
+ </Button>
283
+ </div>
284
+ </Card>
285
+ )
286
+ }
287
+
138
288
  /** The editor's own document held for this place when the sign-in ended, block ids and all; `null` when none. */
139
289
  function heldDocument(hold: HeldTyping | undefined, key: string | undefined): JSONContent | null {
140
290
  const text = hold && key ? hold.text(key) : undefined
@@ -160,18 +310,26 @@ function heldDocument(hold: HeldTyping | undefined, key: string | undefined): JS
160
310
  * While you are in it, it waits, and a line says who saved a newer version,
161
311
  * with "Load it"; leaving with a change saves yours over it — the later save
162
312
  * wins (Miky, LEAF-3's kickoff and 13 October). Your own save coming back is
163
- * never mistaken for someone else's.
313
+ * never mistaken for someone else's. With `merges`, no line: leaving merges
314
+ * yours onto theirs.
315
+ * - **A block you both changed asks** (`onCommit` answers {@link DocumentAsks}):
316
+ * their words are in the text, marked at the block's edge, and yours sit
317
+ * beside it with Use mine, Copy and Dismiss. Nothing is saved until every
318
+ * block is chosen; the last choice saves. Leaving before that saves nothing
319
+ * and goes to `onLeftUnsaved`.
164
320
  * - **The sign-in ending** holds what was typed (`hold`), and the editor opens
165
321
  * with it, unsaved, after the passkey tap.
166
322
  *
167
323
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-edits-a-document-with-one-shared-editor.md
168
324
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/the-block-editor-kit-lives-in-protocol-and-ui.md
325
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md
169
326
  */
170
327
  export function DocumentEditor({
171
328
  value,
172
329
  format,
173
330
  codec,
174
331
  onCommit,
332
+ merges = false,
175
333
  label,
176
334
  placeholder,
177
335
  readOnly = false,
@@ -240,11 +398,73 @@ export function DocumentEditor({
240
398
  */
241
399
  const picking = useRef(false)
242
400
  const picker = useRef<HTMLInputElement>(null)
401
+ // Blocks a refused save asks about: nothing is saved until each is chosen. The ref is for the callbacks.
402
+ const [asking, setAsking] = useState<Asking | null>(null)
403
+ const askingNow = useRef<Asking | null>(null)
404
+ const ask = (next: Asking | null) => {
405
+ askingNow.current = next
406
+ setAsking(next)
407
+ }
408
+ // While blocks ask, what is lost if the text goes now: the text with your version of each. Otherwise `null`.
409
+ const asked = (): JSONContent | null => {
410
+ const now = askingNow.current
411
+ return now && typed.current ? withBlocksFrom(typed.current, now.blocks, now.mine) : null
412
+ }
413
+ // The editor, for the callbacks made before it is.
414
+ const current = useRef<Editor | null>(null)
415
+ // Where each asking block's "Your version" is drawn: elements the editor's decorations place beside and under the block.
416
+ const slots = useRef(new Map<string, HTMLElement>())
417
+ const slotOf = useCallback((id: string, where: AskedSlot) => {
418
+ const key = `${id} ${where}`
419
+ let slot = slots.current.get(key)
420
+ if (!slot) {
421
+ slot = document.createElement('span')
422
+ slot.className = ASKED_BLOCK_CLASSES[where]
423
+ slot.contentEditable = 'false'
424
+ slots.current.set(key, slot)
425
+ }
426
+ return slot
427
+ }, [])
428
+
429
+ /*
430
+ The save asked: theirs is the saved text now, and the editor holds the
431
+ merge, unsaved, with their words in each block that asks. A value still
432
+ holding what this save replaced is not someone else's. `sent` is the text
433
+ that save carried: what was typed since is kept, in the merge or as your
434
+ version of a block that asks, and a block they changed too asks as well.
435
+ */
436
+ const askAbout = (answer: DocumentAsks, replaced: string, sent: JSONContent) => {
437
+ const { codec: words, format: written } = latest.current
438
+ // Both read back through the codec, so they compare with what the app answers.
439
+ const asRead = (doc: JSONContent) => words.read(words.write(doc).value, written)
440
+ const before = asRead(sent)
441
+ const now = typed.current && typed.current !== sent ? asRead(typed.current) : before
442
+ const since = blocksChanged(before, now)
443
+ const mine = withBlocksFrom(words.read(answer.mine, written), since, now)
444
+ const value = words.read(answer.value, written)
445
+ const theirsToo = (id: string) => !!blockOf(before, id) && JSON.stringify(blockOf(value, id)) !== JSON.stringify(blockOf(before, id))
446
+ const asks = [...answer.blocks, ...since.filter((id) => !answer.blocks.includes(id) && theirsToo(id))]
447
+ // A block that asks must be in the text to be chosen: one they deleted that you changed is held as yours, at the end.
448
+ const missing = asks.flatMap((id) => (blockOf(value, id) ? [] : (blockOf(mine, id) ?? [])))
449
+ const merged = missing.length ? { ...value, content: [...(value.content ?? []), ...missing] } : value
450
+ const held = withTypedSince(merged, now, since.filter((id) => !asks.includes(id)))
451
+ const blocks = asks.filter((id) => blockOf(held, id))
452
+ saved.current = answer.theirs
453
+ shown.current = answer.theirs
454
+ setSuperseded(replaced)
455
+ setBase(answer.theirs)
456
+ const editor = current.current
457
+ if (editor && !editor.isDestroyed) editor.commands.setContent(held, { emitUpdate: false })
458
+ typed.current = held
459
+ ask(blocks.length ? { blocks, mine, theirs: words.read(answer.theirs, written), sinceOpened: !!answer.sinceOpened } : null)
460
+ }
243
461
 
244
462
  const save = useCallback(
245
463
  async (doc: JSONContent | null) => {
246
464
  // Read only: a box ticked in a node view is not a save. After an ending the text is held, and a save would be refused.
247
465
  if (!doc || readOnly || ended()) return
466
+ // Blocks ask: nothing of yours is saved until each is chosen.
467
+ if (askingNow.current) return
248
468
  // A change made while a save is out goes next, not nowhere.
249
469
  if (committing.current) {
250
470
  again.current = true
@@ -258,7 +478,18 @@ export function DocumentEditor({
258
478
  const replaced = latest.current.value
259
479
  const editedFrom = saved.current
260
480
  try {
261
- const ok = await onCommit(next.value, next.contentFormat, editedFrom)
481
+ const answer = await onCommit(next.value, next.contentFormat, editedFrom)
482
+ if (isAsks(answer)) {
483
+ // Closed meanwhile: there is no text left to choose in, and nothing was saved. The app keeps what was sent.
484
+ if (left.current) {
485
+ if (!ended()) latest.current.onLeftUnsaved?.(next.value)
486
+ } else {
487
+ askAbout(answer, replaced, doc)
488
+ setFailed(false)
489
+ }
490
+ return
491
+ }
492
+ const ok = answer
262
493
  if (ok) {
263
494
  // The editor already shows it, and may hold more typed since: `shown` keeps the effect below from setting it.
264
495
  saved.current = next.value
@@ -283,7 +514,7 @@ export function DocumentEditor({
283
514
  } finally {
284
515
  committing.current = false
285
516
  setSaving(false)
286
- if (again.current) {
517
+ if (again.current && !askingNow.current) {
287
518
  again.current = false
288
519
  // After an ending it is held for after the tap, and a save would only be refused. Only a change: leaving
289
520
  // while a blur's save is out asks again for the same text, and a refused one would be sent and said twice.
@@ -302,7 +533,8 @@ export function DocumentEditor({
302
533
  const store = latest.current.hold
303
534
  if (!holds || !store || !holdKey) return
304
535
  return store.register(holdKey, () => {
305
- const doc = typed.current
536
+ // While blocks ask, your version of each is held: the ask itself does not outlive the passkey trip.
537
+ const doc = asked() ?? typed.current
306
538
  return doc && latest.current.codec.write(doc).value !== saved.current ? JSON.stringify(doc) : undefined
307
539
  })
308
540
  }, [holdKey, holds])
@@ -414,11 +646,11 @@ export function DocumentEditor({
414
646
  */
415
647
  const arrived = value !== base && value !== superseded && !own.current.has(value)
416
648
  // Read only, there is nothing of yours to keep: theirs loads even while you select words to comment on.
417
- if (arrived && (readOnly || (!focused && !saving && !failed && !restored))) {
649
+ if (arrived && (readOnly || (!focused && !saving && !failed && !restored && !asking))) {
418
650
  own.current.clear()
419
651
  setBase(value)
420
652
  }
421
- const waiting = arrived && !readOnly && (focused || failed || restored)
653
+ const waiting = arrived && !readOnly && (focused || failed || restored || !!asking)
422
654
 
423
655
  // The text the editor should hold, set into it when it changes — never under your own typing, which `shown` already holds.
424
656
  useEffect(() => {
@@ -441,26 +673,65 @@ export function DocumentEditor({
441
673
  setBase(latest.current.value)
442
674
  setFailed(false)
443
675
  setRestored(false)
676
+ // Theirs replaces yours whole, so nothing is left to choose.
677
+ ask(null)
678
+ slots.current.clear()
444
679
  }
445
680
 
446
681
  // Closing saves on the way out. Not when the sign-in ended: the save would be refused and reported as lost over
447
- // the passkey screen, and the text is held on the device instead.
682
+ // the passkey screen, and the text is held on the device instead. Not while blocks ask: nothing is saved until chosen.
448
683
  useEffect(
449
684
  () => () => {
450
685
  left.current = true
451
- if (!ended()) void latestSave.current(typed.current)
686
+ if (ended()) return
687
+ const draft = asked()
688
+ if (draft) latest.current.onLeftUnsaved?.(latest.current.codec.write(draft).value)
689
+ else void latestSave.current(typed.current)
452
690
  },
453
691
  [],
454
692
  )
455
693
 
456
694
  useEffect(() => {
695
+ current.current = editor
457
696
  onEditor?.(editor)
458
697
  return () => onEditor?.(null)
459
698
  }, [editor, onEditor])
460
699
 
700
+ // The blocks that ask, drawn in the text; none once every one is chosen.
701
+ const askedIds = asking?.blocks
702
+ useEffect(() => {
703
+ if (editor && !editor.isDestroyed) setAskedBlocks(editor, askedIds ?? [], slotOf)
704
+ }, [editor, askedIds, slotOf])
705
+
706
+ /*
707
+ One block chosen: yours or theirs in its place, or the block gone when the
708
+ one chosen deleted it. The last choice saves, after their text.
709
+ */
710
+ const choose = (id: string, side: Side) => {
711
+ const now = askingNow.current
712
+ if (!editor || editor.isDestroyed || !now) return
713
+ const chosen = blockOf(side === 'mine' ? now.mine : now.theirs, id)
714
+ const at = blockAt(editor.state.doc, id)
715
+ if (at) {
716
+ const end = at.pos + at.node.nodeSize
717
+ const tr = chosen ? editor.state.tr.replaceWith(at.pos, end, editor.schema.nodeFromJSON(chosen)) : editor.state.tr.delete(at.pos, end)
718
+ editor.view.dispatch(tr)
719
+ }
720
+ typed.current = editor.getJSON()
721
+ const rest = now.blocks.filter((block) => block !== id)
722
+ if (rest.length > 0) {
723
+ ask({ ...now, blocks: rest })
724
+ return
725
+ }
726
+ ask(null)
727
+ slots.current.clear()
728
+ void latestSave.current(typed.current)
729
+ }
730
+
461
731
  const who = changedBy?.name ?? 'Someone'
462
732
  const drawn = (
463
733
  <div className="flex flex-col gap-1">
734
+ {asking?.sinceOpened && <FieldLine tone="helper">This page changed since you opened it.</FieldLine>}
464
735
  <EditorBlockHandle editor={editor} actions={blockRows}>
465
736
  {/* A table's handles and ➕ bars while you point at it; the block handle stays the table's. */}
466
737
  <EditorTableControls editor={editor}>
@@ -498,7 +769,14 @@ export function DocumentEditor({
498
769
  <ReferenceMenuView editor={editor} />
499
770
  {/* Always there, so `/` → File, made as the editor opened, has a dialog to open even if `upload` came and went. */}
500
771
  <FilePicker ref={picker} multiple onPick={(files) => void attach(files)} />
501
- {waiting && (
772
+ {asking?.blocks.flatMap((id) => {
773
+ const mine = blockOf(asking.mine, id)
774
+ const card = <YourVersion words={mine ? wordsOf(mine) : 'You deleted this block.'} onUseMine={() => choose(id, 'mine')} onDismiss={() => choose(id, 'theirs')} />
775
+ // Beside the words, and under the block at phone width: one is shown at a time (`ASKED_BLOCK_CLASSES`).
776
+ // @estiva-escape(estiva/no-hand-rolled-behaviour): into the block's slot in the text (AskedBlocks), not a floating panel.
777
+ return (['beside', 'under'] as const).map((where) => createPortal(card, slotOf(id, where), `${id} ${where}`))
778
+ })}
779
+ {waiting && !merges && (
502
780
  <FieldLine tone="helper">
503
781
  {`${who} saved a newer version.`}{' '}
504
782
  {/* Pressing it must not take focus from the editor: that blur would save yours over theirs first. */}
@@ -568,6 +846,8 @@ export function documentExtensions({ latest, references, mentions, linkChips, ta
568
846
  CodeBlockColours,
569
847
  TableKit.configure({ table: { resizable: false } }),
570
848
  BlockId,
849
+ // A block a refused save asks about, drawn so a save never carries it.
850
+ AskedBlocks,
571
851
  Checklist,
572
852
  Callout,
573
853
  // A link is being edited only while the caret is on its line: anywhere else on the page it previews on hover.
@@ -122,12 +122,10 @@ describe('LinkCard', () => {
122
122
  expect(screen.queryByRole('link')).toBeNull()
123
123
  })
124
124
 
125
- it('says it is not available, and where it may still open: an "Open" button that links there, in a new tab', () => {
125
+ it('says you cannot open it, with nowhere to go, even where the app names somewhere it opens', () => {
126
126
  render(<LinkCard link={UNAVAILABLE} />)
127
- expect(screen.getByText('Issue not available')).toBeTruthy()
128
- const open = screen.getByRole('link', { name: 'Open in App one' })
129
- expect(open.getAttribute('href')).toBe('#elsewhere')
130
- expect(open.getAttribute('target')).toBe('_blank')
131
- expect(open.textContent).toBe('Open')
127
+ expect(screen.getByText("You can't open this issue")).toBeTruthy()
128
+ expect(screen.queryByRole('link')).toBeNull()
129
+ expect(screen.queryByRole('button')).toBeNull()
132
130
  })
133
131
  })
package/src/LinkCard.tsx CHANGED
@@ -56,7 +56,7 @@ export function LinkCard({ link, readOnly = false, bare = false }: LinkCardProps
56
56
  if (link.state === 'loading') return <LinkCardLoading kind={link.kind} shape={link.shape} />
57
57
  if (link.state === 'unavailable') {
58
58
  if (link.url) return <WrittenUrl url={link.url} block />
59
- return <LinkUnavailable kind={link.kind} noun={link.noun} openIn={link.openIn} deleted={link.deleted} card />
59
+ return <LinkUnavailable kind={link.kind} noun={link.noun} named={link.named} deleted={link.deleted} card />
60
60
  }
61
61
  const { linked } = link
62
62
  const body = linked.kind === 'message' && linked.author ? <SaidBody linked={linked} /> : <CardBody linked={linked} readOnly={readOnly || boxed} />