@estiva-app/ui 0.80.0 → 0.82.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 (40) hide show
  1. package/dist/BlockNodes.d.ts.map +1 -1
  2. package/dist/CardUnder.d.ts +24 -3
  3. package/dist/CardUnder.d.ts.map +1 -1
  4. package/dist/CommentBox.d.ts +39 -5
  5. package/dist/CommentBox.d.ts.map +1 -1
  6. package/dist/ComposerTriggers.d.ts +24 -0
  7. package/dist/ComposerTriggers.d.ts.map +1 -1
  8. package/dist/DocumentEditor.d.ts +138 -0
  9. package/dist/DocumentEditor.d.ts.map +1 -0
  10. package/dist/ReferenceMenu.d.ts.map +1 -1
  11. package/dist/SelectionToolbar.d.ts.map +1 -1
  12. package/dist/editor.d.ts +3 -2
  13. package/dist/editor.d.ts.map +1 -1
  14. package/dist/editor.js +565 -46
  15. package/dist/editor.js.map +4 -4
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +2 -2
  18. package/dist/links.d.ts +28 -0
  19. package/dist/links.d.ts.map +1 -0
  20. package/package.json +7 -1
  21. package/registry.json +199 -10
  22. package/src/BlockNodes.tsx +3 -1
  23. package/src/CardUnder.mdx +1 -0
  24. package/src/CardUnder.tsx +10 -6
  25. package/src/CommentBox.mdx +8 -0
  26. package/src/CommentBox.stories.tsx +62 -2
  27. package/src/CommentBox.test.tsx +169 -1
  28. package/src/CommentBox.tsx +110 -17
  29. package/src/ComposerTriggers.tsx +65 -0
  30. package/src/DocumentEditor.mdx +106 -0
  31. package/src/DocumentEditor.stories.tsx +305 -0
  32. package/src/DocumentEditor.test.tsx +528 -0
  33. package/src/DocumentEditor.tsx +568 -0
  34. package/src/ReferenceMenu.tsx +6 -1
  35. package/src/SelectionToolbar.tsx +2 -1
  36. package/src/editor.ts +13 -0
  37. package/src/gates/create-app.test.ts +3 -1
  38. package/src/links.ts +151 -0
  39. package/src/registry/registry.test.ts +6 -6
  40. package/stories/Choosing.mdx +1 -0
@@ -0,0 +1,528 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * The shared document editor (WBD-3): what its page says it owns — saving when
4
+ * you leave, someone else's save arriving, the text held when the sign-in
5
+ * ends, `[`, `/`, `@`, a link on words, files, and reading. The app's side is
6
+ * played by `@estiva-app/protocol` and `@estiva-app/conversation`, so what is
7
+ * checked is what an app would save and whom it would add.
8
+ */
9
+ import { act } from 'react'
10
+ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
11
+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
12
+ import type { Editor } from '@tiptap/core'
13
+ import { Fragment, Slice } from '@tiptap/pm/model'
14
+ import type { JSONContent } from '@tiptap/react'
15
+ import { documentForEditing, encodeNpub, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
16
+ import { newlyNamedPeople } from '@estiva-app/conversation'
17
+ import type { MentionPerson, ReferenceSection } from './ComposerTriggers'
18
+ import { DocumentEditor, type DocumentCodec, type DocumentEditorProps, type HeldTyping } from './DocumentEditor'
19
+
20
+ const codec: DocumentCodec = {
21
+ read: (value, format) => toEditorDocument(documentForEditing(value, format as ContentFormat), { links: true }) as JSONContent,
22
+ write: (doc) => publishableFromEditor(doc as EditorDocument),
23
+ }
24
+
25
+ const KEY_ONE = 'b'.repeat(64)
26
+ const KEY_TWO = 'c'.repeat(64)
27
+ const PEOPLE: MentionPerson[] = [
28
+ { id: 'one', name: 'Person one', pubkey: KEY_ONE },
29
+ { id: 'two', name: 'Person two', pubkey: KEY_TWO },
30
+ { id: 'three', name: 'Person three', pubkey: null },
31
+ ]
32
+ const mentions = { people: () => PEOPLE, uriOf: (person: MentionPerson) => (person.pubkey ? `nostr:${encodeNpub(person.pubkey)}` : null) }
33
+ const ITEM_URI = 'nostr:naddr1itemone'
34
+ const SECTIONS: ReferenceSection[] = [{ label: 'Group one', items: [{ id: 'item-one', label: 'Item one', snippet: '', uri: ITEM_URI }] }]
35
+ const references = { sections: () => SECTIONS, ariaLabel: 'Items', sectionLabel: 'Items' }
36
+
37
+ /** A block document of paragraphs, each with its id. */
38
+ const doc = (...blocks: object[]) => JSON.stringify({ type: 'doc', content: blocks })
39
+ const para = (id: string, text: string, marks?: object[]) => ({ type: 'paragraph', id, content: [{ type: 'text', text, ...(marks ? { marks } : {}) }] })
40
+
41
+ beforeAll(() => {
42
+ Element.prototype.scrollIntoView = vi.fn()
43
+ Element.prototype.getClientRects = () => [] as unknown as DOMRectList
44
+ Range.prototype.getClientRects = () => [] as unknown as DOMRectList
45
+ Range.prototype.getBoundingClientRect = () => new DOMRect()
46
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
47
+ })
48
+
49
+ afterEach(() => {
50
+ cleanup()
51
+ vi.useRealTimers()
52
+ vi.restoreAllMocks()
53
+ })
54
+
55
+ const editorOf = (): Editor => (document.querySelector('.ProseMirror') as unknown as { editor: Editor }).editor
56
+
57
+ /** Types at `at`, in the editor, as a person would: focused. Tiptap's `focus` command focuses a frame later, so the view is focused now. */
58
+ async function type(text: string, at: number | 'end' = 'end') {
59
+ await act(async () => {
60
+ const editor = editorOf()
61
+ editor.view.focus()
62
+ editor.chain().focus(at).insertContent(text).run()
63
+ })
64
+ }
65
+
66
+ async function press(key: string) {
67
+ await act(async () => {
68
+ const editor = editorOf()
69
+ editor.view.someProp('handleKeyDown', (handle) => handle(editor.view, new KeyboardEvent('keydown', { key })))
70
+ })
71
+ }
72
+
73
+ /** Leaving the editor: its blur, as a click elsewhere gives it. */
74
+ async function leave() {
75
+ await act(async () => {
76
+ // The view's own blur: Tiptap's `blur` command waits a frame.
77
+ const { view } = editorOf()
78
+ view.focus()
79
+ view.dom.blur()
80
+ for (let i = 0; i < 5; i++) await Promise.resolve()
81
+ })
82
+ }
83
+
84
+ /** Lets an answer reach the editor: it passes through a few promises on the way. */
85
+ async function settle() {
86
+ await act(async () => {
87
+ for (let i = 0; i < 5; i++) await Promise.resolve()
88
+ })
89
+ }
90
+
91
+ const options = () => within(screen.getByRole('listbox')).getAllByRole('option').map((one) => one.textContent?.replace('↩ Enter', ''))
92
+
93
+ /** What the saved text holds: each block's id and its runs, a run as its text and its marks. */
94
+ const saved = (value: string) =>
95
+ (JSON.parse(value) as { content: { id: string; content?: { text?: string; marks?: { type: string; attrs?: Record<string, unknown> }[] }[] }[] }).content.map((block) => ({
96
+ id: block.id,
97
+ runs: (block.content ?? []).map((run) => ({ text: run.text, marks: run.marks ?? [] })),
98
+ }))
99
+
100
+ function Doc(props: Partial<DocumentEditorProps>) {
101
+ return <DocumentEditor value={doc(para('a1', 'First line'))} format="blocks" codec={codec} label="Document" onCommit={async () => true} {...props} />
102
+ }
103
+
104
+ describe('saving', () => {
105
+ it('saves when you leave, not while typing, and says which saved text the edit started from', async () => {
106
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
107
+ const start = doc(para('a1', 'First line'))
108
+ render(<Doc value={start} onCommit={onCommit} />)
109
+ await type(' and more')
110
+ expect(onCommit).not.toHaveBeenCalled()
111
+ await leave()
112
+ expect(onCommit).toHaveBeenCalledTimes(1)
113
+ const [value, format, editedFrom] = onCommit.mock.calls[0]
114
+ expect(saved(value)).toEqual([{ id: 'a1', runs: [{ text: 'First line and more', marks: [] }] }])
115
+ expect(format).toBe('estiva-blocks-1')
116
+ expect(editedFrom).toBe(start)
117
+ })
118
+
119
+ it('leaving with nothing changed saves nothing', async () => {
120
+ const onCommit = vi.fn(async () => true)
121
+ render(<Doc onCommit={onCommit} />)
122
+ await act(async () => {
123
+ editorOf().commands.focus()
124
+ })
125
+ await leave()
126
+ expect(onCommit).not.toHaveBeenCalled()
127
+ })
128
+
129
+ it('a refused save keeps the text and says so', async () => {
130
+ render(<Doc onCommit={async () => false} />)
131
+ await type(' kept')
132
+ await leave()
133
+ expect(screen.getByText('Could not save. Your text is still here.')).toBeTruthy()
134
+ expect(editorOf().getText()).toBe('First line kept')
135
+ })
136
+
137
+ it('Escape leaves, and so saves', async () => {
138
+ const onCommit = vi.fn(async () => true)
139
+ render(<Doc onCommit={onCommit} />)
140
+ await type('!')
141
+ await press('Escape')
142
+ await settle()
143
+ expect(onCommit).toHaveBeenCalledTimes(1)
144
+ })
145
+ })
146
+
147
+ describe("someone else's save", () => {
148
+ it('is loaded while you are not in the editor', async () => {
149
+ const { rerender } = render(<Doc />)
150
+ rerender(<Doc value={doc(para('a1', 'Their line'))} changedBy={{ name: 'Person two' }} />)
151
+ await settle()
152
+ expect(editorOf().getText()).toBe('Their line')
153
+ })
154
+
155
+ it('waits while you type, with who saved it, and does not touch your text; Load it takes theirs', async () => {
156
+ const { rerender } = render(<Doc />)
157
+ await type(' mine')
158
+ rerender(<Doc value={doc(para('a1', 'Their line'))} changedBy={{ name: 'Person two' }} />)
159
+ await settle()
160
+ // Who saved it, and what pressing Load it costs.
161
+ expect(screen.getByText(/^Person two saved a newer version\.\s+\(replaces your changes\)$/)).toBeTruthy()
162
+ expect(editorOf().getText()).toBe('First line mine')
163
+ await act(async () => {
164
+ fireEvent.click(screen.getByRole('button', { name: 'Load it' }))
165
+ })
166
+ expect(editorOf().getText()).toBe('Their line')
167
+ })
168
+
169
+ it('your own save coming back is not someone else’s', async () => {
170
+ let value = doc(para('a1', 'First line'))
171
+ const onCommit = vi.fn(async (next: string) => {
172
+ value = next
173
+ return true
174
+ })
175
+ const { rerender } = render(<Doc value={value} onCommit={onCommit} changedBy={{ name: 'Person two' }} />)
176
+ await type(' one')
177
+ await leave()
178
+ await act(async () => {
179
+ editorOf().commands.focus('end')
180
+ })
181
+ rerender(<Doc value={value} onCommit={onCommit} changedBy={{ name: 'Person two' }} />)
182
+ await settle()
183
+ expect(screen.queryByText('Person two saved a newer version.')).toBeNull()
184
+ })
185
+ })
186
+
187
+ describe('the sign-in ending', () => {
188
+ /** An app's held-typing store, by key. */
189
+ function store() {
190
+ const held = new Map<string, string>()
191
+ const readers = new Map<string, () => string | undefined>()
192
+ let ending = false
193
+ const hold: HeldTyping = {
194
+ text: (key) => held.get(key),
195
+ release: (key) => void held.delete(key),
196
+ register: (key, read) => {
197
+ readers.set(key, read)
198
+ return () => {
199
+ readers.delete(key)
200
+ if (!ending) held.delete(key)
201
+ }
202
+ },
203
+ ended: () => ending,
204
+ }
205
+ const end = () => {
206
+ ending = true
207
+ for (const [key, read] of readers) {
208
+ const text = read()
209
+ if (text) held.set(key, text)
210
+ }
211
+ }
212
+ const back = () => {
213
+ ending = false
214
+ }
215
+ return { hold, end, back }
216
+ }
217
+
218
+ it('what was typed is in the editor again, unsaved, when it opens after the tap; nothing was saved on the way out', async () => {
219
+ const { hold, end, back } = store()
220
+ const onCommit = vi.fn(async () => true)
221
+ const first = render(<Doc hold={hold} holdKey="doc-1" onCommit={onCommit} />)
222
+ await type(' typed before the end')
223
+ act(() => end())
224
+ first.unmount()
225
+ await settle()
226
+ expect(onCommit).not.toHaveBeenCalled()
227
+ back()
228
+ render(<Doc hold={hold} holdKey="doc-1" onCommit={onCommit} />)
229
+ expect(editorOf().getText()).toBe('First line typed before the end')
230
+ await leave()
231
+ expect(onCommit).toHaveBeenCalledTimes(1)
232
+ expect(hold.text('doc-1')).toBeUndefined()
233
+ })
234
+
235
+ it('the blur as the editor closes after the ending saves nothing', async () => {
236
+ const { hold, end } = store()
237
+ const onCommit = vi.fn(async () => true)
238
+ render(<Doc hold={hold} holdKey="doc-1" onCommit={onCommit} />)
239
+ await type(' typed before the end')
240
+ act(() => end())
241
+ await leave()
242
+ expect(onCommit).not.toHaveBeenCalled()
243
+ })
244
+ })
245
+
246
+ describe('[ and /', () => {
247
+ it('[ opens the list the app supplies, and a pick puts the chip in the text', async () => {
248
+ render(<Doc references={references} />)
249
+ await type(' [')
250
+ expect(screen.getByRole('listbox', { name: 'Items' })).toBeTruthy()
251
+ await press('Enter')
252
+ const chips: unknown[] = []
253
+ editorOf().state.doc.descendants((node) => void (node.type.name === 'reference' && chips.push(node.attrs.uri)))
254
+ expect(chips).toEqual([ITEM_URI])
255
+ })
256
+
257
+ it('without the app’s lists, [ is a bracket', async () => {
258
+ render(<Doc />)
259
+ await type(' [')
260
+ expect(screen.queryByRole('listbox')).toBeNull()
261
+ })
262
+
263
+ it('/ offers Format and Insert, with Table, File and Link to a file when the app can do each', async () => {
264
+ render(<Doc references={references} upload={async () => ({})} />)
265
+ await type(' /')
266
+ // A row reads as its label and the key it is typed with.
267
+ expect(options()).toEqual(expect.arrayContaining(['Text', 'Checklist[]', 'Note', 'Table', 'File', 'Link to a file[']))
268
+ await press('Escape')
269
+ cleanup()
270
+ render(<Doc />)
271
+ await type(' /')
272
+ expect(options()).not.toContain('File')
273
+ expect(options()).not.toContain('Link to a file[')
274
+ expect(options()).toContain('Table')
275
+ })
276
+
277
+ it('/ → Link to a file opens [’s list', async () => {
278
+ vi.useFakeTimers({ toFake: ['requestAnimationFrame'] })
279
+ render(<Doc references={references} />)
280
+ await type(' /link')
281
+ await press('Enter')
282
+ await act(async () => {
283
+ vi.advanceTimersToNextFrame()
284
+ })
285
+ expect(screen.getByRole('listbox', { name: 'Items' })).toBeTruthy()
286
+ })
287
+ })
288
+
289
+ describe('@', () => {
290
+ it('lists the people the app supplies who have a key, and a pick writes a reference to their npub', async () => {
291
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
292
+ render(<Doc mentions={mentions} onCommit={onCommit} />)
293
+ await type(' @')
294
+ // The names offered; each row also draws the face before its name.
295
+ const offered = options()
296
+ expect(offered).toHaveLength(2)
297
+ expect(offered[0]).toMatch(/Person one$/)
298
+ expect(offered[1]).toMatch(/Person two$/)
299
+ await press('Enter')
300
+ await leave()
301
+ const runs = saved(onCommit.mock.calls[0][0])[0].runs
302
+ expect(runs[1].marks).toEqual([{ type: 'reference', attrs: { uri: `nostr:${encodeNpub(KEY_ONE)}` } }])
303
+ })
304
+
305
+ it('a save that names someone new adds them; a typo fix in a text that already names them adds nobody', async () => {
306
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
307
+ const { unmount } = render(<Doc mentions={mentions} onCommit={onCommit} />)
308
+ await type(' @')
309
+ await press('Enter')
310
+ await leave()
311
+ const [named, , from] = onCommit.mock.calls[0]
312
+ expect(newlyNamedPeople({ content: named, format: 'estiva-blocks-1' }, { content: from, format: 'estiva-blocks-1' })).toEqual([KEY_ONE])
313
+ unmount()
314
+ await settle()
315
+
316
+ onCommit.mockClear()
317
+ render(<Doc value={named} mentions={mentions} onCommit={onCommit} />)
318
+ await type('x', 3)
319
+ await leave()
320
+ const [fixed, , before] = onCommit.mock.calls[0]
321
+ expect(before).toBe(named)
322
+ expect(newlyNamedPeople({ content: fixed, format: 'estiva-blocks-1' }, { content: before, format: 'estiva-blocks-1' })).toEqual([])
323
+ })
324
+ })
325
+
326
+ describe('links', () => {
327
+ const URL_ = 'https://example.com/plan'
328
+ async function pasteOver(from: number, to: number, text: string) {
329
+ await act(async () => {
330
+ const editor = editorOf()
331
+ editor.commands.setTextSelection({ from, to })
332
+ const event = { clipboardData: { getData: (kind: string) => (kind === 'text/plain' ? text : ''), files: [], items: [] }, preventDefault: () => {} } as unknown as ClipboardEvent
333
+ const slice = new Slice(Fragment.from(editor.state.schema.text(text)), 0, 0)
334
+ editor.view.someProp('handlePaste', (handle) => handle(editor.view, event, slice))
335
+ })
336
+ }
337
+
338
+ it('a URL pasted over words links them, and the link is still on the words after a save and a reload', async () => {
339
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
340
+ render(<Doc value={doc(para('a1', 'see the plan now'))} onCommit={onCommit} />)
341
+ await pasteOver(5, 13, URL_)
342
+ await leave()
343
+ const value = onCommit.mock.calls[0][0]
344
+ expect(saved(value)[0].runs).toEqual([
345
+ { text: 'see ', marks: [] },
346
+ { text: 'the plan', marks: [{ type: 'link', attrs: { href: URL_ } }] },
347
+ { text: ' now', marks: [] },
348
+ ])
349
+ cleanup()
350
+ render(<Doc value={value} />)
351
+ const link = document.querySelector('.ProseMirror a')
352
+ expect(link?.textContent).toBe('the plan')
353
+ expect(link?.getAttribute('href')).toBe(URL_)
354
+ })
355
+
356
+ it('a URL pasted over words in a callout or a list item links them too', async () => {
357
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
358
+ const value = JSON.stringify({
359
+ type: 'doc',
360
+ content: [
361
+ { type: 'blockquote', id: 'q1', attrs: { tone: 'note' }, content: [{ type: 'text', text: 'the note' }] },
362
+ { type: 'bulletList', id: 'l1', content: [{ type: 'listItem', id: 'i1', content: [{ type: 'text', text: 'the item' }] }] },
363
+ ],
364
+ })
365
+ render(<Doc value={value} onCommit={onCommit} />)
366
+ // Inside the quote's paragraph: 1 opens the quote, 2 its paragraph; "note" starts 4 characters in.
367
+ await pasteOver(6, 10, URL_)
368
+ // The item's words start after the list, the item and its paragraph open.
369
+ const at = editorOf().state.doc.child(0).nodeSize + 3
370
+ await pasteOver(at + 4, at + 8, `${URL_}/two`)
371
+ await leave()
372
+ const out = JSON.parse(onCommit.mock.calls[0][0]) as { content: { content: { text: string; marks?: unknown[]; content?: { text: string; marks?: unknown[] }[] }[] }[] }
373
+ expect(out.content[0].content).toEqual([{ type: 'text', text: 'the ' }, { type: 'text', text: 'note', marks: [{ type: 'link', attrs: { href: URL_ } }] }])
374
+ expect(out.content[1].content[0].content).toEqual([{ type: 'text', text: 'the ' }, { type: 'text', text: 'item', marks: [{ type: 'link', attrs: { href: `${URL_}/two` } }] }])
375
+ })
376
+
377
+ it('a link keeps the keys this version does not know through a save', async () => {
378
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
379
+ render(<Doc value={doc(para('a1', 'the plan', [{ type: 'link', attrs: { href: URL_, title: 'Kept' } }]), para('b2', 'Second'))} onCommit={onCommit} />)
380
+ await type('!', 'end')
381
+ await leave()
382
+ expect(saved(onCommit.mock.calls[0][0])[0].runs).toEqual([{ text: 'the plan', marks: [{ type: 'link', attrs: { href: URL_, title: 'Kept' } }] }])
383
+ })
384
+
385
+ /** A click on the element `pick` finds, as ProseMirror hands one to the editor. */
386
+ async function clickOn(pick: (root: Element) => Element | null) {
387
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
388
+ await act(async () => {
389
+ const { view } = editorOf()
390
+ const target = pick(view.dom)
391
+ expect(target).toBeTruthy()
392
+ view.someProp('handleClick', (handle) => handle(view, 1, { button: 0, target } as unknown as MouseEvent))
393
+ })
394
+ return open
395
+ }
396
+
397
+ it('a click on a link on words or on a bare address opens it in a new tab that cannot reach this one', async () => {
398
+ render(<Doc value={doc(para('a1', 'the plan', [{ type: 'link', attrs: { href: URL_ } }]), para('b2', `see ${URL_}/bare now`))} />)
399
+ const onWords = await clickOn((root) => root.querySelector('a'))
400
+ expect(onWords).toHaveBeenCalledWith(URL_, '_blank', 'noopener,noreferrer')
401
+ onWords.mockRestore()
402
+ const bare = await clickOn((root) => root.querySelector('[data-bare-link]'))
403
+ expect(bare).toHaveBeenCalledWith(`${URL_}/bare`, '_blank', 'noopener,noreferrer')
404
+ })
405
+
406
+ it('a chip saved with a javascript: address opens nothing when clicked', async () => {
407
+ const evil = 'javascript://example.com/%0aalert(1)'
408
+ render(<Doc value={doc(para('a1', evil, [{ type: 'link', attrs: { href: evil } }]))} />)
409
+ const open = await clickOn((root) => root.querySelector('[data-reference]') ?? root.querySelector('p'))
410
+ expect(open).not.toHaveBeenCalled()
411
+ })
412
+
413
+ it('an address typed into the text is saved as the text it is', async () => {
414
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
415
+ render(<Doc onCommit={onCommit} />)
416
+ await type(` ${URL_} `)
417
+ await leave()
418
+ expect(saved(onCommit.mock.calls[0][0])[0].runs).toEqual([{ text: `First line ${URL_} `, marks: [] }])
419
+ })
420
+ })
421
+
422
+ describe('blocks', () => {
423
+ it('each block keeps its id through editing, so what is anchored to it stays on it', async () => {
424
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
425
+ render(<Doc value={doc(para('a1', 'One'), para('b2', 'Two'), para('c3', 'Three'))} onCommit={onCommit} />)
426
+ await type(' changed', 4)
427
+ await act(async () => {
428
+ editorOf().chain().focus('end').splitBlock().insertContent('Four').run()
429
+ })
430
+ await leave()
431
+ const ids = saved(onCommit.mock.calls[0][0]).map((block) => block.id)
432
+ expect(ids.slice(0, 3)).toEqual(['a1', 'b2', 'c3'])
433
+ expect(ids[3]).toMatch(/\S/)
434
+ expect(new Set(ids).size).toBe(4)
435
+ })
436
+
437
+ it('a checklist, a callout and a table come through a save as they were', async () => {
438
+ const value = JSON.stringify({
439
+ type: 'doc',
440
+ content: [
441
+ { type: 'bulletList', id: 'l1', content: [{ type: 'listItem', id: 'i1', attrs: { checked: true }, content: [{ type: 'text', text: 'done' }] }] },
442
+ { type: 'blockquote', id: 'q1', attrs: { tone: 'warning' }, content: [{ type: 'text', text: 'careful' }] },
443
+ {
444
+ type: 'table',
445
+ id: 't1',
446
+ content: [{ type: 'tableRow', id: 'r1', content: [{ type: 'tableHeader', id: 'h1', attrs: { colspan: 1, rowspan: 1 }, content: [{ type: 'paragraph', id: 'p1', content: [{ type: 'text', text: 'a' }] }] }] }],
447
+ },
448
+ para('a1', 'Last'),
449
+ ],
450
+ })
451
+ const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
452
+ render(<Doc value={value} onCommit={onCommit} />)
453
+ await type('!', 'end')
454
+ await leave()
455
+ const out = JSON.parse(onCommit.mock.calls[0][0]) as { content: object[] }
456
+ expect(out.content.slice(0, 3)).toEqual((JSON.parse(value) as { content: object[] }).content.slice(0, 3))
457
+ })
458
+
459
+ it('a pasted picture is uploaded and placed; without an upload the paste is not taken', async () => {
460
+ const upload = vi.fn(async (file: File) => ({ url: 'https://files.example/one.png', m: 'image/png', x: 'f'.repeat(64), size: file.size, filename: file.name }))
461
+ render(<Doc upload={upload} />)
462
+ const picture = new File(['png'], 'one.png', { type: 'image/png' })
463
+ const pasteFile = async () => {
464
+ let taken = false
465
+ await act(async () => {
466
+ const editor = editorOf()
467
+ editor.commands.focus('end')
468
+ const event = { clipboardData: { getData: () => '', files: [picture], items: [{ kind: 'file', type: 'image/png', getAsFile: () => picture }], types: ['Files'] }, preventDefault: () => {} } as unknown as ClipboardEvent
469
+ editor.view.someProp('handlePaste', (handle) => {
470
+ taken = handle(editor.view, event, Slice.empty) || taken
471
+ return taken || undefined
472
+ })
473
+ for (let i = 0; i < 5; i++) await Promise.resolve()
474
+ })
475
+ return taken
476
+ }
477
+ expect(await pasteFile()).toBe(true)
478
+ expect(upload).toHaveBeenCalledTimes(1)
479
+ const files: unknown[] = []
480
+ editorOf().state.doc.descendants((node) => void (node.type.name === 'attachment' && files.push(node.attrs.filename)))
481
+ expect(files).toEqual(['one.png'])
482
+ cleanup()
483
+ render(<Doc />)
484
+ expect(await pasteFile()).toBe(false)
485
+ })
486
+ })
487
+
488
+ describe('reading', () => {
489
+ it('read only, nothing can be typed or saved, and the text is drawn the same', async () => {
490
+ const onCommit = vi.fn(async () => true)
491
+ render(<Doc readOnly onCommit={onCommit} references={references} mentions={mentions} />)
492
+ const view = screen.getByRole('textbox', { name: 'Document' })
493
+ expect(view.getAttribute('contenteditable')).toBe('false')
494
+ expect(view.textContent).toBe('First line')
495
+ // Still focusable, so a selection's strip, and Comment on it, can show.
496
+ expect(view.getAttribute('tabindex')).toBe('0')
497
+ await act(async () => {
498
+ editorOf().commands.focus()
499
+ })
500
+ await leave()
501
+ expect(onCommit).not.toHaveBeenCalled()
502
+ })
503
+
504
+ it('the strip has Comment only when the app switches comments on', async () => {
505
+ vi.useFakeTimers({ shouldAdvanceTime: true })
506
+ const onCommentOnSelection = vi.fn()
507
+ const select = async () => {
508
+ const editor = editorOf()
509
+ vi.spyOn(editor.view, 'hasFocus').mockReturnValue(true)
510
+ vi.spyOn(editor.view, 'coordsAtPos').mockReturnValue({ top: 10, bottom: 20, left: 10, right: 20 })
511
+ act(() => {
512
+ editor.commands.setTextSelection({ from: 1, to: 6 })
513
+ })
514
+ await act(async () => {
515
+ await vi.advanceTimersByTimeAsync(400)
516
+ })
517
+ }
518
+ render(<Doc readOnly onCommentOnSelection={onCommentOnSelection} />)
519
+ await select()
520
+ fireEvent.click(await screen.findByRole('button', { name: 'Comment' }))
521
+ expect(onCommentOnSelection).toHaveBeenCalledTimes(1)
522
+ cleanup()
523
+ render(<Doc />)
524
+ await select()
525
+ expect(screen.getByRole('button', { name: 'Bold' })).toBeTruthy()
526
+ expect(screen.queryByRole('button', { name: 'Comment' })).toBeNull()
527
+ })
528
+ })