@estiva-app/ui 0.75.0 → 0.77.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.
@@ -0,0 +1,218 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite'
2
+ import { useState } from 'react'
3
+ import type { JSONContent } from '@tiptap/react'
4
+ import { userEvent, within } from 'storybook/test'
5
+ import { Button } from './Button'
6
+ import { CommentBox, commentBoxRows, type CommentBoxDraft, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
7
+ import type { CaptionedItem, MentionPerson, ReferenceSection } from './ComposerTriggers'
8
+ import { Kbd } from './Kbd'
9
+
10
+ /**
11
+ * The one box every app writes in. Every story is live: write, open a list,
12
+ * send. A send is answered after a moment; write "refuse" anywhere to see a
13
+ * refusal. Pick the theme in the toolbar.
14
+ */
15
+ const meta = {
16
+ title: 'Primitives/CommentBox',
17
+ component: CommentBox,
18
+ parameters: { layout: 'padded' },
19
+ decorators: [
20
+ (Story) => (
21
+ <div className="w-[480px]">
22
+ <Story />
23
+ </div>
24
+ ),
25
+ ],
26
+ } satisfies Meta<typeof CommentBox>
27
+
28
+ export default meta
29
+ type Story = StoryObj
30
+
31
+ const PEOPLE: MentionPerson[] = ['one', 'two', 'three', 'four'].map((n, i) => ({ id: n, name: `Person ${n}`, pubkey: String(i + 1).repeat(64) }))
32
+
33
+ const ITEMS: CaptionedItem[] = ['one', 'two', 'three'].map((n, i) => ({
34
+ id: String(i + 5).repeat(64),
35
+ label: 'Label',
36
+ snippet: `Item ${n}`,
37
+ uri: `nostr:nevent1item${n}`,
38
+ }))
39
+
40
+ const references = (query: string): ReferenceSection[] => [
41
+ { label: 'Group one', items: ITEMS.filter((item) => item.snippet.toLowerCase().includes(query.toLowerCase())) },
42
+ ]
43
+
44
+ const INSERT = [commentBoxRows.file, commentBoxRows.mention, commentBoxRows.urgent, commentBoxRows.reference]
45
+
46
+ const plain = (body: JSONContent): string => (body.text ?? '') + (body.content ?? []).map(plain).join(' ')
47
+
48
+ /** A relay that answers after a moment, and refuses whatever says "refuse". */
49
+ const answering = (body: JSONContent): Promise<SendAnswer> =>
50
+ new Promise((resolve) =>
51
+ setTimeout(() => resolve(/refuse/i.test(plain(body)) ? { accepted: false, reason: 'rate-limited, try again in a minute' } : { accepted: true }), 900),
52
+ )
53
+
54
+ /** A relay that never answers. */
55
+ const silent = (): Promise<SendAnswer> => new Promise(() => {})
56
+
57
+ const uploads =
58
+ (answer: 'ready' | 'failed' | 'never') =>
59
+ (file: File): Promise<UploadAnswer> =>
60
+ answer === 'never'
61
+ ? new Promise(() => {})
62
+ : new Promise((resolve) =>
63
+ setTimeout(() => resolve(answer === 'ready' ? { accepted: true, value: file.name } : { accepted: false, reason: 'The file is larger than 20 MB.' }), 1800),
64
+ )
65
+
66
+ const PLACEHOLDER = (
67
+ <>
68
+ <span>Write, or type</span>
69
+ <Kbd>/</Kbd>
70
+ <span>for commands</span>
71
+ </>
72
+ )
73
+
74
+ const DRAFT: JSONContent = {
75
+ type: 'doc',
76
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Half written, and still here when you come back' }] }],
77
+ }
78
+
79
+ const WITH_CHIPS: JSONContent = {
80
+ type: 'doc',
81
+ content: [
82
+ {
83
+ type: 'paragraph',
84
+ content: [
85
+ { type: 'text', text: 'Agreed with ' },
86
+ { type: 'mention', attrs: { id: 'two', label: 'Person two', pubkey: '2'.repeat(64) } },
87
+ { type: 'text', text: ', as in ' },
88
+ { type: 'captionedReference', attrs: { id: ITEMS[0].id, label: 'Label', snippet: 'Item one', uri: ITEMS[0].uri } },
89
+ ],
90
+ },
91
+ ],
92
+ }
93
+
94
+ /** The sent lines above the box, so a send can be seen to land. */
95
+ function Live({ start, ...props }: Partial<CommentBoxProps> & { start?: JSONContent }) {
96
+ const [sent, setSent] = useState<string[]>([])
97
+ const [kept] = useState(() => {
98
+ let body = start
99
+ const draft: CommentBoxDraft = { read: () => body, write: (b) => (body = b), clear: () => (body = undefined) }
100
+ return draft
101
+ })
102
+ const [open, setOpen] = useState(true)
103
+ return (
104
+ <div className="flex flex-col gap-3">
105
+ {sent.map((line, i) => (
106
+ <p key={i} className="text-body-2 text-text-primary">
107
+ {line}
108
+ </p>
109
+ ))}
110
+ {open ? (
111
+ <CommentBox
112
+ people={PEOPLE}
113
+ references={references}
114
+ insert={INSERT}
115
+ send={answering}
116
+ label="Write"
117
+ placeholder={PLACEHOLDER}
118
+ draft={kept}
119
+ upload={uploads('ready')}
120
+ onSent={(body) => setSent((all) => [...all, plain(body)])}
121
+ {...props}
122
+ />
123
+ ) : (
124
+ <p className="text-body-2 text-text-muted">The box is closed. Open it again: the words are kept.</p>
125
+ )}
126
+ {start && (
127
+ <div>
128
+ <Button variant="outlined" size="small" onClick={() => setOpen((o) => !o)}>
129
+ {open ? 'Close the box' : 'Open the box'}
130
+ </Button>
131
+ </div>
132
+ )}
133
+ </div>
134
+ )
135
+ }
136
+
137
+ const typeInto = (text: string) =>
138
+ async function play({ canvasElement }: { canvasElement: HTMLElement }) {
139
+ const box = within(canvasElement).getByRole('textbox', { name: 'Write' })
140
+ await userEvent.click(box)
141
+ await userEvent.keyboard(text)
142
+ }
143
+
144
+ const pickAFile = async ({ canvasElement }: { canvasElement: HTMLElement }) => {
145
+ const input = canvasElement.querySelector('input[type=file]') as HTMLInputElement
146
+ await userEvent.upload(input, new File(['placeholder'], 'plan.pdf', { type: 'application/pdf' }))
147
+ }
148
+
149
+ /** Nothing written. */
150
+ export const Empty: Story = { render: () => <Live /> }
151
+
152
+ /** Words half written. Close the box and open it again: they are still there. */
153
+ export const WithADraft: Story = { render: () => <Live start={DRAFT} /> }
154
+
155
+ /** `@`: the people the app supplies. */
156
+ export const MentionOpen: Story = { render: () => <Live />, play: typeInto('Asking @') }
157
+
158
+ /** `!@`: the same people, urgently. */
159
+ export const UrgentOpen: Story = { render: () => <Live />, play: typeInto('Asking !@') }
160
+
161
+ /** `[`: what the app's sections list. */
162
+ export const ReferenceOpen: Story = { render: () => <Live />, play: typeInto('As in [[') }
163
+
164
+ /** `/`: the shared Format section, then the app's Insert rows. */
165
+ export const CommandsOpen: Story = { render: () => <Live />, play: typeInto('/') }
166
+
167
+ /** Held until the relay answers: the words stay, shut. */
168
+ export const Sending: Story = { render: () => <Live send={silent} />, play: typeInto('On its way{Enter}') }
169
+
170
+ /** The relay said no: the words are back in the box, and a line says why. */
171
+ export const Refused: Story = { render: () => <Live />, play: typeInto('Please refuse this{Enter}') }
172
+
173
+ /** Shown at once: the box empties now, and a refusal puts the words back. Write "refuse" to see it. */
174
+ export const ShownAtOnce: Story = { render: () => <Live showsAtOnce /> }
175
+
176
+ /** Editing something sent: the chips stay chips; only the keys on the left. */
177
+ export const Editing: Story = {
178
+ render: () => <Live edit={{ body: WITH_CHIPS, onCancel: () => {}, onSave: answering }} />,
179
+ }
180
+
181
+ /** A save the relay refused: "Saving…" while it waits, then a line under the box; the changes stay. */
182
+ export const EditingRefused: Story = {
183
+ render: () => (
184
+ <Live
185
+ edit={{
186
+ body: WITH_CHIPS,
187
+ onCancel: () => {},
188
+ onSave: () => new Promise((resolve) => setTimeout(() => resolve({ accepted: false, reason: 'rate-limited, try again in a minute' }), 900)),
189
+ }}
190
+ />
191
+ ),
192
+ play: typeInto('{Enter}'),
193
+ }
194
+
195
+ /** A file uploading: Send waits for it. */
196
+ export const FileUploading: Story = { render: () => <Live upload={uploads('never')} />, play: pickAFile }
197
+
198
+ /** A file that failed: it says why and can be removed. */
199
+ export const FileFailed: Story = { render: () => <Live upload={uploads('failed')} />, play: pickAFile }
200
+
201
+ /** Read-only, archived: a line in the box's place. */
202
+ export const ReadOnlyArchived: Story = { render: () => <Live closed={{ reason: 'This is archived, so nothing new can be written here.' }} /> }
203
+
204
+ /** Read-only, signed out: a line in the box's place. */
205
+ export const ReadOnlySignedOut: Story = { render: () => <Live closed={{ reason: 'Sign in to write here.' }} /> }
206
+
207
+ /** The narrowest column it sits in, 320px, with a file uploading. */
208
+ export const Narrow: Story = {
209
+ decorators: [
210
+ (Story) => (
211
+ <div className="w-[320px]">
212
+ <Story />
213
+ </div>
214
+ ),
215
+ ],
216
+ render: () => <Live upload={uploads('never')} start={DRAFT} />,
217
+ play: pickAFile,
218
+ }
@@ -0,0 +1,265 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * The shared comment box (COMM-2): what its page says it owns — the keys,
4
+ * sending held or shown at once, a refusal putting the words back, the edit
5
+ * mode, drafts, files and the read-only line.
6
+ */
7
+ import { act } from 'react'
8
+ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
9
+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
10
+ import type { Editor } from '@tiptap/core'
11
+ import type { JSONContent } from '@tiptap/react'
12
+ import { CommentBox, commentBoxRows, type CommentBoxDraft, type CommentBoxEdit, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
13
+ import type { MentionPerson } from './ComposerTriggers'
14
+
15
+ const PEOPLE: MentionPerson[] = [{ id: 'one', name: 'Person one', pubkey: 'b'.repeat(64) }]
16
+ const INSERT = [commentBoxRows.file, commentBoxRows.mention, commentBoxRows.urgent, commentBoxRows.reference]
17
+
18
+ beforeAll(() => {
19
+ Element.prototype.scrollIntoView = vi.fn()
20
+ Element.prototype.getClientRects = () => [] as unknown as DOMRectList
21
+ Range.prototype.getClientRects = () => [] as unknown as DOMRectList
22
+ Range.prototype.getBoundingClientRect = () => new DOMRect()
23
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
24
+ // Only the clock: a list closing gives Enter 100ms of grace (suggestionPopup), which must not reach the next test.
25
+ vi.useFakeTimers({ toFake: ['Date'] })
26
+ })
27
+
28
+ afterEach(() => {
29
+ cleanup()
30
+ vi.setSystemTime(Date.now() + 1000)
31
+ })
32
+
33
+ /** A promise the test answers. */
34
+ function later<T>() {
35
+ let answer!: (value: T) => void
36
+ const promise = new Promise<T>((resolve) => {
37
+ answer = resolve
38
+ })
39
+ return { promise, answer }
40
+ }
41
+
42
+ const editorOf = (): Editor => (document.querySelector('.ProseMirror') as unknown as { editor: Editor }).editor
43
+
44
+ const textOf = (body: JSONContent): string => (body.text ?? '') + (body.content ?? []).map(textOf).join('')
45
+
46
+ async function type(text: string) {
47
+ await act(async () => {
48
+ editorOf().chain().focus('end').insertContent(text).run()
49
+ })
50
+ }
51
+
52
+ async function press(key: string, init: KeyboardEventInit = {}) {
53
+ await act(async () => {
54
+ const editor = editorOf()
55
+ editor.view.someProp('handleKeyDown', (handle) => handle(editor.view, new KeyboardEvent('keydown', { key, ...init })))
56
+ })
57
+ }
58
+
59
+ /** Lets an answer reach the box: it passes through a few promises on the way. */
60
+ async function settle() {
61
+ await act(async () => {
62
+ for (let i = 0; i < 5; i++) await Promise.resolve()
63
+ })
64
+ }
65
+
66
+ function Box(props: Partial<CommentBoxProps>) {
67
+ return <CommentBox people={PEOPLE} insert={INSERT} label="Write" placeholder="Write…" send={async () => ({ accepted: true })} {...props} />
68
+ }
69
+
70
+ describe('sending, held until the relay answers', () => {
71
+ it('Enter sends the words and the box holds them, shut, until it is accepted; then it is empty', async () => {
72
+ const answer = later<SendAnswer>()
73
+ const send = vi.fn<CommentBoxProps['send']>(() => answer.promise)
74
+ render(<Box send={send} />)
75
+ await type('Hello there')
76
+ await press('Enter')
77
+ expect(send).toHaveBeenCalledTimes(1)
78
+ expect(textOf(send.mock.calls[0][0])).toBe('Hello there')
79
+ expect(screen.getByText('Sending…')).toBeTruthy()
80
+ expect(editorOf().isEditable).toBe(false)
81
+ expect(editorOf().getText()).toBe('Hello there')
82
+ answer.answer({ accepted: true })
83
+ await settle()
84
+ expect(editorOf().getText()).toBe('')
85
+ expect(screen.queryByText('Sending…')).toBeNull()
86
+ })
87
+
88
+ it('a refusal keeps the words in the box and says why under it', async () => {
89
+ render(<Box send={async () => ({ accepted: false, reason: 'rate-limited' })} />)
90
+ await type('Hello there')
91
+ await press('Enter')
92
+ await settle()
93
+ expect(editorOf().getText()).toBe('Hello there')
94
+ expect(screen.getByText('Not sent: rate-limited. Your text is back in the box.')).toBeTruthy()
95
+ expect(editorOf().isEditable).toBe(true)
96
+ })
97
+
98
+ it('Ctrl/Cmd+Enter sends as Enter does; Shift+Enter does not send', async () => {
99
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
100
+ render(<Box send={send} />)
101
+ await type('One')
102
+ await press('Enter', { shiftKey: true })
103
+ expect(send).not.toHaveBeenCalled()
104
+ await press('Enter', { ctrlKey: true })
105
+ expect(send).toHaveBeenCalledTimes(1)
106
+ })
107
+
108
+ it('an empty box sends nothing', async () => {
109
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
110
+ render(<Box send={send} />)
111
+ await type(' ')
112
+ await press('Enter')
113
+ expect(send).not.toHaveBeenCalled()
114
+ })
115
+ })
116
+
117
+ describe('sending, shown at once', () => {
118
+ it('the box empties at once; a refusal puts the words back, says why, and tells the app', async () => {
119
+ const answer = later<SendAnswer>()
120
+ const onSent = vi.fn()
121
+ const onRefused = vi.fn()
122
+ render(<Box showsAtOnce send={() => answer.promise} onSent={onSent} onRefused={onRefused} />)
123
+ await type('Hello there')
124
+ await press('Enter')
125
+ expect(editorOf().getText()).toBe('')
126
+ expect(onSent).toHaveBeenCalledTimes(1)
127
+ answer.answer({ accepted: false, reason: 'rate-limited' })
128
+ await settle()
129
+ expect(editorOf().getText()).toBe('Hello there')
130
+ expect(onRefused).toHaveBeenCalledTimes(1)
131
+ expect(screen.getByText('Not sent: rate-limited. Your text is back in the box.')).toBeTruthy()
132
+ })
133
+ })
134
+
135
+ describe('editing', () => {
136
+ const body: JSONContent = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Said before' }] }] }
137
+
138
+ it('opens with what it says; Enter saves it, and Escape cancels', async () => {
139
+ const onSave = vi.fn<CommentBoxEdit['onSave']>(async () => ({ accepted: true }))
140
+ const onCancel = vi.fn()
141
+ render(<Box edit={{ body, onSave, onCancel }} />)
142
+ expect(editorOf().getText()).toBe('Said before')
143
+ expect(screen.getByText(/to cancel/).textContent).toBe('Esc to cancel · Enter to save')
144
+ await type(', and now')
145
+ await press('Enter')
146
+ expect(textOf(onSave.mock.calls[0][0])).toBe('Said before, and now')
147
+ await press('Escape')
148
+ expect(onCancel).toHaveBeenCalledTimes(1)
149
+ })
150
+
151
+ it('!@ opens no urgent list in an edit, and @ still does', async () => {
152
+ render(<Box edit={{ body, onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
153
+ await type(' !@')
154
+ expect(screen.queryByRole('listbox', { name: 'Urgent mention' })).toBeNull()
155
+ await type(' @')
156
+ expect(screen.getByRole('listbox', { name: 'People' })).toBeTruthy()
157
+ await press('Escape')
158
+ })
159
+
160
+ it('Escape right after closing a list cancels the edit', async () => {
161
+ const onCancel = vi.fn()
162
+ render(<Box edit={{ body, onSave: async () => ({ accepted: true }), onCancel }} />)
163
+ await type(' @')
164
+ expect(screen.getByRole('listbox')).toBeTruthy()
165
+ await press('Escape')
166
+ expect(onCancel).not.toHaveBeenCalled()
167
+ await press('Escape')
168
+ expect(onCancel).toHaveBeenCalledTimes(1)
169
+ })
170
+
171
+ it('a refused save keeps the words and says it was not saved', async () => {
172
+ render(<Box edit={{ body, onSave: async () => ({ accepted: false, reason: 'gone' }), onCancel: () => {} }} />)
173
+ await press('Enter')
174
+ await settle()
175
+ expect(screen.getByText('Not saved: gone. Your changes are still in the box.')).toBeTruthy()
176
+ expect(editorOf().getText()).toBe('Said before')
177
+ })
178
+
179
+ it('/ offers no File and no Urgent in an edit', async () => {
180
+ render(<Box upload={async () => ({ accepted: true, value: 1 })} edit={{ body, onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
181
+ await type(' /')
182
+ const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
183
+ expect(rows.some((r) => r.startsWith('Mention'))).toBe(true)
184
+ expect(rows.some((r) => r.startsWith('File') || r.startsWith('Urgent'))).toBe(false)
185
+ // Closed here: the editor is destroyed on a timer, and a list it closes then would hold the next test's Enter.
186
+ await press('Escape')
187
+ })
188
+ })
189
+
190
+ describe('drafts', () => {
191
+ it('keeps what is written, opens with it again, and forgets it once sent', async () => {
192
+ let kept: JSONContent | undefined
193
+ const draft: CommentBoxDraft = { read: () => kept, write: (b) => (kept = b), clear: () => (kept = undefined) }
194
+ const first = render(<Box draft={draft} />)
195
+ await type('Half written')
196
+ first.unmount()
197
+ expect(textOf(kept!)).toBe('Half written')
198
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
199
+ render(<Box draft={draft} send={send} />)
200
+ expect(editorOf().getText()).toBe('Half written')
201
+ await press('Enter')
202
+ await settle()
203
+ expect(send).toHaveBeenCalledTimes(1)
204
+ expect(kept).toBeUndefined()
205
+ })
206
+ })
207
+
208
+ describe('files', () => {
209
+ it('a picked file uploads, Send waits for it, and it goes out with the words', async () => {
210
+ const uploaded = later<UploadAnswer>()
211
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
212
+ render(<Box send={send} upload={() => uploaded.promise} />)
213
+ const input = document.querySelector('input[type=file]') as HTMLInputElement
214
+ await act(async () => {
215
+ fireEvent.change(input, { target: { files: [new File(['x'], 'plan.pdf', { type: 'application/pdf' })] } })
216
+ })
217
+ expect(screen.getByText('Uploading… Send waits for the file.')).toBeTruthy()
218
+ await type('See this')
219
+ await press('Enter')
220
+ expect(send).not.toHaveBeenCalled()
221
+ uploaded.answer({ accepted: true, value: 'the-record' })
222
+ await settle()
223
+ await press('Enter')
224
+ expect(send).toHaveBeenCalledTimes(1)
225
+ expect(send.mock.calls[0][1]).toMatchObject([{ name: 'plan.pdf', state: 'ready', value: 'the-record' }])
226
+ })
227
+
228
+ it('a failed upload says why, and nothing waits for it', async () => {
229
+ render(<Box upload={async () => ({ accepted: false, reason: 'too large' })} />)
230
+ const input = document.querySelector('input[type=file]') as HTMLInputElement
231
+ await act(async () => {
232
+ fireEvent.change(input, { target: { files: [new File(['x'], 'big.mov', { type: 'video/quicktime' })] } })
233
+ })
234
+ await settle()
235
+ expect(screen.getByText('too large')).toBeTruthy()
236
+ expect(screen.queryByText('Uploading… Send waits for the file.')).toBeNull()
237
+ })
238
+
239
+ it('an upload that arrives after the box opened offers File in /', async () => {
240
+ const { rerender } = render(<Box />)
241
+ rerender(<Box upload={async () => ({ accepted: true, value: 1 })} />)
242
+ await type('/')
243
+ const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
244
+ expect(rows.some((r) => r.startsWith('File'))).toBe(true)
245
+ await press('Escape')
246
+ })
247
+
248
+ it('no upload: no paperclip and no File row', async () => {
249
+ render(<Box />)
250
+ expect(screen.queryByRole('button', { name: 'Attach a file' })).toBeNull()
251
+ await type('/')
252
+ const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
253
+ expect(rows.some((r) => r.startsWith('File'))).toBe(false)
254
+ await press('Escape')
255
+ })
256
+ })
257
+
258
+ describe('read-only', () => {
259
+ it('a line saying why takes the box’s place', () => {
260
+ render(<Box closed={{ reason: 'Archived. It takes no new comments.' }} />)
261
+ expect(screen.getByText('Archived. It takes no new comments.')).toBeTruthy()
262
+ expect(document.querySelector('.ProseMirror')).toBeNull()
263
+ expect(screen.queryByRole('button', { name: 'Send' })).toBeNull()
264
+ })
265
+ })