@estiva-app/ui 0.82.1 → 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.
Files changed (44) hide show
  1. package/dist/BlockNodes.d.ts +16 -5
  2. package/dist/BlockNodes.d.ts.map +1 -1
  3. package/dist/CommentBox.d.ts +11 -2
  4. package/dist/CommentBox.d.ts.map +1 -1
  5. package/dist/ComposeBox.d.ts +17 -0
  6. package/dist/ComposeBox.d.ts.map +1 -1
  7. package/dist/DocumentEditor.d.ts +5 -4
  8. package/dist/DocumentEditor.d.ts.map +1 -1
  9. package/dist/LinkPlaces.d.ts +51 -0
  10. package/dist/LinkPlaces.d.ts.map +1 -0
  11. package/dist/ReferenceMenu.d.ts.map +1 -1
  12. package/dist/editor.d.ts +1 -0
  13. package/dist/editor.d.ts.map +1 -1
  14. package/dist/editor.js +392 -178
  15. package/dist/editor.js.map +4 -4
  16. package/dist/linked.examples.d.ts.map +1 -1
  17. package/dist/links.d.ts.map +1 -1
  18. package/package.json +1 -1
  19. package/registry.json +75 -12
  20. package/src/BlockNodes.tsx +36 -9
  21. package/src/CommentBox.mdx +11 -1
  22. package/src/CommentBox.stories.tsx +75 -2
  23. package/src/CommentBox.test.tsx +170 -3
  24. package/src/CommentBox.tsx +211 -53
  25. package/src/ComposeBox.tsx +19 -2
  26. package/src/DocumentEditor.mdx +7 -2
  27. package/src/DocumentEditor.stories.tsx +101 -15
  28. package/src/DocumentEditor.test.tsx +49 -0
  29. package/src/DocumentEditor.tsx +17 -10
  30. package/src/LinkPlaces.mdx +59 -0
  31. package/src/LinkPlaces.stories.tsx +60 -0
  32. package/src/LinkPlaces.test.ts +134 -0
  33. package/src/LinkPlaces.ts +169 -0
  34. package/src/ReferenceCards.mdx +4 -0
  35. package/src/ReferenceMenu.mdx +32 -24
  36. package/src/ReferenceMenu.stories.tsx +15 -16
  37. package/src/ReferenceMenu.test.tsx +161 -57
  38. package/src/ReferenceMenu.tsx +48 -44
  39. package/src/editor.ts +1 -0
  40. package/src/linked.examples.ts +4 -3
  41. package/src/links.ts +4 -1
  42. package/src/pages.test.ts +2 -2
  43. package/src/registry/registry.test.ts +6 -6
  44. package/stories/Choosing.mdx +3 -2
@@ -1 +1 @@
1
- {"version":3,"file":"linked.examples.d.ts","sourceRoot":"","sources":["../src/linked.examples.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,MAAM,EAAgB,SAAS,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAI7E,eAAO,MAAM,cAAc,EAAE,YAAY,EAKxC,CAAA;AAED,eAAO,MAAM,MAAM,EAAE,YAAY,EAIhC,CAAA;AAMD,8FAA8F;AAC9F,eAAO,MAAM,IAAI,EAAE,MAYlB,CAAA;AAED,wDAAwD;AACxD,eAAO,MAAM,cAAc,EAAE,MAAuG,CAAA;AAEpI,oFAAoF;AACpF,eAAO,MAAM,WAAW,EAAE,MAA0F,CAAA;AAEpH,+DAA+D;AAC/D,eAAO,MAAM,eAAe,EAAE,MAAiI,CAAA;AAE/J,0EAA0E;AAC1E,eAAO,MAAM,KAAK,EAAE,MAgBnB,CAAA;AAED,yFAAyF;AACzF,eAAO,MAAM,KAAK,EAAE,MAUnB,CAAA;AAED,8DAA8D;AAC9D,eAAO,MAAM,IAAI,EAAE,MASlB,CAAA;AAED,kDAAkD;AAClD,eAAO,MAAM,IAAI,EAAE,MAQlB,CAAA;AAED,eAAO,MAAM,KAAK,GAAI,QAAQ,MAAM,KAAG,SAAyC,CAAA;AAChF,eAAO,MAAM,OAAO,EAAE,SAA+C,CAAA;AACrE,eAAO,MAAM,WAAW,EAAE,SAAiH,CAAA"}
1
+ {"version":3,"file":"linked.examples.d.ts","sourceRoot":"","sources":["../src/linked.examples.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,MAAM,EAAgB,SAAS,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAI7E,eAAO,MAAM,cAAc,EAAE,YAAY,EAKxC,CAAA;AAED,eAAO,MAAM,MAAM,EAAE,YAAY,EAIhC,CAAA;AAMD,8FAA8F;AAC9F,eAAO,MAAM,IAAI,EAAE,MAYlB,CAAA;AAED,wDAAwD;AACxD,eAAO,MAAM,cAAc,EAAE,MAAuG,CAAA;AAEpI,oFAAoF;AACpF,eAAO,MAAM,WAAW,EAAE,MAA0F,CAAA;AAEpH,+DAA+D;AAC/D,eAAO,MAAM,eAAe,EAAE,MAAiI,CAAA;AAE/J,0EAA0E;AAC1E,eAAO,MAAM,KAAK,EAAE,MAiBnB,CAAA;AAED,yFAAyF;AACzF,eAAO,MAAM,KAAK,EAAE,MAUnB,CAAA;AAED,8DAA8D;AAC9D,eAAO,MAAM,IAAI,EAAE,MASlB,CAAA;AAED,kDAAkD;AAClD,eAAO,MAAM,IAAI,EAAE,MAQlB,CAAA;AAED,eAAO,MAAM,KAAK,GAAI,QAAQ,MAAM,KAAG,SAAyC,CAAA;AAChF,eAAO,MAAM,OAAO,EAAE,SAA+C,CAAA;AACrE,eAAO,MAAM,WAAW,EAAE,SAAiH,CAAA"}
@@ -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.82.1",
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,9 +4,9 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.82.1",
8
- "exports": 206,
9
- "typeExports": 206,
7
+ "packageVersion": "0.84.0",
8
+ "exports": 209,
9
+ "typeExports": 207,
10
10
  "files": null
11
11
  },
12
12
  "storybook": {
@@ -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": [],
@@ -2860,7 +2872,7 @@
2860
2872
  "name": "referenceView",
2861
2873
  "takes": "ComponentType<ReferenceViewProps>",
2862
2874
  "required": false,
2863
- "note": "Draws a chip: the app's own, which resolves what it names."
2875
+ "note": "Draws a link: the app's own, which resolves what it names — its chip, its row or its card in the row's place, as `place` says (§13.3)."
2864
2876
  },
2865
2877
  {
2866
2878
  "name": "attachmentView",
@@ -2868,12 +2880,6 @@
2868
2880
  "required": false,
2869
2881
  "note": "Draws a placed file: the app's own card."
2870
2882
  },
2871
- {
2872
- "name": "cards",
2873
- "takes": "a handler",
2874
- "required": false,
2875
- "note": "Drawn after the text: the cards chips ask for, as the app draws them."
2876
- },
2877
2883
  {
2878
2884
  "name": "wrap",
2879
2885
  "takes": "a handler",
@@ -4805,6 +4811,44 @@
4805
4811
  "app": null,
4806
4812
  "looks": []
4807
4813
  },
4814
+ {
4815
+ "name": "linkPlaceAt",
4816
+ "repo": "estiva-ui",
4817
+ "kind": "helper",
4818
+ "importPath": "@estiva-app/ui/editor",
4819
+ "sourceFile": "src/LinkPlaces.ts",
4820
+ "purpose": "How the reference node at `pos` draws. Anything that is not a reference with a `uri` draws as a chip.",
4821
+ "purposeFrom": "comment",
4822
+ "props": [],
4823
+ "variants": [],
4824
+ "ownsBehaviours": [],
4825
+ "status": "stable",
4826
+ "migrationStage": null,
4827
+ "docsId": "primitives-linkplaces--docs",
4828
+ "storyId": "primitives-linkplaces--in-an-editor",
4829
+ "docPage": null,
4830
+ "app": null,
4831
+ "looks": []
4832
+ },
4833
+ {
4834
+ "name": "LinkPlaces",
4835
+ "repo": "estiva-ui",
4836
+ "kind": "component",
4837
+ "importPath": "@estiva-app/ui/editor",
4838
+ "sourceFile": "src/LinkPlaces.ts",
4839
+ "purpose": "Where a link in a document sits decides how it draws: its chip in a sentence, its row alone on its line, and its card in the row's place when its writer chose one (`embed` `detailed`).",
4840
+ "purposeFrom": "page",
4841
+ "props": [],
4842
+ "variants": [],
4843
+ "ownsBehaviours": [],
4844
+ "status": "stable",
4845
+ "migrationStage": null,
4846
+ "docsId": "primitives-linkplaces--docs",
4847
+ "storyId": "primitives-linkplaces--in-an-editor",
4848
+ "docPage": "src/LinkPlaces.mdx",
4849
+ "app": null,
4850
+ "looks": []
4851
+ },
4808
4852
  {
4809
4853
  "name": "LinkPreview",
4810
4854
  "repo": "estiva-ui",
@@ -7257,7 +7301,7 @@
7257
7301
  "kind": "component",
7258
7302
  "importPath": "@estiva-app/ui/editor",
7259
7303
  "sourceFile": "src/ReferenceMenu.tsx",
7260
- "purpose": "What a chip in a document offers whoever is writing it: Open, and its Card — none, compact or detailed.",
7304
+ "purpose": "What a link in a document offers whoever is writing it: Open, and — when it is alone on its line — Show as Row or Card.",
7261
7305
  "purposeFrom": "page",
7262
7306
  "props": [],
7263
7307
  "variants": [],
@@ -8399,6 +8443,25 @@
8399
8443
  "app": null,
8400
8444
  "looks": []
8401
8445
  },
8446
+ {
8447
+ "name": "staysChip",
8448
+ "repo": "estiva-ui",
8449
+ "kind": "helper",
8450
+ "importPath": "@estiva-app/ui/editor",
8451
+ "sourceFile": "src/LinkPlaces.ts",
8452
+ "purpose": "Whether what `uri` names stays a chip alone on its line: a person (`npub`, `nprofile`) or a Folder (an `naddr` of kind 39000).",
8453
+ "purposeFrom": "comment",
8454
+ "props": [],
8455
+ "variants": [],
8456
+ "ownsBehaviours": [],
8457
+ "status": "stable",
8458
+ "migrationStage": null,
8459
+ "docsId": "primitives-linkplaces--docs",
8460
+ "storyId": "primitives-linkplaces--in-an-editor",
8461
+ "docPage": null,
8462
+ "app": null,
8463
+ "looks": []
8464
+ },
8402
8465
  {
8403
8466
  "name": "SuggestionMenu",
8404
8467
  "repo": "estiva-ui",
@@ -7,6 +7,7 @@ import type { EditorView, NodeView } from '@tiptap/pm/view'
7
7
  import { NodeViewWrapper, ReactNodeViewRenderer, ReactRenderer, type ReactNodeViewProps } from '@tiptap/react'
8
8
  import { Checkbox, type CheckboxProps } from './Checkbox'
9
9
  import { calloutLook } from './RichText'
10
+ import { placeOf, type LinkPlace } from './LinkPlaces'
10
11
  import { referenceMenuClick } from './ReferenceMenu'
11
12
 
12
13
  /*
@@ -372,6 +373,14 @@ const webUrl = (raw: string | null): string | null => (raw && /^https?:\/\/\S+$/
372
373
  export interface ReferenceViewProps {
373
374
  uri: string
374
375
  href?: string
376
+ /**
377
+ * Where it sits, so how it draws: `chip` in a sentence, `row` alone on its
378
+ * line, `card` in the row's place (`LinkPlaces`, §13.3). Always `chip` in an
379
+ * editor without `LinkPlaces`.
380
+ */
381
+ place?: LinkPlace
382
+ /** Being edited: a click opens its menu rather than it, so a row or card shows no hover preview. */
383
+ editing?: boolean
375
384
  }
376
385
 
377
386
  export interface ReferenceNodeOptions {
@@ -390,11 +399,13 @@ export interface ReferenceNodeOptions {
390
399
  * is also how deleting one works. `marks` carries the run's other marks, so a
391
400
  * bold reference comes back bold.
392
401
  *
393
- * `embed` is the card its writer chose to draw after its block — `compact`,
394
- * `detailed`, or null for none (SPEC §13.3, "A reference's card") — and `extra`
395
- * every key of the mark this version does not know. Both are declared so that
396
- * ProseMirror keeps them: an undeclared attribute is dropped when the node is
397
- * made, and the card with it. `ReferenceCards` draws the cards.
402
+ * `embed` is the card its writer chose — `detailed`, drawn in the row's place
403
+ * when the reference is alone on its line, or null for its row (SPEC §13.3, "A
404
+ * reference's card"; older writers wrote `compact`, which draws the row) — and
405
+ * `extra` every key of the mark this version does not know. Both are declared
406
+ * so that ProseMirror keeps them: an undeclared attribute is dropped when the
407
+ * node is made, and the card with it. With `LinkPlaces`, the view is told where
408
+ * the reference sits (`place`) and draws its chip, row or card.
398
409
  *
399
410
  * `href` makes it a **URL chip**: an app URL that reads as the chip of what it
400
411
  * names, and is that URL on the wire (§13.3). `uri` is what it names, filled in
@@ -440,25 +451,41 @@ export const ReferenceNode = Node.create<ReferenceNodeOptions>({
440
451
  addNodeView() {
441
452
  const View = this.options.view
442
453
  if (!View) return null
443
- return ReactNodeViewRenderer(({ node, editor, getPos }: ReactNodeViewProps) => {
454
+ return ReactNodeViewRenderer(({ node, editor, getPos, decorations }: ReactNodeViewProps) => {
444
455
  const uri = String(node.attrs.uri ?? '')
445
456
  const href = typeof node.attrs.href === 'string' && node.attrs.href ? node.attrs.href : undefined
457
+ const place = placeOf(decorations)
446
458
  return (
447
459
  <NodeViewWrapper
448
460
  as="span"
449
- className="inline"
461
+ // A row or a card is the whole line.
462
+ className={place === 'chip' ? 'inline' : 'block w-full'}
450
463
  // While editing, a click opens the chip's menu (`ReferenceMenu`) rather than following the chip.
451
464
  onClickCapture={(event: MouseEvent) => {
465
+ // A click in something the view portals out — a picker's list, a hover card — reaches here through React's
466
+ // tree, not the page's: it is that thing's, not a click on the link.
452
467
  const pos = getPos()
453
- if (typeof pos !== 'number' || !referenceMenuClick(editor, pos)) return
468
+ if (typeof pos !== 'number') return
469
+ // (`Node` here is Tiptap's; a click's target is an Element.)
470
+ const own = editor.view.nodeDOM(pos)
471
+ if (!(event.target instanceof Element) || !own || !own.contains(event.target)) return
472
+ // A card's own controls — its status, its owner — change it from the card, while editing too.
473
+ if (place === 'card' && event.target.closest('button, input, select, [role="combobox"]')) return
474
+ if (!referenceMenuClick(editor, pos)) return
454
475
  event.preventDefault()
455
476
  event.stopPropagation()
456
477
  }}
457
478
  >
458
479
  {/* A URL chip not resolved yet reads as the URL it was written as. */}
459
- {uri ? <View uri={uri} {...(href ? { href } : {})} /> : <span>{href}</span>}
480
+ {uri ? <View uri={uri} {...(href ? { href } : {})} place={place} editing={editor.isEditable} /> : <span>{href}</span>}
460
481
  </NodeViewWrapper>
461
482
  )
483
+ }, {
484
+ // Words typed beside a link leave its node as it was, and Tiptap then skips the redraw; its place has changed (code review).
485
+ update: ({ oldNode, newNode, oldDecorations, newDecorations, updateProps }) => {
486
+ if (oldNode !== newNode || placeOf(oldDecorations) !== placeOf(newDecorations)) updateProps()
487
+ return true
488
+ },
462
489
  })
463
490
  },
464
491
  })
@@ -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
+ })