@estiva-app/ui 0.81.0 → 0.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite'
2
+ import { useEffect, useRef, useState } from 'react'
3
+ import type { Editor } from '@tiptap/react'
4
+ import type { JSONContent } from '@tiptap/react'
5
+ import { IconSquareRounded } from '@tabler/icons-react'
6
+ import { descriptionTextToBlockDocument, documentForEditing, encodeNpub, publishableFromEditor, toEditorDocument, type ContentFormat, type EditorDocument } from '@estiva-app/protocol'
7
+ import { newlyNamedPeople } from '@estiva-app/conversation'
8
+ import { AttachmentCard } from './AttachmentCard'
9
+ import type { HandleBlock } from './BlockHandle'
10
+ import type { AttachmentViewProps, ReferenceViewProps } from './BlockNodes'
11
+ import { Button } from './Button'
12
+ import { setCommentAnchors, type CommentAnchor, type SelectionAnchor } from './CommentHighlights'
13
+ import type { CaptionedItem, MentionPerson, ReferenceSection } from './ComposerTriggers'
14
+ import { DocumentEditor, type DocumentCodec, type DocumentEditorProps, type HeldTyping } from './DocumentEditor'
15
+ import { InlineChip } from './InlineChip'
16
+ import { MenuItem } from './Menu'
17
+
18
+ /**
19
+ * One document's text, always an editor. Every story is live: type, open `/`,
20
+ * `[` or `@`, click away to save. The panel under the editor is the app's
21
+ * side: what was saved, whom the save would add, and buttons for what happens
22
+ * to a document from outside — someone else's save, a reload, the sign-in
23
+ * ending. Pick the theme in the toolbar.
24
+ */
25
+ const meta = {
26
+ title: 'Primitives/DocumentEditor',
27
+ component: DocumentEditor,
28
+ parameters: { layout: 'padded' },
29
+ } satisfies Meta<typeof DocumentEditor>
30
+
31
+ export default meta
32
+ type Story = StoryObj
33
+
34
+ // ─── The app's side, played by @estiva-app/protocol and @estiva-app/conversation ───
35
+
36
+ const codec: DocumentCodec = {
37
+ read: (value, format) => toEditorDocument(documentForEditing(value, format as ContentFormat), { links: true }) as JSONContent,
38
+ write: (doc) => publishableFromEditor(doc as EditorDocument),
39
+ }
40
+ const readMarkdown = (text: string) => toEditorDocument(descriptionTextToBlockDocument(text)) as JSONContent
41
+ const FORMAT_TAG = 'estiva-blocks-1'
42
+
43
+ const PEOPLE: MentionPerson[] = ['one', 'two', 'three'].map((n, i) => ({ id: n, name: `Person ${n}`, pubkey: String.fromCharCode(98 + i).repeat(64) }))
44
+ const npubOf = (person: MentionPerson) => (person.pubkey ? `nostr:${encodeNpub(person.pubkey)}` : null)
45
+ const nameOfKey = (key: string) => PEOPLE.find((person) => person.pubkey === key)?.name ?? 'Someone'
46
+
47
+ const APP_LINK = 'https://app.example/item/one'
48
+ const ITEMS: CaptionedItem[] = ['one', 'two', 'three'].map((n) => ({ id: `item-${n}`, label: `Item ${n}`, snippet: '', uri: `nostr:naddr1item${n}` }))
49
+ const sections = (query: string): ReferenceSection[] => [{ label: 'Items', items: ITEMS.filter((item) => item.label.toLowerCase().includes(query.toLowerCase())) }]
50
+ const linkChips = { referenceOf: (url: string) => (url === APP_LINK ? ITEMS[0].uri : undefined), ask: null, limit: 24 }
51
+
52
+ const SQUARE = <IconSquareRounded size={14} stroke={1.5} />
53
+ const ROW_ICON = <IconSquareRounded size={16} stroke={1.5} className="text-text-secondary" />
54
+
55
+ /** A chip as the app draws it: a person by name, an item by its label; it opens where it leads. */
56
+ function Chip({ uri, href }: ReferenceViewProps) {
57
+ const person = PEOPLE.find((one) => npubOf(one) === uri)
58
+ if (person) return <InlineChip tone="person">{`@${person.name}`}</InlineChip>
59
+ const item = ITEMS.find((one) => one.uri === uri)
60
+ return (
61
+ <InlineChip icon={SQUARE} href={href ?? 'https://example.com/item'} target="_blank" rel="noreferrer">
62
+ {item?.label ?? 'Item'}
63
+ </InlineChip>
64
+ )
65
+ }
66
+
67
+ function PlacedFile({ attrs }: AttachmentViewProps) {
68
+ return <AttachmentCard name={String(attrs.filename ?? 'file')} size={Number(attrs.size) || undefined} contentType={String(attrs.m ?? '')} src={String(attrs.url ?? '') || undefined} />
69
+ }
70
+
71
+ /** An upload that answers after a moment with the file's attributes; the picture is drawn from this page. */
72
+ const upload = (file: File): Promise<Record<string, unknown>> =>
73
+ new Promise((resolve) => setTimeout(() => resolve({ url: URL.createObjectURL(file), m: file.type, x: '0'.repeat(64), size: file.size, filename: file.name }), 600))
74
+
75
+ const START = JSON.stringify({
76
+ type: 'doc',
77
+ content: [
78
+ { type: 'heading', id: 'b1', attrs: { level: 1 }, content: [{ type: 'text', text: 'Label' }] },
79
+ {
80
+ type: 'paragraph',
81
+ id: 'b2',
82
+ content: [
83
+ { type: 'text', text: 'Type / for formats, [ to link ' },
84
+ { type: 'text', text: 'Item one', marks: [{ type: 'reference', attrs: { uri: ITEMS[0].uri } }] },
85
+ { type: 'text', text: ', @ to name a person. Words can carry ' },
86
+ { type: 'text', text: 'a link', marks: [{ type: 'link', attrs: { href: 'https://example.com' } }] },
87
+ { type: 'text', text: '.' },
88
+ ],
89
+ },
90
+ {
91
+ type: 'bulletList',
92
+ id: 'b3',
93
+ content: [
94
+ { type: 'listItem', id: 'b4', attrs: { checked: true }, content: [{ type: 'text', text: 'Item one' }] },
95
+ { type: 'listItem', id: 'b5', attrs: { checked: false }, content: [{ type: 'text', text: 'Item two' }] },
96
+ ],
97
+ },
98
+ { type: 'blockquote', id: 'b6', attrs: { tone: 'note' }, content: [{ type: 'text', text: 'A note, kept with its tone.' }] },
99
+ ],
100
+ })
101
+
102
+ /** An app's held-typing store: what each open editor holds is read when the sign-in ends. */
103
+ function heldStore() {
104
+ const held = new Map<string, string>()
105
+ const readers = new Map<string, () => string | undefined>()
106
+ let ending = false
107
+ const hold: HeldTyping = {
108
+ text: (key) => held.get(key),
109
+ release: (key) => void held.delete(key),
110
+ register: (key, read) => {
111
+ readers.set(key, read)
112
+ return () => {
113
+ readers.delete(key)
114
+ if (!ending) held.delete(key)
115
+ }
116
+ },
117
+ ended: () => ending,
118
+ }
119
+ return {
120
+ hold,
121
+ end: () => {
122
+ ending = true
123
+ for (const [key, read] of readers) {
124
+ const text = read()
125
+ if (text) held.set(key, text)
126
+ }
127
+ },
128
+ back: () => {
129
+ ending = false
130
+ },
131
+ }
132
+ }
133
+
134
+ /** The saved text's lines, and each link on words with where it goes. */
135
+ function savedLines(value: string): string[] {
136
+ const lines: string[] = []
137
+ const walk = (node: { text?: string; marks?: { type: string; attrs?: { href?: string } }[]; content?: unknown[] }, line: string[]) => {
138
+ if (node.text !== undefined) {
139
+ const link = node.marks?.find((mark) => mark.type === 'link')
140
+ line.push(link ? `[${node.text}](${link.attrs?.href})` : node.text)
141
+ }
142
+ for (const child of (node.content ?? []) as (typeof node)[]) walk(child, line)
143
+ }
144
+ for (const block of (JSON.parse(value) as { content: { content?: unknown[] }[] }).content) {
145
+ const line: string[] = []
146
+ walk(block, line)
147
+ lines.push(line.join(''))
148
+ }
149
+ return lines
150
+ }
151
+
152
+ type Bench = Pick<DocumentEditorProps, 'readOnly' | 'upload' | 'linkChips' | 'readMarkdown'> & {
153
+ /** The app's `[` and `@`. */
154
+ lists?: boolean
155
+ /** Comments on a selection, as the app switches them on. */
156
+ comments?: boolean
157
+ /** The block handle's rows: Copy link, and Comment on the block. */
158
+ rows?: boolean
159
+ }
160
+
161
+ /** The editor and the app around it. */
162
+ function Workbench({ lists = true, comments = false, rows = false, readOnly = false, ...rest }: Bench) {
163
+ const [value, setValue] = useState(START)
164
+ const [changedBy, setChangedBy] = useState<{ name: string } | null>(null)
165
+ const [opened, setOpened] = useState(0)
166
+ const [signedIn, setSignedIn] = useState(true)
167
+ const [added, setAdded] = useState<string[] | null>(null)
168
+ const [said, setSaid] = useState<string | null>(null)
169
+ const store = useRef(heldStore()).current
170
+
171
+ const onCommit: DocumentEditorProps['onCommit'] = async (next, contentFormat, editedFrom) => {
172
+ setAdded(newlyNamedPeople({ content: next, format: contentFormat }, { content: editedFrom, format: FORMAT_TAG }).map(nameOfKey))
173
+ setValue(next)
174
+ setChangedBy(null)
175
+ return true
176
+ }
177
+ const someoneElse = () => {
178
+ const doc = JSON.parse(value) as { type: 'doc'; content: object[] }
179
+ doc.content.push({ type: 'paragraph', id: `other-${Date.now()}`, content: [{ type: 'text', text: 'A line someone else added.' }] })
180
+ setValue(JSON.stringify(doc))
181
+ setChangedBy({ name: 'Person two' })
182
+ }
183
+ const blockRows = (block: HandleBlock) =>
184
+ block.id ? (
185
+ <>
186
+ <MenuItem label="Copy link" leading={ROW_ICON} onClick={() => setSaid(`Copied the link to block ${block.id}.`)} />
187
+ <MenuItem label="Comment" leading={ROW_ICON} onClick={() => setSaid(`A comment on block ${block.id}.`)} />
188
+ </>
189
+ ) : null
190
+ // Each comment stays drawn on its words, through edits and a reload, by the block ids it was anchored to.
191
+ const [anchors, setAnchors] = useState<CommentAnchor[]>([])
192
+ const [editor, setEditor] = useState<Editor | null>(null)
193
+ useEffect(() => {
194
+ if (editor && !editor.isDestroyed) setCommentAnchors(editor, anchors)
195
+ }, [editor, anchors])
196
+ const onCommentOnSelection = (anchor: SelectionAnchor) => {
197
+ setAnchors((all) => [...all, { id: `comment-${all.length + 1}`, ...anchor }])
198
+ setSaid(`A comment on ${anchor.quote ? `“${anchor.quote.start}${anchor.quote.end ? ` … ${anchor.quote.end}` : ''}”` : `block ${anchor.blocks.join(', ')}`}.`)
199
+ }
200
+
201
+ return (
202
+ <div className="flex max-w-2xl flex-col gap-4 pl-10">
203
+ {signedIn ? (
204
+ <DocumentEditor
205
+ key={opened}
206
+ onEditor={setEditor}
207
+ value={value}
208
+ format="blocks"
209
+ codec={codec}
210
+ onCommit={onCommit}
211
+ label="Document"
212
+ placeholder="Type / for headings and lists."
213
+ readOnly={readOnly}
214
+ changedBy={changedBy}
215
+ hold={store.hold}
216
+ holdKey="document-one"
217
+ referenceView={Chip}
218
+ attachmentView={PlacedFile}
219
+ {...(lists ? { references: { sections, ariaLabel: 'Items', sectionLabel: 'Items' }, mentions: { people: () => PEOPLE, uriOf: npubOf } } : {})}
220
+ {...(comments ? { onCommentOnSelection } : {})}
221
+ {...(rows ? { blockRows } : {})}
222
+ {...rest}
223
+ />
224
+ ) : (
225
+ <p className="text-body-2 text-text-secondary">The sign-in ended. What was typed is kept on this device.</p>
226
+ )}
227
+ <div className="flex flex-col gap-2 rounded-md border border-border-default p-3 text-body-2 text-text-secondary">
228
+ <div className="flex flex-wrap gap-2">
229
+ {!readOnly && (
230
+ // Pressing it keeps you in the editor, so their save arrives while you are typing.
231
+ <Button variant="outlined" size="small" onMouseDown={(event) => event.preventDefault()} onClick={someoneElse}>
232
+ Someone else saves
233
+ </Button>
234
+ )}
235
+ <Button variant="outlined" size="small" onClick={() => setOpened((n) => n + 1)}>
236
+ Reload
237
+ </Button>
238
+ {!readOnly &&
239
+ (signedIn ? (
240
+ <Button
241
+ variant="outlined"
242
+ size="small"
243
+ // An ending comes from outside, with the text still being typed: pressing it must not leave the editor, which saves.
244
+ onMouseDown={(event) => event.preventDefault()}
245
+ onClick={() => {
246
+ store.end()
247
+ setSignedIn(false)
248
+ }}
249
+ >
250
+ End the sign-in
251
+ </Button>
252
+ ) : (
253
+ <Button
254
+ variant="outlined"
255
+ size="small"
256
+ onClick={() => {
257
+ store.back()
258
+ setSignedIn(true)
259
+ }}
260
+ >
261
+ Sign in again
262
+ </Button>
263
+ ))}
264
+ </div>
265
+ {said && <p>{said}</p>}
266
+ {added && <p>{added.length > 0 ? `This save adds ${added.join(', ')}.` : 'This save adds nobody.'}</p>}
267
+ <p className="text-caption">Saved:</p>
268
+ <ul className="flex flex-col gap-1 text-caption">
269
+ {savedLines(value).map((line, at) => (
270
+ <li key={at}>{line || ' '}</li>
271
+ ))}
272
+ </ul>
273
+ </div>
274
+ </div>
275
+ )
276
+ }
277
+
278
+ /** `[`, `/`, `@`, comments on a selection, and the handle's Copy link and Comment. */
279
+ export const WithComments: Story = {
280
+ render: () => <Workbench comments rows linkChips={linkChips} readMarkdown={readMarkdown} />,
281
+ }
282
+
283
+ /**
284
+ * Files: `/` → File and a pasted picture, uploaded first. A pasted app URL
285
+ * (`https://app.example/item/one`) becomes its chip. The handle has Copy link
286
+ * and Comment; a selection has no Comment.
287
+ */
288
+ export const WithFiles: Story = {
289
+ render: () => <Workbench rows upload={upload} linkChips={linkChips} readMarkdown={readMarkdown} />,
290
+ }
291
+
292
+ /** Nothing of the app's but its chips: no `[`, no `@`, no rows, no comments. */
293
+ export const Plain: Story = {
294
+ render: () => <Workbench lists={false} linkChips={linkChips} />,
295
+ }
296
+
297
+ /** For reading: the same drawing, nothing typed or saved. Chips open; a selection still has Comment. */
298
+ export const ReadOnly: Story = {
299
+ render: () => <Workbench readOnly comments rows />,
300
+ }
301
+
302
+ /** Read only where the app has comments off: a selection has no strip at all. */
303
+ export const ReadOnlyWithoutComments: Story = {
304
+ render: () => <Workbench readOnly />,
305
+ }