@estiva-app/ui 0.105.0 → 0.107.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/ui",
3
- "version": "0.105.0",
3
+ "version": "0.107.0",
4
4
  "description": "Estiva's design tokens (the contract) and a small set of primitives (a convenience) for every Estiva app.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -133,8 +133,8 @@
133
133
  },
134
134
  "devDependencies": {
135
135
  "@eslint/js": "^10.0.1",
136
- "@estiva-app/conversation": "^0.22.0",
137
- "@estiva-app/protocol": "^0.45.0",
136
+ "@estiva-app/conversation": "^0.33.0",
137
+ "@estiva-app/protocol": "^0.51.0",
138
138
  "@storybook/addon-a11y": "^10.6.0",
139
139
  "@storybook/addon-docs": "^10.5.10",
140
140
  "@storybook/addon-vitest": "^10.6.0",
package/registry.json CHANGED
@@ -4,8 +4,8 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.105.0",
8
- "exports": 245,
7
+ "packageVersion": "0.107.0",
8
+ "exports": 247,
9
9
  "typeExports": 254,
10
10
  "files": null
11
11
  },
@@ -638,8 +638,8 @@
638
638
  "looks": [
639
639
  "text-caption font-medium text-text-primary truncate",
640
640
  "text-small tracking-wide leading-tight truncate",
641
+ "text-small tracking-wide leading-tight line-clamp-2 text-error-default",
641
642
  "rounded-md bg-bg-active text-text-secondary overflow-hidden",
642
- "text-small tracking-wide leading-tight truncate text-error-default",
643
643
  "text-small tracking-wide leading-tight truncate text-warning-default",
644
644
  "text-small tracking-wide leading-tight truncate text-text-secondary",
645
645
  "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100",
@@ -2765,6 +2765,12 @@
2765
2765
  "required": false,
2766
2766
  "note": "Deleted: \"This comment was deleted.\", and its replies stay."
2767
2767
  },
2768
+ {
2769
+ "name": "unseen",
2770
+ "takes": "true/false",
2771
+ "required": false,
2772
+ "note": "Not read, and nothing says it was deleted (SPEC §6.5's \"not returned\"): \"This comment can't be shown.\", drawn as a deleted one is, and its replies stay (Miky, 6 November, ONE-9)."
2773
+ },
2768
2774
  {
2769
2775
  "name": "replies",
2770
2776
  "takes": "Omit<RepliesRowProps, 'urgent'>",
@@ -2883,13 +2889,7 @@
2883
2889
  "name": "reactions",
2884
2890
  "takes": "ReactionRowProps",
2885
2891
  "required": false,
2886
- "note": "Its reactions: the kit's `ReactionRow`. With `onToggle`, the strip offers React too."
2887
- },
2888
- {
2889
- "name": "reactionRefused",
2890
- "takes": "text",
2891
- "required": false,
2892
- "note": "Why the last reaction was refused, in plain words: said under the reactions."
2892
+ "note": "Its reactions: the kit's `ReactionRow`. With `onToggle`, the strip offers React too; when `onToggle` answers with a refusal, \"Not reacted: <why>.\" is said under the reactions until the next reaction here, or until the card goes."
2893
2893
  },
2894
2894
  {
2895
2895
  "name": "isNew",
@@ -4744,6 +4744,44 @@
4744
4744
  "app": null,
4745
4745
  "looks": []
4746
4746
  },
4747
+ {
4748
+ "name": "GONE_CLOSED",
4749
+ "repo": "estiva-ui",
4750
+ "kind": "helper",
4751
+ "importPath": "@estiva-app/ui",
4752
+ "sourceFile": "src/PinnedComment.tsx",
4753
+ "purpose": "The box's `closed` under that thread, deleted or not shown, the same in every app: the line above already says why.",
4754
+ "purposeFrom": "comment",
4755
+ "props": [],
4756
+ "variants": [],
4757
+ "ownsBehaviours": [],
4758
+ "status": "stable",
4759
+ "migrationStage": null,
4760
+ "docsId": "conversation-pinnedcomment--docs",
4761
+ "storyId": "conversation-pinnedcomment--pinned",
4762
+ "docPage": null,
4763
+ "app": null,
4764
+ "looks": []
4765
+ },
4766
+ {
4767
+ "name": "goneWords",
4768
+ "repo": "estiva-ui",
4769
+ "kind": "helper",
4770
+ "importPath": "@estiva-app/ui",
4771
+ "sourceFile": "src/PinnedComment.tsx",
4772
+ "purpose": "What stands in a comment's place when it is gone: deleted, or not shown (SPEC §6.5).",
4773
+ "purposeFrom": "comment",
4774
+ "props": [],
4775
+ "variants": [],
4776
+ "ownsBehaviours": [],
4777
+ "status": "stable",
4778
+ "migrationStage": null,
4779
+ "docsId": "conversation-pinnedcomment--docs",
4780
+ "storyId": "conversation-pinnedcomment--pinned",
4781
+ "docPage": null,
4782
+ "app": null,
4783
+ "looks": []
4784
+ },
4747
4785
  {
4748
4786
  "name": "hueFor",
4749
4787
  "repo": "estiva-ui",
@@ -8239,6 +8277,12 @@
8239
8277
  "takes": "true/false",
8240
8278
  "required": false,
8241
8279
  "note": "It was deleted; its replies stay."
8280
+ },
8281
+ {
8282
+ "name": "unseen",
8283
+ "takes": "true/false",
8284
+ "required": false,
8285
+ "note": "It wasn't read, and nothing says it was deleted: \"This comment can't be shown.\", and its replies stay (ONE-9)."
8242
8286
  }
8243
8287
  ],
8244
8288
  "variants": [],
@@ -9443,13 +9487,7 @@
9443
9487
  "name": "reactions",
9444
9488
  "takes": "ReactionRowProps",
9445
9489
  "required": false,
9446
- "note": "Its reactions: the kit's `ReactionRow`. With `onToggle`, the strip offers React too."
9447
- },
9448
- {
9449
- "name": "reactionRefused",
9450
- "takes": "text",
9451
- "required": false,
9452
- "note": "Why the last reaction was refused, in plain words: said under the reactions."
9490
+ "note": "Its reactions: the kit's `ReactionRow`. With `onToggle`, the strip offers React too; when `onToggle` answers with a refusal, \"Not reacted: <why>.\" is said under the reactions until the next reaction here, or until the card goes."
9453
9491
  },
9454
9492
  {
9455
9493
  "name": "isNew",
@@ -94,6 +94,9 @@ const TILE_CLASSES = TYPE_TILE_CLASSES
94
94
  // @estiva-escape(no-copied-look): A6 (Katerina, 24 September: record only): a 12px medium name, the text style InputChip's label also uses, not a copy of a part
95
95
  const NAME_CLASSES = 'text-caption font-medium text-text-primary truncate'
96
96
  const NOTE_CLASSES = 'text-small tracking-wide leading-tight truncate'
97
+ // A failed file's reason is what the person acts on, its limit included ("Too large: the most is 10 MB"): up to two
98
+ // lines rather than cut at the card's width (ONE-4).
99
+ const FAILED_NOTE_CLASSES = 'text-small tracking-wide leading-tight line-clamp-2 text-error-default'
97
100
 
98
101
  function TypeIcon({ name }: { name: string }) {
99
102
  const Icon = ICON_BY_EXTENSION[extensionOf(name)] ?? IconFile
@@ -414,7 +417,7 @@ export function AttachmentCard({
414
417
  <Truncating
415
418
  text={(failed || warning ? note : state === 'uploading' ? (note ?? 'Uploading…') : (note ?? sizeText)) ?? ''}
416
419
  hint={noteHint}
417
- className={cn(NOTE_CLASSES, failed ? 'text-error-default' : warning ? 'text-warning-default' : 'text-text-secondary')}
420
+ className={failed ? FAILED_NOTE_CLASSES : cn(NOTE_CLASSES, warning ? 'text-warning-default' : 'text-text-secondary')}
418
421
  />
419
422
  </div>
420
423
  {onRemove && (
@@ -65,7 +65,9 @@ const draft = composerDraft(createDraftStore(localStorage), draftKeys.thread(roo
65
65
  ```
66
66
 
67
67
  - **It speaks the editor's document.** The text a document sends, and the document an edit or a draft opens with, are `@estiva-app/conversation`'s: `composerText`, `composerDocument`, `composerDraft`. Never write marker text here.
68
- - **`send` answers.** Resolve `{ accepted: false, reason }` and the words come back with "Not sent: *reason*". A thrown send is a refusal too.
68
+ - **`send` answers.** Resolve `{ accepted: false, reason }` and the words come back with "Not sent: *why*. Your text is back in the box." A thrown send is a refusal too. Hand `reason` over as it came — the relay's words, the error, the HTTP body, or `{ cause }` for a cause of your own — never your own sentence: the box says it in `@estiva-app/conversation`'s plain words (`refusalReason`), the same in every app. `onSave` and `edit.refused` likewise ("Not saved: *why*.", and "Your changes are still in the box." while it holds something).
69
+ - **`upload` answers the same way**: `{ accepted: false, reason }` with the reason as it came (protocol's `upload failed: <status> <body>`); the file's card says `uploadRefusal`'s line. A file over the server's limit for its type (10 MB a GIF, 50 MB another picture, 100 MB anything else) is said on its card as it is picked, and never handed to `upload`.
70
+ - **An edit holding nothing**, no words and no file, cannot be saved: Save is off. One whose words are all gone but that keeps a file is saved.
69
71
  - **`label` is required**: the editor's accessible name.
70
72
  - **`insert` is the app's Insert rows**, after the shared Format section: `commentBoxRows` and the app's own. An edit drops Urgent itself (an edit makes nobody urgent); with no `upload` there is no Upload (`commentBoxRows.file` is that row).
71
73
  - **Give the box a `key` per destination.** The editor, the rows and `code` are made once, as the box opens; a new thread is a new box.
@@ -88,7 +90,8 @@ It does these by itself. Write none of them around it.
88
90
  | `[`'s rows wear the icon of the kind each address names | an icon lookup |
89
91
  | Enter and Ctrl/Cmd+Enter send; Escape cancels an edit | key handlers |
90
92
  | Holding the words until the answer, or showing the send at once | a sending state |
91
- | A refusal: the words back, and a line under the box | a toast, or putting text back |
93
+ | A refusal: the words back, and a line under the box in the plain words every app says | a toast, putting text back, or words for the relay's reasons |
94
+ | A file over the server's limit, said on its card before anything uploads | a size check |
92
95
  | The draft, written as you type and forgotten once sent | an update listener |
93
96
  | Files: picking, pasting, dropping, uploading, failing; Send waits for an upload and holds on a failed file until its ✕ removes it | a file list |
94
97
  | The card in the box, its ✕, and a ✕ forgotten once the link is taken out; a refused send puts back what ✕ took off | a card state |
@@ -11,6 +11,7 @@ import { InlineChip } from './InlineChip'
11
11
  import { Kbd } from './Kbd'
12
12
  import { LinkCard } from './LinkCard'
13
13
  import { LinkChip } from './LinkChip'
14
+ import { RELAY_SAYS, SERVER_SAYS, type RelaySays, type ServerSays } from './conversation.examples'
14
15
  import { ITEM, ITEM_NO_SUMMARY, ready } from './linked.examples'
15
16
  import { PartCard } from './PartCard'
16
17
  import { QuotedLine } from './QuotedLine'
@@ -54,24 +55,31 @@ const INSERT = [commentBoxRows.file, commentBoxRows.mention, commentBoxRows.urge
54
55
 
55
56
  const plain = (body: JSONContent): string => (body.text ?? '') + (body.content ?? []).map(plain).join(' ')
56
57
 
57
- /** A relay that answers after a moment, and refuses whatever says "refuse". */
58
- const answering = (body: JSONContent): Promise<SendAnswer> =>
59
- new Promise((resolve) =>
60
- setTimeout(() => resolve(/refuse/i.test(plain(body)) ? { accepted: false, reason: 'rate-limited, try again in a minute' } : { accepted: true }), 900),
61
- )
58
+ /** A relay that answers after a moment, and refuses whatever says "refuse", for `refusal`. */
59
+ const answering =
60
+ (refusal: RelaySays = 'Too many at once') =>
61
+ (body: JSONContent): Promise<SendAnswer> =>
62
+ new Promise((resolve) => setTimeout(() => resolve(/refuse/i.test(plain(body)) ? { accepted: false, reason: RELAY_SAYS[refusal] } : { accepted: true }), 900))
63
+
64
+ /** A relay that refuses every save, for `refusal`. */
65
+ const refusing = (refusal: RelaySays) => (): Promise<SendAnswer> => new Promise((resolve) => setTimeout(() => resolve({ accepted: false, reason: RELAY_SAYS[refusal] }), 900))
62
66
 
63
67
  /** A relay that never answers. */
64
68
  const silent = (): Promise<SendAnswer> => new Promise(() => {})
65
69
 
70
+ /** A server that takes every file, never answers, or refuses every file for `refusal`. */
66
71
  const uploads =
67
- (answer: 'ready' | 'failed' | 'never') =>
72
+ (answer: 'ready' | 'failed' | 'never', refusal: ServerSays = 'Anything else') =>
68
73
  (file: File): Promise<UploadAnswer> =>
69
74
  answer === 'never'
70
75
  ? new Promise(() => {})
71
76
  : new Promise((resolve) =>
72
- setTimeout(() => resolve(answer === 'ready' ? { accepted: true, value: file.name } : { accepted: false, reason: 'The file is larger than 20 MB.' }), 1800),
77
+ setTimeout(() => resolve(answer === 'ready' ? { accepted: true, value: file.name } : { accepted: false, reason: SERVER_SAYS[refusal] }), 1800),
73
78
  )
74
79
 
80
+ /** What the relay said, picked in the controls. */
81
+ const relayControl = { argTypes: { refusal: { control: 'select', options: Object.keys(RELAY_SAYS) } } } as const
82
+
75
83
  const PLACEHOLDER = (
76
84
  <>
77
85
  <span>Write, or type</span>
@@ -121,7 +129,7 @@ function Live({ start, ...props }: Partial<CommentBoxProps> & { start?: JSONCont
121
129
  people={PEOPLE}
122
130
  references={references}
123
131
  insert={INSERT}
124
- send={answering}
132
+ send={answering()}
125
133
  label="Write"
126
134
  placeholder={PLACEHOLDER}
127
135
  draft={kept}
@@ -176,39 +184,63 @@ export const CommandsOpen: Story = { render: () => <Live />, play: typeInto('/')
176
184
  /** Held until the relay answers: the words stay, shut. */
177
185
  export const Sending: Story = { render: () => <Live send={silent} />, play: typeInto('On its way{Enter}') }
178
186
 
179
- /** The relay said no: the words are back in the box, and a line says why. */
180
- export const Refused: Story = { render: () => <Live />, play: typeInto('Please refuse this{Enter}') }
187
+ /**
188
+ * The relay said no: the words are back in the box, and a line says why, in the same plain words in every app. Pick
189
+ * what the relay said in the controls.
190
+ */
191
+ export const Refused: StoryObj<{ refusal: RelaySays }> = {
192
+ ...relayControl,
193
+ args: { refusal: 'Too long' },
194
+ render: ({ refusal }) => <Live send={answering(refusal)} />,
195
+ play: typeInto('Please refuse this{Enter}'),
196
+ }
181
197
 
182
198
  /** Shown at once: the box empties now, and a refusal puts the words back. Write "refuse" to see it. */
183
199
  export const ShownAtOnce: Story = { render: () => <Live showsAtOnce /> }
184
200
 
185
201
  /** Editing something sent: the chips stay chips; only the keys on the left. */
186
202
  export const Editing: Story = {
187
- render: () => <Live edit={{ body: WITH_CHIPS, onCancel: () => {}, onSave: answering }} />,
203
+ render: () => <Live edit={{ body: WITH_CHIPS, onCancel: () => {}, onSave: answering() }} />,
188
204
  }
189
205
 
190
- /** A save the relay refused: "Saving…" while it waits, then a line under the box; the changes stay. */
191
- export const EditingRefused: Story = {
192
- render: () => (
193
- <Live
194
- edit={{
195
- body: WITH_CHIPS,
196
- onCancel: () => {},
197
- onSave: () => new Promise((resolve) => setTimeout(() => resolve({ accepted: false, reason: 'rate-limited, try again in a minute' }), 900)),
198
- }}
199
- />
200
- ),
206
+ /** A save the relay refused: "Saving…" while it waits, then a line under the box; the changes stay. Pick what the relay said in the controls. */
207
+ export const EditingRefused: StoryObj<{ refusal: RelaySays }> = {
208
+ ...relayControl,
209
+ args: { refusal: 'Deleted, or no longer yours to write beside' },
210
+ render: ({ refusal }) => <Live edit={{ body: WITH_CHIPS, onCancel: () => {}, onSave: refusing(refusal) }} />,
201
211
  play: typeInto('{Enter}'),
202
212
  }
203
213
 
214
+ /** An edit with nothing left in it, no words and no file: Save is off, and nothing is said. */
215
+ export const EditingEmptied: Story = {
216
+ render: () => <Live edit={{ body: { type: 'doc', content: [{ type: 'paragraph' }] }, onCancel: () => {}, onSave: answering() }} />,
217
+ }
218
+
204
219
  /** A file attached and ready: its card under the text, and Send can send it with no words. */
205
220
  export const WithAFile: Story = { render: () => <Live />, play: pickAFile }
206
221
 
207
222
  /** A file uploading: Send waits for it. */
208
223
  export const FileUploading: Story = { render: () => <Live upload={uploads('never')} />, play: pickAFile }
209
224
 
210
- /** A file that failed: it says why, Send holds, and its ✕ removes it. */
211
- export const FileFailed: Story = { render: () => <Live upload={uploads('failed')} />, play: pickAFile }
225
+ /**
226
+ * A file the server refused: its card says why, Send holds, and its ✕ removes it. Pick what the server said in the
227
+ * controls.
228
+ */
229
+ export const FileFailed: StoryObj<{ refusal: ServerSays }> = {
230
+ args: { refusal: 'Too large' },
231
+ argTypes: { refusal: { control: 'select', options: Object.keys(SERVER_SAYS) } },
232
+ render: ({ refusal }) => <Live upload={uploads('failed', refusal)} />,
233
+ play: pickAFile,
234
+ }
235
+
236
+ /** A file over the server's limit for its type (a GIF over 10 MB): its card says so at once, and nothing uploads. */
237
+ export const FileTooLarge: Story = {
238
+ render: () => <Live />,
239
+ play: async ({ canvasElement }) => {
240
+ const input = canvasElement.querySelector('input[type=file]') as HTMLInputElement
241
+ await userEvent.upload(input, new File([new Uint8Array(15 * 1024 * 1024)], 'image.gif', { type: 'image/gif' }))
242
+ },
243
+ }
212
244
 
213
245
  /** Read-only, archived: a line in the box's place. */
214
246
  export const ReadOnlyArchived: Story = { render: () => <Live closed={{ reason: 'This is archived, so nothing new can be written here.' }} /> }
@@ -307,7 +339,7 @@ export const EditingWithACard: Story = {
307
339
  edit={{
308
340
  body: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'As in' }] }] },
309
341
  onCancel: () => {},
310
- onSave: answering,
342
+ onSave: answering(),
311
343
  }}
312
344
  />
313
345
  ),
@@ -90,13 +90,30 @@ describe('sending, held until the relay answers', () => {
90
90
  expect(screen.queryByText('Sending…')).toBeNull()
91
91
  })
92
92
 
93
- it('a refusal keeps the words in the box and says why under it', async () => {
94
- render(<Box send={async () => ({ accepted: false, reason: 'rate-limited' })} />)
93
+ it('a refusal keeps the words in the box and says why under it in plain words, never the relay’s', async () => {
94
+ render(<Box send={async () => ({ accepted: false, reason: 'invalid: content exceeds maximum size of 262144 bytes' })} />)
95
95
  await type('Hello there')
96
96
  await press('Enter')
97
97
  await settle()
98
98
  expect(editorOf().getText()).toBe('Hello there')
99
- expect(screen.getByText('Not sent: rate-limited. Your text is back in the box.')).toBeTruthy()
99
+ expect(screen.getByText('Not sent: it is too long. Your text is back in the box.')).toBeTruthy()
100
+ expect(screen.queryByText(/262144|invalid:/)).toBeNull()
101
+ })
102
+
103
+ it('a send refused as on a deleted message says you can no longer write here, not that a message was deleted', async () => {
104
+ render(<Box send={async () => ({ accepted: false, reason: 'invalid: reply target event not found' })} />)
105
+ await type('Hello there')
106
+ await press('Enter')
107
+ await settle()
108
+ expect(screen.getByText('Not sent: you can no longer write here. Your text is back in the box.')).toBeTruthy()
109
+ })
110
+
111
+ it('a send that throws says something went wrong, not the error', async () => {
112
+ render(<Box send={async () => Promise.reject(new TypeError('Failed to fetch'))} />)
113
+ await type('Hello there')
114
+ await press('Enter')
115
+ await settle()
116
+ expect(screen.getByText('Not sent: something went wrong, try again. Your text is back in the box.')).toBeTruthy()
100
117
  expect(editorOf().isEditable).toBe(true)
101
118
  })
102
119
 
@@ -182,11 +199,11 @@ describe('sending, shown at once', () => {
182
199
  await press('Enter')
183
200
  expect(editorOf().getText()).toBe('')
184
201
  expect(onSent).toHaveBeenCalledTimes(1)
185
- answer.answer({ accepted: false, reason: 'rate-limited' })
202
+ answer.answer({ accepted: false, reason: 'restricted: not a channel member' })
186
203
  await settle()
187
204
  expect(editorOf().getText()).toBe('Hello there')
188
205
  expect(onRefused).toHaveBeenCalledTimes(1)
189
- expect(screen.getByText('Not sent: rate-limited. Your text is back in the box.')).toBeTruthy()
206
+ expect(screen.getByText('Not sent: you can no longer write here. Your text is back in the box.')).toBeTruthy()
190
207
  })
191
208
  })
192
209
 
@@ -242,14 +259,44 @@ describe('editing', () => {
242
259
  expect(onCancel).toHaveBeenCalledTimes(1)
243
260
  })
244
261
 
245
- it('a refused save keeps the words and says it was not saved', async () => {
246
- render(<Box edit={{ body, onSave: async () => ({ accepted: false, reason: 'gone' }), onCancel: () => {} }} />)
262
+ it('a refused save keeps the words and says it was not saved, and why', async () => {
263
+ render(<Box edit={{ body, onSave: async () => ({ accepted: false, reason: 'invalid: edit target not found or not editable by you' }), onCancel: () => {} }} />)
247
264
  await press('Enter')
248
265
  await settle()
249
- expect(screen.getByText('Not saved: gone. Your changes are still in the box.')).toBeTruthy()
266
+ expect(screen.getByText('Not saved: this message was deleted, or you can no longer write here. Your changes are still in the box.')).toBeTruthy()
250
267
  expect(editorOf().getText()).toBe('Said before')
251
268
  })
252
269
 
270
+ it('an edit emptied of its words and files cannot be saved, and says nothing', async () => {
271
+ const onSave = vi.fn<CommentBoxEdit['onSave']>(async () => ({ accepted: true }))
272
+ render(<Box edit={{ body, onSave, onCancel: () => {} }} />)
273
+ await act(async () => {
274
+ editorOf().commands.clearContent(true)
275
+ })
276
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true)
277
+ await press('Enter')
278
+ expect(onSave).not.toHaveBeenCalled()
279
+ expect(screen.queryByText(/Not saved/)).toBeNull()
280
+ })
281
+
282
+ it('an edit emptied of its words that keeps a file is saved', async () => {
283
+ const onSave = vi.fn<CommentBoxEdit['onSave']>(async () => ({ accepted: true }))
284
+ const files = [{ id: 'old', name: 'old.png', state: 'ready' as const, value: 'old-record' }]
285
+ render(<Box edit={{ body, files, writesFiles: true, onSave, onCancel: () => {} }} />)
286
+ await act(async () => {
287
+ editorOf().commands.clearContent(true)
288
+ })
289
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false)
290
+ await press('Enter')
291
+ expect(onSave).toHaveBeenCalledTimes(1)
292
+ expect(onSave.mock.calls[0][1]).toMatchObject([{ value: 'old-record' }])
293
+ })
294
+
295
+ it('a refusal reopened with nothing in the box does not say the changes are still there', () => {
296
+ render(<Box edit={{ body: { type: 'doc', content: [{ type: 'paragraph' }] }, refused: 'rate-limited: slow down', onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
297
+ expect(screen.getByText('Not saved: too many at once, try again in a moment.')).toBeTruthy()
298
+ })
299
+
253
300
  it('/ offers Upload and no Urgent in an edit whose save writes files', async () => {
254
301
  render(<Box upload={async () => ({ accepted: true, value: 1 })} edit={{ body, writesFiles: true, onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
255
302
  await type(' /')
@@ -317,8 +364,8 @@ describe('editing', () => {
317
364
  })
318
365
 
319
366
  it('an edit the app reopens after a refusal says why under it as it opens', () => {
320
- render(<Box edit={{ body, refused: 'rate-limited', onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
321
- expect(screen.getByText('Not saved: rate-limited. Your changes are still in the box.')).toBeTruthy()
367
+ render(<Box edit={{ body, refused: 'rate-limited: slow down', onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
368
+ expect(screen.getByText('Not saved: too many at once, try again in a moment. Your changes are still in the box.')).toBeTruthy()
322
369
  expect(editorOf().getText()).toBe('Said before')
323
370
  })
324
371
  })
@@ -363,13 +410,13 @@ describe('files', () => {
363
410
 
364
411
  it('a failed upload says why and holds Send and Enter until its ✕ takes it off', async () => {
365
412
  const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
366
- render(<Box send={send} upload={async () => ({ accepted: false, reason: 'too large' })} />)
413
+ render(<Box send={send} upload={async () => ({ accepted: false, reason: 'upload failed: 413 {"error":"file too large: 11534336 bytes (max 10485760)"}' })} />)
367
414
  const input = document.querySelector('input[type=file]') as HTMLInputElement
368
415
  await act(async () => {
369
416
  fireEvent.change(input, { target: { files: [new File(['x'], 'big.mov', { type: 'video/quicktime' })] } })
370
417
  })
371
418
  await settle()
372
- expect(screen.getByText('too large')).toBeTruthy()
419
+ expect(screen.getByText('Too large: the most is 10 MB')).toBeTruthy()
373
420
  expect(screen.queryByText('Uploading… Send waits for the file.')).toBeNull()
374
421
  await type('See this')
375
422
  expect(screen.getByText('Remove the file that did not upload to send.')).toBeTruthy()
@@ -386,6 +433,19 @@ describe('files', () => {
386
433
  expect(send.mock.calls[0][1]).toEqual([])
387
434
  })
388
435
 
436
+ it('a file over the server’s limit for its type says so on its card and never uploads', async () => {
437
+ const upload = vi.fn<NonNullable<CommentBoxProps['upload']>>(async () => ({ accepted: true, value: 1 }))
438
+ render(<Box upload={upload} />)
439
+ const gif = new File(['x'], 'big.gif', { type: 'image/gif' })
440
+ Object.defineProperty(gif, 'size', { value: 15 * 1024 * 1024 })
441
+ await act(async () => {
442
+ fireEvent.change(document.querySelector('input[type=file]') as HTMLInputElement, { target: { files: [gif] } })
443
+ })
444
+ expect(screen.getByText('Too large: the most is 10 MB')).toBeTruthy()
445
+ expect(screen.getByText('Remove the file that did not upload to send.')).toBeTruthy()
446
+ expect(upload).not.toHaveBeenCalled()
447
+ })
448
+
389
449
  it('an upload that arrives after the box opened offers Upload in /', async () => {
390
450
  const { rerender } = render(<Box />)
391
451
  rerender(<Box upload={async () => ({ accepted: true, value: 1 })} />)
@@ -1,6 +1,7 @@
1
1
  import { Fragment, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
2
2
  import { Extension, nodePasteRule, type AnyExtension, type EditorOptions } from '@tiptap/core'
3
3
  import { Editor, type JSONContent } from '@tiptap/react'
4
+ import { REFUSAL_REASONS, refusalCause, refusalReason, tooLarge, uploadRefusal } from '@estiva-app/conversation'
4
5
  import { IconLock, IconPaperclip, IconSquareRounded, IconX } from '@tabler/icons-react'
5
6
  import { AttachedCard } from './AttachedCard'
6
7
  import { AttachmentCard } from './AttachmentCard'
@@ -52,11 +53,15 @@ import { sendsInLayout } from './conversationScroll'
52
53
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-writes-and-reacts-with-one-shared-box.md
53
54
  */
54
55
 
55
- /** What the relay said about a send, an edit or an upload. */
56
- export type SendAnswer = { accepted: true } | { accepted: false; reason: string }
56
+ /**
57
+ * What the relay said about a send, an edit or a reaction. `reason` is the refusal as it came (the relay's words, an
58
+ * `Error`, an HTTP body, or `{ cause }` for an app's own): the box says it in `@estiva-app/conversation`'s plain words
59
+ * (`refusalReason`), the same in every app, never the relay's.
60
+ */
61
+ export type SendAnswer = { accepted: true } | { accepted: false; reason: unknown }
57
62
 
58
- /** What an upload answered: the app's own record of the file, or why not. */
59
- export type UploadAnswer = { accepted: true; value: unknown } | { accepted: false; reason: string }
63
+ /** What an upload answered: the app's own record of the file, or why not, as it came; the card says `uploadRefusal`'s line. */
64
+ export type UploadAnswer = { accepted: true; value: unknown } | { accepted: false; reason: unknown }
60
65
 
61
66
  /** Where a file in the box is: Send waits for one uploading. */
62
67
  export type BoxFileState = 'uploading' | 'ready' | 'failed'
@@ -74,6 +79,15 @@ export interface BoxFile {
74
79
  value?: unknown
75
80
  }
76
81
 
82
+ /**
83
+ * Why a send was refused. "This message was deleted" is an edit's or a reaction's (Decided, ONE-4): a new message
84
+ * refused the same way (a reply whose message went) is one you can no longer write here.
85
+ */
86
+ function sendRefusal(reason: unknown): string {
87
+ const cause = refusalCause(reason)
88
+ return REFUSAL_REASONS[cause === 'gone' ? 'no-access' : cause]
89
+ }
90
+
77
91
  /** A draft, in the box's terms — `@estiva-app/conversation`'s `composerDraft` is one. */
78
92
  export interface CommentBoxDraft {
79
93
  read(): JSONContent | undefined
@@ -92,8 +106,8 @@ export interface CommentBoxEdit {
92
106
  * Opt-in, so an app whose save drops them never offers it: a file added and silently lost.
93
107
  */
94
108
  writesFiles?: boolean
95
- /** Why the relay refused this edit, when the app reopens a box it closed at once: said under it as it opens. Read as the box opens, so a reopen is a new box (a new `key`). */
96
- refused?: string
109
+ /** Why the relay refused this edit, as it came, when the app reopens a box it closed at once: said under it as it opens. Read as the box opens, so a reopen is a new box (a new `key`). */
110
+ refused?: unknown
97
111
  onCancel: () => void
98
112
  /** Save; the box holds the words until the answer, and a refusal is said under it. */
99
113
  onSave: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>
@@ -495,7 +509,8 @@ function OpenCommentBox({
495
509
  }: CommentBoxProps) {
496
510
  const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])
497
511
  const [sending, setSending] = useState(false)
498
- const [refused, setRefused] = useState<string | null>(edit?.refused ?? null)
512
+ // The plain reason, never the relay's words (ONE-4).
513
+ const [refused, setRefused] = useState<string | null>(edit?.refused ? refusalReason(edit.refused) : null)
499
514
  // What shows under the box, and what ✕ took off.
500
515
  const [reading, setReading] = useState<BoxUnderRead | undefined>(undefined)
501
516
  const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set())
@@ -512,14 +527,19 @@ function OpenCommentBox({
512
527
  for (const file of picked) {
513
528
  fileCount += 1
514
529
  const id = `file-${fileCount}`
515
- setFiles((all) => [...all, { id, name: file.name, size: file.size, contentType: file.type, state: 'uploading' }])
516
- uploadOne(file).then(
517
- (answer) =>
518
- setFiles((all) =>
519
- all.map((f) => (f.id !== id ? f : answer.accepted ? { ...f, state: 'ready', value: answer.value } : { ...f, state: 'failed', note: answer.reason })),
520
- ),
521
- () => setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'failed', note: 'It could not be uploaded.' } : f))),
522
- )
530
+ const card = { id, name: file.name, size: file.size, contentType: file.type }
531
+ // Over the server's limit for its type: said on its card before anything uploads (Miky, 4 Nov).
532
+ const over = tooLarge(file)
533
+ if (over) {
534
+ setFiles((all) => [...all, { ...card, state: 'failed', note: over }])
535
+ continue
536
+ }
537
+ setFiles((all) => [...all, { ...card, state: 'uploading' }])
538
+ const failed = (reason: unknown) => setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'failed', note: uploadRefusal(reason, file) } : f)))
539
+ uploadOne(file).then((answer) => {
540
+ if (!answer.accepted) return failed(answer.reason)
541
+ setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'ready', value: answer.value } : f)))
542
+ }, failed)
523
543
  }
524
544
  return true
525
545
  }, [])
@@ -558,6 +578,19 @@ function OpenCommentBox({
558
578
  return () => handOut.current?.(null)
559
579
  }, [editor])
560
580
 
581
+ // Whether the edit's words are gone: Save waits for something to save, and a refusal says the changes are in the box only while they are.
582
+ const editing = !!edit
583
+ const [wordless, setWordless] = useState(() => editing && !!editor && isEmpty(editor))
584
+ useEffect(() => {
585
+ if (!editor || !editing) return
586
+ const read = () => setWordless(isEmpty(editor))
587
+ read()
588
+ editor.on('update', read)
589
+ return () => {
590
+ editor.off('update', read)
591
+ }
592
+ }, [editor, editing])
593
+
561
594
  // Drafts: every change is kept, and an empty box is no draft.
562
595
  useEffect(() => {
563
596
  if (!editor || edit) return
@@ -645,7 +678,7 @@ function OpenCommentBox({
645
678
  const sent = files.filter((f) => f.state === 'ready')
646
679
  const sentUnder = underOf(body)
647
680
  setRefused(null)
648
- const answered = (answer: Promise<SendAnswer>) => answer.catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
681
+ const answered = (answer: Promise<SendAnswer>) => answer.catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))
649
682
  if (showsAtOnce) {
650
683
  // Shown at once: the box empties now (the send box clears it); a refusal puts the words back above anything written since,
651
684
  // and what ✕ took off with them.
@@ -667,7 +700,7 @@ function OpenCommentBox({
667
700
  ed.commands.focus('end')
668
701
  setRemoved((now) => new Set([...now, ...took]))
669
702
  setFiles((all) => [...sent, ...all])
670
- setRefused(answer.reason)
703
+ setRefused(sendRefusal(answer.reason))
671
704
  })
672
705
  return true
673
706
  }
@@ -677,7 +710,7 @@ function OpenCommentBox({
677
710
  setSending(false)
678
711
  if (!answer.accepted) {
679
712
  layout?.refused()
680
- setRefused(answer.reason)
713
+ setRefused(sendRefusal(answer.reason))
681
714
  return
682
715
  }
683
716
  if (!ed.isDestroyed) ed.commands.clearContent(true)
@@ -691,17 +724,20 @@ function OpenCommentBox({
691
724
  [files, removed, underOf, showsAtOnce, send, draft, onSent, onRefused, layout],
692
725
  )
693
726
 
727
+ // An edit holding nothing, no words and no file, cannot be saved: Save is off, and nothing is said (Miky, 4 Nov). One
728
+ // emptied of its words that keeps a file is saved, in every app.
729
+ const holdsNothing = !!edit && wordless && files.length === 0
694
730
  save.current = () => {
695
- if (!editor || !edit || sending || uploading || failed > 0) return true
731
+ if (!editor || !edit || sending || uploading || failed > 0 || (isEmpty(editor) && files.length === 0)) return true
696
732
  setRefused(null)
697
733
  setSending(true)
698
734
  const body = editor.getJSON()
699
735
  void edit
700
736
  .onSave(body, files, underOf(body))
701
- .catch((): SendAnswer => ({ accepted: false, reason: 'try again in a moment' }))
737
+ .catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))
702
738
  .then((answer) => {
703
739
  setSending(false)
704
- if (!answer.accepted) setRefused(answer.reason)
740
+ if (!answer.accepted) setRefused(refusalReason(answer.reason))
705
741
  })
706
742
  return true
707
743
  }
@@ -762,7 +798,7 @@ function OpenCommentBox({
762
798
 
763
799
  const refusedLine = refused && (
764
800
  <FieldLine tone="error">
765
- {edit ? `Not saved: ${refused}. Your changes are still in the box.` : `Not sent: ${refused}. Your text is back in the box.`}
801
+ {edit ? `Not saved: ${refused}.${holdsNothing ? '' : ' Your changes are still in the box.'}` : `Not sent: ${refused}. Your text is back in the box.`}
766
802
  </FieldLine>
767
803
  )
768
804
 
@@ -803,7 +839,7 @@ function OpenCommentBox({
803
839
  <Button variant="outlined" size="small" onClick={edit.onCancel}>
804
840
  Cancel
805
841
  </Button>
806
- <Button variant="primary" size="small" disabled={uploading || failed > 0 || sending} onClick={() => save.current()}>
842
+ <Button variant="primary" size="small" disabled={uploading || failed > 0 || sending || holdsNothing} onClick={() => save.current()}>
807
843
  Save
808
844
  </Button>
809
845
  </div>