@estiva-app/ui 0.83.0 → 0.84.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.
@@ -1 +1 @@
1
- {"version":3,"file":"links.d.ts","sourceRoot":"","sources":["../src/links.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAa,MAAM,cAAc,CAAA;AAenD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,qBAqCzB,CAAA;AAEF,wIAAwI;AACxI,eAAO,MAAM,MAAM,iEAIjB,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,WAAW,iEAatB,CAAA;AAcF,gIAAgI;AAChI,eAAO,MAAM,UAAU,kEAAkE,CAAA;AAKzF,4IAA4I;AAC5I,eAAO,MAAM,oBAAoB;;;;;CAAqG,CAAA;AAItI,eAAO,MAAM,SAAS,qBAuCpB,CAAA"}
1
+ {"version":3,"file":"links.d.ts","sourceRoot":"","sources":["../src/links.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAa,MAAM,cAAc,CAAA;AAenD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,qBAwCzB,CAAA;AAEF,wIAAwI;AACxI,eAAO,MAAM,MAAM,iEAIjB,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,WAAW,iEAatB,CAAA;AAcF,gIAAgI;AAChI,eAAO,MAAM,UAAU,kEAAkE,CAAA;AAKzF,4IAA4I;AAC5I,eAAO,MAAM,oBAAoB;;;;;CAAqG,CAAA;AAItI,eAAO,MAAM,SAAS,qBAuCpB,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/ui",
3
- "version": "0.83.0",
3
+ "version": "0.84.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",
package/registry.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.83.0",
7
+ "packageVersion": "0.84.0",
8
8
  "exports": 209,
9
9
  "typeExports": 207,
10
10
  "files": null
@@ -2098,6 +2098,18 @@
2098
2098
  "required": false,
2099
2099
  "note": "Called when a send shown at once was refused, so the app takes it back."
2100
2100
  },
2101
+ {
2102
+ "name": "marked",
2103
+ "takes": "a handler",
2104
+ "required": false,
2105
+ "note": "The bar down the text's left edge shows while this holds, besides while an urgent mention is in the box: the app's own marks (a highlight)."
2106
+ },
2107
+ {
2108
+ "name": "onEditor",
2109
+ "takes": "a handler",
2110
+ "required": false,
2111
+ "note": "Called with the box's editor once it is drawn, and with `null` as it goes: an app's launcher inserts into the box last used."
2112
+ },
2101
2113
  {
2102
2114
  "name": "className",
2103
2115
  "takes": "text",
@@ -2238,7 +2250,7 @@
2238
2250
  "kind": "helper",
2239
2251
  "importPath": "@estiva-app/ui/editor",
2240
2252
  "sourceFile": "src/ComposeBox.tsx",
2241
- "purpose": "The editor's own classes inside the box: Peek's, rich text with no outline.",
2253
+ "purpose": "The classes the box's editor wears: rich text with no outline.",
2242
2254
  "purposeFrom": "comment",
2243
2255
  "props": [],
2244
2256
  "variants": [],
@@ -17,9 +17,15 @@ The one box every app writes a comment, a reply and a line of a conversation in:
17
17
  - `upload` to offer files: the paperclip, `/` → Upload, a pasted picture and a dropped file.
18
18
  - `under` to show, while something is written, the one card it will be sent with (✕ takes it off) and the live part of each block link, drawn as the app draws them under a sent message. An edit box shows the card and no part.
19
19
  - `closed` where nothing can be written (archived, signed out): a line saying why, in the box's place. No greyed box.
20
+ - `marked` when the app has its own reason for the bar down the text, besides an urgent mention, which always draws it.
21
+ - `onEditor` when something outside the box writes into it: the app keeps the editor it is handed and inserts into the box last used.
20
22
 
21
23
  <Canvas of={CommentBoxStories.Refused} />
22
24
 
25
+ <Canvas of={CommentBoxStories.WithAnAppsOwnRows} />
26
+
27
+ <Canvas of={CommentBoxStories.LongDraft} />
28
+
23
29
  <Canvas of={CommentBoxStories.CardUnderTheBox} />
24
30
 
25
31
  ## When not
@@ -62,6 +68,8 @@ const draft = composerDraft(createDraftStore(localStorage), draftKeys.thread(roo
62
68
  - **`under.read` is the app's reading of the draft**: `@estiva-app/conversation`'s `boxReadOf(body, context)` says which file gets the card and which parts show; the app adds its own view of each. Call `under.changed`'s listener when what a link names comes back. `send`'s third argument is `{ card }`, the card still shown, which the app writes with `embedsToSend` (or `embedsToEdit` for `onSave`).
63
69
  - **An edit box's `read` passes `previous: namedBefore(<the message's text>)`**, so only a file the edit names first gets a card. A card the message already has, or one taken off with ✕ before or after sending, never shows again in the edit box, and Save leaves it as it was.
64
70
  - **A link chip for a pasted app URL** is the app's `LinkChips`, passed in `extensions`.
71
+ - **`keepCommentBoxWarm({ extensions, referenceView })`**, called once as the app starts, builds an editor while the page is idle, and the next empty box given those same `extensions` and `referenceView` (the same objects, in the same order) takes it, so it opens at once. A box opening with a draft or an edit, or with other extensions, builds its own. Keep `extensions` a module constant: a new array per render never matches.
72
+ - **`onEditor` gets `null` as the box goes**, so a launcher never writes into a box that is gone.
65
73
 
66
74
  ## What it owns
67
75
 
@@ -76,7 +84,9 @@ It does these by itself. Write none of them around it.
76
84
  | The draft, written as you type and forgotten once sent | an update listener |
77
85
  | Files: picking, pasting, dropping, uploading, failing; Send waits for an upload and holds on a failed file until its ✕ removes it | a file list |
78
86
  | The card under the box, its ✕, and a ✕ forgotten once the link is taken out; a refused send puts back what ✕ took off | a card state |
79
- | A URL pasted over words links them when a message can carry them as a link (one line of plain words, no bracket, no chip, no `)` in the URL); otherwise the URL goes in after the words. Typing after linked words is not linked | a paste handler |
87
+ | A URL pasted over words links them when a message can carry them as a link (one line of plain words, no bracket, no chip, no `)` in the URL); otherwise the URL goes in after the words. The caret goes after the link, so the next Enter sends. Typing after linked words is not linked | a paste handler |
88
+ | A long draft stops at half the window and scrolls inside the box, in the send box and the edit box | a height or a scroll container |
89
+ | The bar down the text while an urgent mention is in the box | an urgent check |
80
90
  | The read-only line | a disabled box |
81
91
 
82
92
  ## Keys
@@ -1,10 +1,13 @@
1
1
  import type { Meta, StoryObj } from '@storybook/react-vite'
2
2
  import { useState } from 'react'
3
- import type { JSONContent } from '@tiptap/react'
3
+ import type { Editor, JSONContent } from '@tiptap/react'
4
+ import { IconSquareRounded } from '@tabler/icons-react'
4
5
  import { expect, userEvent, waitFor, within } from 'storybook/test'
6
+ import type { ReferenceViewProps } from './BlockNodes'
5
7
  import { Button } from './Button'
6
8
  import { CommentBox, commentBoxRows, type BoxUnder, type CommentBoxDraft, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
7
- import type { CaptionedItem, MentionPerson, ReferenceSection } from './ComposerTriggers'
9
+ import type { CaptionedItem, MentionPerson, ReferenceSection, SlashCommand } from './ComposerTriggers'
10
+ import { InlineChip } from './InlineChip'
8
11
  import { Kbd } from './Kbd'
9
12
  import { LinkCard } from './LinkCard'
10
13
  import { ITEM, ready } from './linked.examples'
@@ -264,6 +267,76 @@ export const EditingWithACard: Story = {
264
267
  },
265
268
  }
266
269
 
270
+ /** An app's own `/` rows, after the kit's: each puts a label at the start of the box, which the app marks. */
271
+ const OWN_ROWS: SlashCommand[] = ['one', 'two', 'three', 'four', 'five'].map((n) => ({
272
+ key: `own-${n}`,
273
+ row: { label: `Item ${n}` },
274
+ keywords: ['item'],
275
+ run: (editor) => editor.chain().focus().insertContentAt(1, `Item ${n}: `).run(),
276
+ }))
277
+
278
+ /** The app's own chip for a reference the box holds. */
279
+ const OwnChip = ({ uri }: ReferenceViewProps) => (
280
+ <InlineChip icon={<IconSquareRounded size={16} stroke={1.5} />}>{uri.endsWith('one') ? 'Item one' : 'Item'}</InlineChip>
281
+ )
282
+
283
+ const WITH_A_REFERENCE: JSONContent = {
284
+ type: 'doc',
285
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'As in ' }, { type: 'reference', attrs: { uri: 'nostr:item-one' } }] }],
286
+ }
287
+
288
+ /** What an app adds around the box: its own rows and mark, its chip, and a control outside the box that writes into the box last used. */
289
+ function AppAround() {
290
+ const [last, setLast] = useState<Editor | null>(null)
291
+ return (
292
+ <div className="flex flex-col gap-3">
293
+ <div>
294
+ <Button variant="outlined" size="small" disabled={!last} onClick={() => last?.chain().focus('end').insertContent(' Written from outside the box.').run()}>
295
+ Write into the box
296
+ </Button>
297
+ </div>
298
+ <Live
299
+ start={WITH_A_REFERENCE}
300
+ insert={[...INSERT, ...OWN_ROWS]}
301
+ referenceView={OwnChip}
302
+ marked={(editor) => editor.getText().startsWith('Item ')}
303
+ onEditor={(editor) => setLast(editor)}
304
+ />
305
+ </div>
306
+ )
307
+ }
308
+
309
+ /**
310
+ * An app's own `/` rows after the kit's, its own mark (the bar down the text,
311
+ * as an urgent mention draws it), its chip for a reference, a pasted picture
312
+ * becoming a file, and a control outside the box writing into it.
313
+ */
314
+ export const WithAnAppsOwnRows: Story = { render: () => <AppAround />, play: typeInto('/item') }
315
+
316
+ /** An urgent mention in the box: the bar down the text while it is there. */
317
+ export const UrgentMarked: Story = {
318
+ render: () => (
319
+ <Live
320
+ start={{
321
+ type: 'doc',
322
+ content: [{ type: 'paragraph', content: [{ type: 'urgentMention', attrs: { id: 'two', label: 'Person two', pubkey: '2'.repeat(64) } }, { type: 'text', text: ' please look' }] }],
323
+ }}
324
+ />
325
+ ),
326
+ }
327
+
328
+ /** A draft longer than the box: it stops at half the window and scrolls inside, so its first line can be reached. */
329
+ export const LongDraft: Story = {
330
+ render: () => (
331
+ <Live
332
+ start={{
333
+ type: 'doc',
334
+ content: Array.from({ length: 40 }, (_, i) => ({ type: 'paragraph', content: [{ type: 'text', text: `Line ${i + 1} of a long draft.` }] })),
335
+ }}
336
+ />
337
+ ),
338
+ }
339
+
267
340
  /** The narrowest column it sits in, 320px, with a file uploading. */
268
341
  export const Narrow: Story = {
269
342
  decorators: [
@@ -4,13 +4,13 @@
4
4
  * sending held or shown at once, a refusal putting the words back, the edit
5
5
  * mode, drafts, files and the read-only line.
6
6
  */
7
- import { act } from 'react'
7
+ import { act, Suspense, use } from 'react'
8
8
  import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
9
9
  import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
10
- import type { Editor } from '@tiptap/core'
10
+ import { Extension, type Editor } from '@tiptap/core'
11
11
  import { Fragment, Slice } from '@tiptap/pm/model'
12
12
  import type { JSONContent } from '@tiptap/react'
13
- import { CommentBox, commentBoxRows, type BoxUnder, type CommentBoxDraft, type CommentBoxEdit, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
13
+ import { CommentBox, commentBoxRows, keepCommentBoxWarm, type BoxUnder, type CommentBoxDraft, type CommentBoxEdit, type CommentBoxProps, type SendAnswer, type UploadAnswer } from './CommentBox'
14
14
  import type { MentionPerson } from './ComposerTriggers'
15
15
 
16
16
  const PEOPLE: MentionPerson[] = [{ id: 'one', name: 'Person one', pubkey: 'b'.repeat(64) }]
@@ -422,6 +422,18 @@ describe('a URL pasted over words', () => {
422
422
  expect(runs()).toEqual(['text:see ', `link:the plan>${URL_}`, 'text:! now'])
423
423
  })
424
424
 
425
+ it('leaves the caret after the linked words, so the selection strip stays shut and one Enter sends (COMM-8)', async () => {
426
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
427
+ render(<Box send={send} />)
428
+ await type('see the plan')
429
+ await pasteOver(5, 13, URL_)
430
+ expect(editorOf().state.selection.empty).toBe(true)
431
+ expect(editorOf().state.selection.from).toBe(13)
432
+ expect(screen.queryByRole('textbox', { name: /link/i })).toBeNull()
433
+ await press('Enter')
434
+ expect(send).toHaveBeenCalledTimes(1)
435
+ })
436
+
425
437
  it('select-all over one line links all its words, without the full stop copied after the URL', async () => {
426
438
  render(<Box edit={editing(doc({ type: 'text', text: 'the plan' }))} />)
427
439
  await pasteOver('all', 0, `${URL_}.`)
@@ -446,3 +458,158 @@ describe('a URL pasted over words', () => {
446
458
  expect(runs()).toEqual(['text:the spec https://wiki.example/Nostr_(protocol)'])
447
459
  })
448
460
  })
461
+
462
+ describe('what an app adds around the box', () => {
463
+ const bar = () => document.querySelector('[data-composer-editor]')?.hasAttribute('data-marked')
464
+ const URGENT = { type: 'urgentMention', attrs: { id: 'one', label: 'Person one' } }
465
+
466
+ it('draws the bar down the text while an urgent mention is in the box, and drops it when the mention goes', async () => {
467
+ render(<Box />)
468
+ expect(bar()).toBe(false)
469
+ await act(async () => {
470
+ editorOf().chain().focus('end').insertContent([URGENT, { type: 'text', text: ' look' }]).run()
471
+ })
472
+ expect(bar()).toBe(true)
473
+ await act(async () => {
474
+ editorOf().commands.clearContent(true)
475
+ })
476
+ expect(bar()).toBe(false)
477
+ })
478
+
479
+ it("draws the bar while the app's own mark holds, in the edit box too", async () => {
480
+ const marked = (editor: Editor) => editor.getText().includes('!!')
481
+ const body: JSONContent = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'plain' }] }] }
482
+ render(<Box marked={marked} edit={{ body, onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
483
+ expect(bar()).toBe(false)
484
+ await type(' !!')
485
+ expect(bar()).toBe(true)
486
+ })
487
+
488
+ it("hands the box's editor out, so a launcher inserts into it and the words are sent; and null once it goes", async () => {
489
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
490
+ let handed: Editor | null = null
491
+ const { unmount } = render(<Box send={send} onEditor={(editor) => (handed = editor)} />)
492
+ await act(async () => {
493
+ handed!.chain().focus('end').insertContent('from the launcher').run()
494
+ })
495
+ await press('Enter')
496
+ expect(textOf(send.mock.calls[0][0])).toBe('from the launcher')
497
+ unmount()
498
+ expect(handed).toBeNull()
499
+ })
500
+ })
501
+
502
+ describe('a box built ahead', () => {
503
+ /** Runs what waits for an idle moment at once, as a page with nothing to do would. */
504
+ function idleNow() {
505
+ const queued: IdleRequestCallback[] = []
506
+ window.requestIdleCallback = ((callback: IdleRequestCallback) => queued.push(callback)) as typeof window.requestIdleCallback
507
+ return () => {
508
+ while (queued.length) queued.shift()!({ didTimeout: false, timeRemaining: () => 50 })
509
+ }
510
+ }
511
+
512
+ /** An app's own extension that counts the editors built with it. */
513
+ function counted() {
514
+ const built: Editor[] = []
515
+ const extensions = [Extension.create({ name: 'appOwn', onBeforeCreate: ({ editor }) => void built.push(editor as Editor) })]
516
+ return { built, extensions }
517
+ }
518
+
519
+ it("takes the editor built while the page was idle, labelled as this box, and it sends with this box's send", async () => {
520
+ const flush = idleNow()
521
+ const { built, extensions } = counted()
522
+ keepCommentBoxWarm({ extensions })
523
+ flush()
524
+ expect(built).toHaveLength(1)
525
+ let handed: Editor | null = null
526
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
527
+ render(<Box send={send} extensions={extensions} onEditor={(editor) => (handed = editor)} />)
528
+ expect(handed).toBe(built[0])
529
+ expect(screen.getByRole('textbox', { name: 'Write' })).toBeTruthy()
530
+ await type('ahead')
531
+ await press('Enter')
532
+ expect(textOf(send.mock.calls[0][0])).toBe('ahead')
533
+ // …and the next spare is built for the next box.
534
+ flush()
535
+ expect(built).toHaveLength(2)
536
+ })
537
+
538
+ it('a box opening with a draft, or with other extensions, builds its own and leaves the spare', async () => {
539
+ const flush = idleNow()
540
+ const { built, extensions } = counted()
541
+ keepCommentBoxWarm({ extensions })
542
+ flush()
543
+ let handed: Editor | null = null
544
+ const kept: CommentBoxDraft = { read: () => ({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'kept' }] }] }), write: () => {}, clear: () => {} }
545
+ render(<Box draft={kept} extensions={extensions} onEditor={(editor) => (handed = editor)} />)
546
+ expect(built).toHaveLength(2)
547
+ expect(handed).not.toBe(built[0])
548
+ expect(editorOf().getText()).toBe('kept')
549
+ cleanup()
550
+ render(<Box onEditor={(editor) => (handed = editor)} />)
551
+ expect(handed).not.toBe(built[0])
552
+ })
553
+
554
+ it('works again, with what was typed, after a loading page hides the box and shows it again', async () => {
555
+ // The box lets its editor go a moment after it is hidden: that moment is this clock's.
556
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
557
+ try {
558
+ let kept: JSONContent | undefined
559
+ const draft: CommentBoxDraft = { read: () => kept, write: (body) => void (kept = body), clear: () => void (kept = undefined) }
560
+ const send = vi.fn<CommentBoxProps['send']>(async () => ({ accepted: true }))
561
+ const loading = later<void>()
562
+ function Loading() {
563
+ use(loading.promise)
564
+ return null
565
+ }
566
+ function Page({ more }: { more: boolean }) {
567
+ return (
568
+ <Suspense fallback={<p>Loading</p>}>
569
+ <Box send={send} draft={draft} />
570
+ {more && <Loading />}
571
+ </Suspense>
572
+ )
573
+ }
574
+ const { rerender } = render(<Page more={false} />)
575
+ await type('typed before')
576
+ await act(async () => rerender(<Page more />))
577
+ expect(screen.getByText('Loading')).toBeTruthy()
578
+ act(() => vi.advanceTimersByTime(50))
579
+ await act(async () => {
580
+ loading.answer()
581
+ await loading.promise
582
+ })
583
+ expect(screen.queryByText('Loading')).toBeNull()
584
+ expect(screen.queryByRole('textbox', { name: 'Write' })).not.toBeNull()
585
+ expect(editorOf().getText()).toBe('typed before')
586
+ await press('Enter')
587
+ expect(textOf(send.mock.calls[0][0])).toBe('typed before')
588
+ } finally {
589
+ vi.useFakeTimers({ toFake: ['Date'] })
590
+ }
591
+ })
592
+ })
593
+
594
+ describe('a long draft', () => {
595
+ const said: JSONContent = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Said before' }] }] }
596
+
597
+ it('scrolls in the package’s ScrollArea, capped at half the window, in the send box and the edit box — not with the browser’s bar', () => {
598
+ for (const props of [{}, { edit: { body: said, onSave: async () => ({ accepted: true as const }), onCancel: () => {} } }]) {
599
+ const { unmount } = render(<Box {...props} />)
600
+ const text = document.querySelector('.ProseMirror') as HTMLElement
601
+ // The text itself never scrolls: that is the browser's bar (Katerina, 21 Oct).
602
+ expect(text.className).not.toMatch(/(^|\s)overflow(-[xy])?-(auto|scroll)(\s|$)/)
603
+ expect(text.className).not.toContain('max-h-')
604
+ // ScrollArea's viewport (its overscroll rule is its mark) holds the text, with the cap.
605
+ const viewport = text.parentElement?.closest('[class*="overscroll-y-contain"]') as HTMLElement | null
606
+ expect(viewport).not.toBeNull()
607
+ expect(viewport!.className.split(' ')).toContain('max-h-[50vh]')
608
+ // The region reaches into the box's right padding and its content gives it back: the bar at the box's edge, the text where it was.
609
+ expect(viewport!.parentElement!.className.split(' ')).toContain('-mr-3')
610
+ expect((viewport!.firstElementChild as HTMLElement).className.split(' ')).toContain('pr-3')
611
+ expect(viewport!.closest('[data-composer-editor]')).not.toBeNull()
612
+ unmount()
613
+ }
614
+ })
615
+ })