@estiva-app/ui 0.81.0 → 0.82.1

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,28 @@
1
+ import { Extension } from '@tiptap/core';
2
+ /**
3
+ * A URL pasted over words links them, as in Peek, when the message can carry
4
+ * them as a link on words: plain words on one line, no chip, no line break, no
5
+ * bracket, no code. Otherwise the words stay and the URL goes in after them,
6
+ * so neither is lost. Ahead of StarterKit's own link-on-paste.
7
+ */
8
+ export declare const PasteOverWords: Extension<any, any>;
9
+ /** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */
10
+ export declare const BoxKit: Extension<import("@tiptap/starter-kit").StarterKitOptions, any>;
11
+ /**
12
+ * {@link BoxKit} for a document: the same link, which also keeps `extra` —
13
+ * every key a saved link carries that this version does not know — so a save
14
+ * writes it back. ProseMirror drops an attribute its schema does not name, and
15
+ * the key with it. Protocol's `toEditorDocument(doc, { links: true })` fills it.
16
+ */
17
+ export declare const DocumentKit: Extension<import("@tiptap/starter-kit").StarterKitOptions, any>;
18
+ /** A link's look in an editor: the package `Link variant="text"`, spelled out for a mark's element and a decoration's range. */
19
+ export declare const LINK_CLASS = "text-info-default underline underline-offset-2 cursor-pointer";
20
+ /** How a link mark is drawn in a document: the link look, a mark {@link BareLinks} recognises, and a new tab that cannot reach this one. */
21
+ export declare const LINK_MARK_ATTRIBUTES: {
22
+ class: string;
23
+ 'data-link-mark': string;
24
+ target: string;
25
+ rel: string;
26
+ };
27
+ export declare const BareLinks: Extension<any, any>;
28
+ //# sourceMappingURL=links.d.ts.map
@@ -0,0 +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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/ui",
3
- "version": "0.81.0",
3
+ "version": "0.82.1",
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",
@@ -93,6 +93,7 @@
93
93
  "@tiptap/react": "^3.22.1",
94
94
  "@tiptap/suggestion": "^3.22.1",
95
95
  "@tiptap/extension-code-block-lowlight": "^3.22.1",
96
+ "@tiptap/extension-table": "^3.22.1",
96
97
  "@tiptap/starter-kit": "^3.22.1"
97
98
  },
98
99
  "peerDependenciesMeta": {
@@ -123,12 +124,17 @@
123
124
  "@tiptap/extension-code-block-lowlight": {
124
125
  "optional": true
125
126
  },
127
+ "@tiptap/extension-table": {
128
+ "optional": true
129
+ },
126
130
  "@tiptap/starter-kit": {
127
131
  "optional": true
128
132
  }
129
133
  },
130
134
  "devDependencies": {
131
135
  "@eslint/js": "^10.0.1",
136
+ "@estiva-app/conversation": "^0.17.0",
137
+ "@estiva-app/protocol": "^0.41.0",
132
138
  "@storybook/addon-a11y": "^10.6.0",
133
139
  "@storybook/addon-docs": "^10.5.10",
134
140
  "@storybook/addon-vitest": "^10.6.0",
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.81.0",
8
- "exports": 204,
9
- "typeExports": 200,
7
+ "packageVersion": "0.82.1",
8
+ "exports": 206,
9
+ "typeExports": 206,
10
10
  "files": null
11
11
  },
12
12
  "storybook": {
@@ -2124,7 +2124,7 @@
2124
2124
  "kind": "helper",
2125
2125
  "importPath": "@estiva-app/ui/editor",
2126
2126
  "sourceFile": "src/CommentBox.tsx",
2127
- "purpose": "The `/` Insert rows the kit offers. Pass the ones an app can perform, in its order, with its own after them; an edit drops File and Urgent itself.",
2127
+ "purpose": "The `/` Insert rows the kit offers. Pass the ones an app can perform, in its order, with its own after them; an edit drops Upload and Urgent itself.",
2128
2128
  "purposeFrom": "comment",
2129
2129
  "props": [],
2130
2130
  "variants": [],
@@ -2733,6 +2733,176 @@
2733
2733
  "app": null,
2734
2734
  "looks": []
2735
2735
  },
2736
+ {
2737
+ "name": "DocumentEditor",
2738
+ "repo": "estiva-ui",
2739
+ "kind": "component",
2740
+ "importPath": "@estiva-app/ui/editor",
2741
+ "sourceFile": "src/DocumentEditor.tsx",
2742
+ "purpose": "One document's text as one surface that is always an editor, the same in every app: `/`, `[` and `@`, links on words, files, checklists, callouts and tables, the block handle, saving when you leave, someone else's save arriving, and the text held when the sign-in ends.",
2743
+ "purposeFrom": "page",
2744
+ "props": [
2745
+ {
2746
+ "name": "value",
2747
+ "takes": "text",
2748
+ "required": true,
2749
+ "note": "The saved text. A new value while the editor is open is somebody else's save, or your own coming back."
2750
+ },
2751
+ {
2752
+ "name": "format",
2753
+ "takes": "text",
2754
+ "required": true,
2755
+ "note": "The format `value` is in, handed to `codec.read`."
2756
+ },
2757
+ {
2758
+ "name": "codec",
2759
+ "takes": "DocumentCodec",
2760
+ "required": true,
2761
+ "note": null
2762
+ },
2763
+ {
2764
+ "name": "onCommit",
2765
+ "takes": "a handler",
2766
+ "required": true,
2767
+ "note": "Save. Called when you leave, never while typing, with the text, its format, and the saved text this edit started from — so the app can tell whom the save names anew."
2768
+ },
2769
+ {
2770
+ "name": "label",
2771
+ "takes": "text",
2772
+ "required": true,
2773
+ "note": "The editor's accessible name."
2774
+ },
2775
+ {
2776
+ "name": "placeholder",
2777
+ "takes": "anything",
2778
+ "required": false,
2779
+ "note": "Muted words over an empty editor."
2780
+ },
2781
+ {
2782
+ "name": "readOnly",
2783
+ "takes": "true/false",
2784
+ "required": false,
2785
+ "note": "For reading: nothing is typed or saved; chips open, and comments on a selection work when on."
2786
+ },
2787
+ {
2788
+ "name": "changedBy",
2789
+ "takes": "{ name: string } | null",
2790
+ "required": false,
2791
+ "note": "Who saved the text last, when it was not you: named in \"… saved a newer version\"."
2792
+ },
2793
+ {
2794
+ "name": "onLeftUnsaved",
2795
+ "takes": "a handler",
2796
+ "required": false,
2797
+ "note": "A save refused after the editor closed, with nothing left on screen to say it."
2798
+ },
2799
+ {
2800
+ "name": "hold",
2801
+ "takes": "HeldTyping",
2802
+ "required": false,
2803
+ "note": "Where text typed when the sign-in ends is held, under `holdKey`."
2804
+ },
2805
+ {
2806
+ "name": "holdKey",
2807
+ "takes": "text",
2808
+ "required": false,
2809
+ "note": null
2810
+ },
2811
+ {
2812
+ "name": "references",
2813
+ "takes": "DocumentReferences",
2814
+ "required": false,
2815
+ "note": "`[` and `/` → File."
2816
+ },
2817
+ {
2818
+ "name": "mentions",
2819
+ "takes": "DocumentMentions",
2820
+ "required": false,
2821
+ "note": "`@` and `/` → Mention."
2822
+ },
2823
+ {
2824
+ "name": "linkChips",
2825
+ "takes": "LinkChipsOptions",
2826
+ "required": false,
2827
+ "note": "A pasted app URL drawn as the chip of what it names (`LinkChips`)."
2828
+ },
2829
+ {
2830
+ "name": "upload",
2831
+ "takes": "a handler",
2832
+ "required": false,
2833
+ "note": "`/` → Upload, and a pasted picture: upload one file and answer the attachment's attributes (its `imeta` fields)."
2834
+ },
2835
+ {
2836
+ "name": "readMarkdown",
2837
+ "takes": "a handler",
2838
+ "required": false,
2839
+ "note": "Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document."
2840
+ },
2841
+ {
2842
+ "name": "table",
2843
+ "takes": "true/false",
2844
+ "required": false,
2845
+ "note": "`/` → Table. Default on."
2846
+ },
2847
+ {
2848
+ "name": "onCommentOnSelection",
2849
+ "takes": "a handler",
2850
+ "required": false,
2851
+ "note": "Comment on what is selected: the selection strip's Comment, and the comment highlights."
2852
+ },
2853
+ {
2854
+ "name": "blockRows",
2855
+ "takes": "a handler",
2856
+ "required": false,
2857
+ "note": "The app's rows in a block's handle menu, after the editing ones: Copy link, Comment."
2858
+ },
2859
+ {
2860
+ "name": "referenceView",
2861
+ "takes": "ComponentType<ReferenceViewProps>",
2862
+ "required": false,
2863
+ "note": "Draws a chip: the app's own, which resolves what it names."
2864
+ },
2865
+ {
2866
+ "name": "attachmentView",
2867
+ "takes": "ComponentType<AttachmentViewProps>",
2868
+ "required": false,
2869
+ "note": "Draws a placed file: the app's own card."
2870
+ },
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
+ {
2878
+ "name": "wrap",
2879
+ "takes": "a handler",
2880
+ "required": false,
2881
+ "note": "Around everything the editor draws: the app's providers, which may read the editor."
2882
+ },
2883
+ {
2884
+ "name": "onEditor",
2885
+ "takes": "a handler",
2886
+ "required": false,
2887
+ "note": "The editor, once it is there, and `null` as it goes."
2888
+ },
2889
+ {
2890
+ "name": "extensions",
2891
+ "takes": "readonly AnyExtension[]",
2892
+ "required": false,
2893
+ "note": "More of the app's own extensions."
2894
+ }
2895
+ ],
2896
+ "variants": [],
2897
+ "ownsBehaviours": [],
2898
+ "status": "stable",
2899
+ "migrationStage": null,
2900
+ "docsId": "primitives-documenteditor--docs",
2901
+ "storyId": "primitives-documenteditor--with-comments",
2902
+ "docPage": "src/DocumentEditor.mdx",
2903
+ "app": null,
2904
+ "looks": []
2905
+ },
2736
2906
  {
2737
2907
  "name": "duplicateBlock",
2738
2908
  "repo": "estiva-ui",
@@ -6194,6 +6364,25 @@
6194
6364
  "app": null,
6195
6365
  "looks": []
6196
6366
  },
6367
+ {
6368
+ "name": "PersonReference",
6369
+ "repo": "estiva-ui",
6370
+ "kind": "component",
6371
+ "importPath": "@estiva-app/ui/editor",
6372
+ "sourceFile": "src/ComposerTriggers.tsx",
6373
+ "purpose": "`@` in a document — a person, written as a reference to them: a `ReferenceNode` whose `uri` is their `nostr:npub…` (SPEC §13.1, §13.3).",
6374
+ "purposeFrom": "comment",
6375
+ "props": [],
6376
+ "variants": [],
6377
+ "ownsBehaviours": [],
6378
+ "status": "stable",
6379
+ "migrationStage": null,
6380
+ "docsId": "primitives-composertriggers--docs",
6381
+ "storyId": "primitives-composertriggers--default",
6382
+ "docPage": null,
6383
+ "app": null,
6384
+ "looks": []
6385
+ },
6197
6386
  {
6198
6387
  "name": "PersonTrigger",
6199
6388
  "repo": "estiva-ui",
@@ -429,7 +429,9 @@ export const ReferenceNode = Node.create<ReferenceNodeOptions>({
429
429
  // A copy to the clipboard as HTML, and the whole drawing when no view is given.
430
430
  // The card goes along, so a paste keeps it; a URL chip copies as its URL.
431
431
  const embed = typeof node.attrs.embed === 'string' ? { 'data-embed': node.attrs.embed } : {}
432
- const href = typeof node.attrs.href === 'string' && node.attrs.href ? { 'data-href': node.attrs.href } : {}
432
+ // Only a web address: the document's `href` is whatever its writer saved, and this attribute is read back by a paste.
433
+ const web = webUrl(typeof node.attrs.href === 'string' ? node.attrs.href : null)
434
+ const href = web ? { 'data-href': web } : {}
433
435
  return ['span', { 'data-reference': String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)]
434
436
  },
435
437
  renderText({ node }) {
@@ -14,7 +14,7 @@ The one box every app writes a comment, a reply and a line of a conversation in:
14
14
  - **Writing anything that is sent**, in every app: a comment, a reply, a line in a conversation. The same box writes all of them.
15
15
  - `showsAtOnce` when the app shows a send before the relay answers: the box empties at once, and a refusal puts the words back. Without it the box holds the words, shut, until the answer.
16
16
  - `edit` to change something already sent: the same box with Cancel and Save, and only its keys on the left.
17
- - `upload` to offer files: the paperclip, `/` → File, a pasted picture and a dropped file.
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
20
 
@@ -56,7 +56,7 @@ const draft = composerDraft(createDraftStore(localStorage), draftKeys.thread(roo
56
56
  - **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.
57
57
  - **`send` answers.** Resolve `{ accepted: false, reason }` and the words come back with "Not sent: *reason*". A thrown send is a refusal too.
58
58
  - **`label` is required**: the editor's accessible name.
59
- - **`insert` is the app's Insert rows**, after the shared Format section: `commentBoxRows` and the app's own. An edit drops File and Urgent itself; with no `upload` there is no File.
59
+ - **`insert` is the app's Insert rows**, after the shared Format section: `commentBoxRows` and the app's own. An edit drops Upload and Urgent itself; with no `upload` there is no Upload (`commentBoxRows.file` is that row).
60
60
  - **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.
61
61
  - A send shown at once and refused after its box went away writes the words into its draft instead.
62
62
  - **`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`).
@@ -177,12 +177,12 @@ describe('editing', () => {
177
177
  expect(editorOf().getText()).toBe('Said before')
178
178
  })
179
179
 
180
- it('/ offers no File and no Urgent in an edit', async () => {
180
+ it('/ offers no Upload and no Urgent in an edit', async () => {
181
181
  render(<Box upload={async () => ({ accepted: true, value: 1 })} edit={{ body, onSave: async () => ({ accepted: true }), onCancel: () => {} }} />)
182
182
  await type(' /')
183
183
  const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
184
184
  expect(rows.some((r) => r.startsWith('Mention'))).toBe(true)
185
- expect(rows.some((r) => r.startsWith('File') || r.startsWith('Urgent'))).toBe(false)
185
+ expect(rows.some((r) => r.startsWith('Upload') || r.startsWith('Urgent'))).toBe(false)
186
186
  // Closed here: the editor is destroyed on a timer, and a list it closes then would hold the next test's Enter.
187
187
  await press('Escape')
188
188
  })
@@ -251,21 +251,22 @@ describe('files', () => {
251
251
  expect(send.mock.calls[0][1]).toEqual([])
252
252
  })
253
253
 
254
- it('an upload that arrives after the box opened offers File in /', async () => {
254
+ it('an upload that arrives after the box opened offers Upload in /', async () => {
255
255
  const { rerender } = render(<Box />)
256
256
  rerender(<Box upload={async () => ({ accepted: true, value: 1 })} />)
257
257
  await type('/')
258
258
  const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
259
- expect(rows.some((r) => r.startsWith('File'))).toBe(true)
259
+ expect(rows.some((r) => r.startsWith('Upload'))).toBe(true)
260
+ expect(rows.some((r) => r.startsWith('File'))).toBe(false)
260
261
  await press('Escape')
261
262
  })
262
263
 
263
- it('no upload: no paperclip and no File row', async () => {
264
+ it('no upload: no paperclip and no Upload row', async () => {
264
265
  render(<Box />)
265
266
  expect(screen.queryByRole('button', { name: 'Attach a file' })).toBeNull()
266
267
  await type('/')
267
268
  const rows = within(screen.getByRole('listbox')).getAllByRole('option').map((o) => o.textContent ?? '')
268
- expect(rows.some((r) => r.startsWith('File'))).toBe(false)
269
+ expect(rows.some((r) => r.startsWith('Upload'))).toBe(false)
269
270
  await press('Escape')
270
271
  })
271
272
  })
@@ -1,8 +1,6 @@
1
1
  import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'
2
2
  import { Extension, type AnyExtension } from '@tiptap/core'
3
- import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
4
3
  import { EditorContent, useEditor, type Editor, type JSONContent } from '@tiptap/react'
5
- import StarterKit from '@tiptap/starter-kit'
6
4
  import { IconLock, IconPaperclip, IconSquareRounded } from '@tabler/icons-react'
7
5
  import { AttachmentCard } from './AttachmentCard'
8
6
  import { ReferenceNode, type ReferenceViewProps } from './BlockNodes'
@@ -28,6 +26,7 @@ import {
28
26
  import { FieldLine } from './Field'
29
27
  import { FilePicker } from './FilePicker'
30
28
  import { Kbd } from './Kbd'
29
+ import { BoxKit, PasteOverWords } from './links'
31
30
  import { WRITING_BOX_CLASSES } from './looks'
32
31
  import { PastedImages } from './PastedImages'
33
32
  import { KeptSelection } from './SelectionToolbar'
@@ -174,10 +173,11 @@ const askForFile = (editor: Editor) => editor.view.dom.dispatchEvent(new CustomE
174
173
 
175
174
  /**
176
175
  * The `/` Insert rows the kit offers. Pass the ones an app can perform, in
177
- * its order, with its own after them; an edit drops File and Urgent itself.
176
+ * its order, with its own after them; an edit drops Upload and Urgent itself.
177
+ * `file` is the Upload row, named as in a document's `/`.
178
178
  */
179
179
  export const commentBoxRows: Readonly<Record<'file' | 'mention' | 'urgent' | 'reference', SlashCommand>> = {
180
- file: { key: 'insert-file', row: { label: 'File' }, keywords: ['attach', 'upload'], run: askForFile },
180
+ file: { key: 'insert-file', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: askForFile },
181
181
  mention: { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'Mention a person'], run: typeTrigger('@') },
182
182
  urgent: { key: 'insert-urgent', row: { label: 'Urgent', shortcut: '!@' }, keywords: ['!@', 'Urgent mention'], run: typeTrigger('!@') },
183
183
  reference: { key: 'insert-reference', row: { label: 'Reference', shortcut: '[' }, keywords: ['[', 'Reference'], run: typeTrigger('[') },
@@ -198,60 +198,6 @@ const BoxKeys = Extension.create<{ onEscape: () => boolean }>({
198
198
  },
199
199
  })
200
200
 
201
- /** A link a message can carry on words, `[words](url)`: no `)` and no space in it (conversation's `composerText`). */
202
- const LINK_ON_WORDS_TARGET = /^https?:\/\/[^\s)]+$/
203
-
204
- /**
205
- * A URL pasted over words links them, as in Peek, when the message can carry
206
- * them as a link on words: plain words on one line, no chip, no line break, no
207
- * bracket, no code. Otherwise the words stay and the URL goes in after them,
208
- * so neither is lost. Ahead of StarterKit's own link-on-paste.
209
- */
210
- const PasteOverWords = Extension.create({
211
- name: 'commentBoxPasteOverWords',
212
- priority: 1001,
213
- addProseMirrorPlugins() {
214
- return [
215
- new Plugin({
216
- key: new PluginKey('commentBoxPasteOverWords'),
217
- props: {
218
- handlePaste: (view, event) => {
219
- // A URL copied with the end of its sentence names what it names without it, as LinkChips reads one.
220
- const url = (event.clipboardData?.getData('text/plain').trim() ?? '').replace(/[.,;:!?]+$/, '')
221
- const { state } = view
222
- const { schema } = state
223
- if (state.selection.empty || !schema.marks.link || !/^https?:\/\/\S+$/.test(url)) return false
224
- // Select-all spans the document itself: read it as the text it holds.
225
- const { $from, $to, from, to } = TextSelection.between(state.selection.$from, state.selection.$to)
226
- let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code
227
- state.doc.nodesBetween(from, to, (node) => {
228
- if (node.isTextblock) return true
229
- if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) plain = false
230
- return false
231
- })
232
- if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
233
- view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })))
234
- return true
235
- }
236
- const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '')
237
- const inserted = before && !/\s/.test(before) ? ` ${url}` : url
238
- const tr = state.tr.insertText(inserted, to)
239
- view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to + inserted.length)).scrollIntoView())
240
- return true
241
- },
242
- },
243
- }),
244
- ]
245
- },
246
- })
247
-
248
- /** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */
249
- const BoxKit = StarterKit.extend({
250
- addExtensions() {
251
- return (this.parent?.() ?? []).map((extension) => (extension.name === 'link' ? extension.extend({ inclusive: () => false }) : extension))
252
- },
253
- })
254
-
255
201
  /** What `removed` still holds of what the draft names; the same set when nothing was forgotten. */
256
202
  const stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): ReadonlySet<string> =>
257
203
  [...removed].every((value) => names.includes(value)) ? removed : new Set([...removed].filter((value) => names.includes(value)))
@@ -216,6 +216,71 @@ export function urgentPubkeys(editor: { state: { doc: Doc } }): string[] | undef
216
216
  return urgent.length > 0 ? urgent : undefined
217
217
  }
218
218
 
219
+ export interface PersonReferenceOptions {
220
+ /** Everyone `@` can offer, asked each time the query changes. */
221
+ people: () => readonly MentionPerson[]
222
+ /** The `nostr:npub…` a person is written as; `null` for someone without one, who is not offered. */
223
+ uriOf: (person: MentionPerson) => string | null
224
+ /** The node a pick inserts. Default `reference`, `ReferenceNode`'s. */
225
+ nodeName: string
226
+ }
227
+
228
+ /**
229
+ * `@` in a document — a person, written as a reference to them: a
230
+ * `ReferenceNode` whose `uri` is their `nostr:npub…` (SPEC §13.1, §13.3). Not
231
+ * {@link PersonMention}'s chip, which is a message's: a document names people
232
+ * the way it names anything else, and a save that newly names someone is what
233
+ * adds them (`@estiva-app/conversation`'s `mentionAddsFor`, which reads only
234
+ * that uri).
235
+ *
236
+ * PersonReference.configure({ people: () => directory, uriOf: (person) => npubUri(person.pubkey) })
237
+ *
238
+ * The chip carries no name: the app's `ReferenceNode` view resolves the uri,
239
+ * so a rename shows everywhere the person is named.
240
+ *
241
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-mention-in-a-files-text-adds-the-person-with-no-unread.md
242
+ */
243
+ export const PersonReference = Extension.create<PersonReferenceOptions>({
244
+ name: 'personReference',
245
+ addOptions() {
246
+ return { people: () => [], uriOf: () => null, nodeName: 'reference' }
247
+ },
248
+ addProseMirrorPlugins() {
249
+ const options = this.options
250
+ return [
251
+ Suggestion<MentionPerson>({
252
+ editor: this.editor,
253
+ char: '@',
254
+ pluginKey: new PluginKey('personReference'),
255
+ ...listening('@'),
256
+ // As `[`'s: only where the chip may go.
257
+ allow: ({ state, range }) => {
258
+ const type = state.schema.nodes[options.nodeName]
259
+ return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type)
260
+ },
261
+ items: ({ query }) =>
262
+ filterPeople(
263
+ options.people().filter((person) => options.uriOf(person) !== null),
264
+ query,
265
+ ),
266
+ render: suggestionPopup(peopleMenu(false)),
267
+ command: ({ editor, range, props: person }) => {
268
+ const uri = options.uriOf(person)
269
+ if (!uri) return
270
+ editor
271
+ .chain()
272
+ .focus()
273
+ .insertContentAt(range, [
274
+ { type: options.nodeName, attrs: { uri } },
275
+ { type: 'text', text: ' ' },
276
+ ])
277
+ .run()
278
+ },
279
+ }),
280
+ ]
281
+ },
282
+ })
283
+
219
284
  // ─── [ ───
220
285
 
221
286
  /** Something `[` offers: a reference drawn as who said it and how it opens. */
@@ -0,0 +1,106 @@
1
+ import { Meta, Canvas, Controls } from '@storybook/addon-docs/blocks'
2
+ import * as DocumentEditorStories from './DocumentEditor.stories'
3
+
4
+ <Meta of={DocumentEditorStories} />
5
+
6
+ # DocumentEditor
7
+
8
+ One document's text as one surface that is always an editor, the same in every app: `/`, `[` and `@`, links on words, files, checklists, callouts and tables, the block handle, saving when you leave, someone else's save arriving, and the text held when the sign-in ends. The app supplies the translation of its saved text, its lists, its upload and its views of a chip and a file.
9
+
10
+ <Canvas of={DocumentEditorStories.WithComments} />
11
+
12
+ ## When
13
+
14
+ - **Any document's text**, written where it is read: a page, a description, a panel. The same editor in every app.
15
+ - `references` and `mentions` for `[` and `@`, from the app's own lists. Without them, `[` and `@` are text.
16
+ - `upload` for `/` → Upload and a pasted picture, uploaded before the file is placed.
17
+ - `onCommentOnSelection` to offer Comment on what is selected, and draw where comments are. Without it, neither.
18
+ - `blockRows` for the app's rows in a block's menu: Copy link, Comment on the block.
19
+ - `readOnly` for reading: the same drawing, nothing typed or saved. Chips open, and Comment on a selection stays where it is on.
20
+
21
+ <Canvas of={DocumentEditorStories.WithFiles} />
22
+
23
+ <Canvas of={DocumentEditorStories.ReadOnly} />
24
+
25
+ ## When not
26
+
27
+ - Something sent, a comment or a line in a conversation → **CommentBox**. Nothing is sent from here; it saves.
28
+ - One line, a title or the line under it → **InlineText**.
29
+ - Text in a form → **TextInput** or **Textarea**.
30
+
31
+ ## How
32
+
33
+ ```tsx
34
+ import { DocumentEditor, type DocumentCodec } from '@estiva-app/ui/editor'
35
+ import { documentForEditing, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
36
+ import { mentionAddsFor } from '@estiva-app/conversation'
37
+
38
+ const codec: DocumentCodec = {
39
+ read: (value, format) => toEditorDocument(documentForEditing(value, format as ContentFormat), { links: true }),
40
+ write: (doc) => publishableFromEditor(doc as EditorDocument),
41
+ }
42
+
43
+ <DocumentEditor
44
+ key={address}
45
+ value={text}
46
+ format={format}
47
+ codec={codec}
48
+ label="Document"
49
+ placeholder="Type / for headings and lists."
50
+ changedBy={lastEditor}
51
+ hold={heldTyping}
52
+ holdKey={address}
53
+ references={{ sections: sectionsFor, ariaLabel: 'Items', sectionLabel: 'Items' }}
54
+ mentions={{ people: () => people, uriOf: (person) => `nostr:${encodeNpub(person.pubkey)}` }}
55
+ upload={uploadOne}
56
+ referenceView={chipView}
57
+ attachmentView={fileView}
58
+ onCommit={async (value, contentFormat, editedFrom) => {
59
+ const adds = mentionAddsFor(me, Date.now(), {
60
+ file: address,
61
+ folder: folderId,
62
+ saved: { content: value, format: contentFormat },
63
+ editedFrom: { content: editedFrom, format: savedFormatTag },
64
+ })
65
+ return save(value, contentFormat, adds)
66
+ }}
67
+ />
68
+ ```
69
+
70
+ - **It speaks the editor's document.** The package does not depend on `@estiva-app/protocol`: the app hands it `codec`, which reads its saved text and writes the editor's document back. Pass `{ links: true }`, or a link on words is lost at the next save.
71
+ - **`onCommit` answers whether it was saved**, and gets the saved text the edit started from: whom a save names anew is the difference between the two (`mentionAddsFor`). A refused or thrown save keeps the text and says so.
72
+ - **`@` writes a reference to the person**, a chip whose `uri` is their `nostr:npub…`, not a message's mention. `uriOf` answers it; someone without one is not offered. The chip carries no name: `referenceView` resolves it.
73
+ - **`label` is required**: the editor's accessible name.
74
+ - **Give the editor a `key` per document.** The editor and which of `[`, `@`, File, comments and markdown it has are made once, as it opens; the lists, the upload and the people are read as they are each time.
75
+ - **`hold` is the app's held-typing store.** `register` must not forget what is held when it is called again for the same key during an ending; the editor registers once per `holdKey`.
76
+ - **The cards a chip asks for** are drawn by the app's `cards`, after the text, until the kit has its own.
77
+
78
+ ## What it owns
79
+
80
+ It does these by itself. Write none of them around it.
81
+
82
+ | It does | So you never write |
83
+ |---|---|
84
+ | Saving on blur, on unmount and on a checklist tick; never while typing; Escape leaves | a save button, a timer, a key handler |
85
+ | A refused save: the text kept, and "Could not save. Your text is still here." | a toast, or putting text back |
86
+ | Someone else's save: loaded while you are not in it; while you are, "*Name* saved a newer version. Load it (replaces your changes)", and leaving saves yours over theirs — the later save wins | a merge, a conflict dialog |
87
+ | Your own save coming back is not someone else's | an echo filter |
88
+ | The text held when the sign-in ends, back unsaved after the tap, and nothing saved on the way out | a draft |
89
+ | `/` Format (with checklist, note and warning) and Insert: Table, File (opens `[`), Upload, Mention (opens `@`) | the `/` rows |
90
+ | A URL pasted over plain words links them; typing after linked words is not linked; a link keeps the keys this version does not know | a paste handler, a link schema |
91
+ | A bare address drawn as a link, opened by a click, and saved as the text it is | a link decoration |
92
+ | Each block's id through editing, so what is anchored to it stays on it | an id plugin |
93
+ | A pasted picture uploaded and placed; the file dialog's blur is not leaving | an upload state |
94
+ | Read only: no caret, no `/`, `[` or `@`, no format buttons; still focusable, so a selection's Comment shows | a reading view |
95
+
96
+ ## Keys
97
+
98
+ | Key | What it does |
99
+ |---|---|
100
+ | Escape | Lets go of selected words; with nothing selected, leaves the editor, which saves. With a list or a chip's menu open, closes it first. |
101
+ | Enter | With a list open, picks the row. |
102
+ | `/` | Opens Format and Insert. |
103
+ | `[` | Opens the app's list, when it passed one. |
104
+ | `@` | Opens the app's people, when it passed them. |
105
+
106
+ <Controls />