@estiva-app/ui 0.82.0 → 0.83.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BlockNodes.d.ts +16 -5
- package/dist/BlockNodes.d.ts.map +1 -1
- package/dist/CommentBox.d.ts +2 -1
- package/dist/CommentBox.d.ts.map +1 -1
- package/dist/DocumentEditor.d.ts +8 -7
- package/dist/DocumentEditor.d.ts.map +1 -1
- package/dist/LinkPlaces.d.ts +51 -0
- package/dist/LinkPlaces.d.ts.map +1 -0
- package/dist/ReferenceMenu.d.ts.map +1 -1
- package/dist/editor.d.ts +1 -0
- package/dist/editor.d.ts.map +1 -1
- package/dist/editor.js +260 -128
- package/dist/editor.js.map +4 -4
- package/dist/linked.examples.d.ts.map +1 -1
- package/package.json +1 -1
- package/registry.json +66 -15
- package/src/BlockNodes.tsx +36 -9
- package/src/CommentBox.mdx +2 -2
- package/src/CommentBox.test.tsx +7 -6
- package/src/CommentBox.tsx +3 -2
- package/src/DocumentEditor.mdx +9 -4
- package/src/DocumentEditor.stories.tsx +101 -15
- package/src/DocumentEditor.test.tsx +76 -11
- package/src/DocumentEditor.tsx +29 -19
- package/src/LinkPlaces.mdx +59 -0
- package/src/LinkPlaces.stories.tsx +60 -0
- package/src/LinkPlaces.test.ts +134 -0
- package/src/LinkPlaces.ts +169 -0
- package/src/ReferenceCards.mdx +4 -0
- package/src/ReferenceMenu.mdx +32 -24
- package/src/ReferenceMenu.stories.tsx +15 -16
- package/src/ReferenceMenu.test.tsx +161 -57
- package/src/ReferenceMenu.tsx +48 -44
- package/src/editor.ts +1 -0
- package/src/linked.examples.ts +4 -3
- package/src/pages.test.ts +2 -2
- package/src/registry/registry.test.ts +6 -6
- package/stories/Choosing.mdx +3 -2
|
@@ -260,29 +260,45 @@ describe('[ and /', () => {
|
|
|
260
260
|
expect(screen.queryByRole('listbox')).toBeNull()
|
|
261
261
|
})
|
|
262
262
|
|
|
263
|
-
it('/ offers Format and Insert
|
|
264
|
-
render(<Doc references={references} upload={async () => ({})} />)
|
|
263
|
+
it('/ offers Format and Insert: Table, File, Upload and Mention, each when the app can do it', async () => {
|
|
264
|
+
render(<Doc references={references} mentions={mentions} upload={async () => ({})} />)
|
|
265
265
|
await type(' /')
|
|
266
|
-
// A row reads as its label and the key it is typed with.
|
|
267
|
-
|
|
266
|
+
// A row reads as its label and the key it is typed with; Insert in this order.
|
|
267
|
+
const rows = options()
|
|
268
|
+
expect(rows).toEqual(expect.arrayContaining(['Text', 'Checklist[]', 'Note']))
|
|
269
|
+
expect(rows.slice(-4)).toEqual(['Table', 'File[', 'Upload', 'Mention@'])
|
|
268
270
|
await press('Escape')
|
|
269
271
|
cleanup()
|
|
270
272
|
render(<Doc />)
|
|
271
273
|
await type(' /')
|
|
272
|
-
expect(options()).
|
|
273
|
-
expect(options()).not.toContain('Link to a file[')
|
|
274
|
-
expect(options()).toContain('Table')
|
|
274
|
+
expect(options().slice(-1)).toEqual(['Table'])
|
|
275
275
|
})
|
|
276
276
|
|
|
277
|
-
it('/ →
|
|
277
|
+
it('/ → Upload opens the file dialog, and that dialog taking focus does not save', async () => {
|
|
278
|
+
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
|
|
279
|
+
const onCommit = vi.fn(async () => true)
|
|
280
|
+
render(<Doc upload={async () => ({})} onCommit={onCommit} />)
|
|
281
|
+
await type(' /upload')
|
|
282
|
+
await press('Enter')
|
|
283
|
+
expect(click).toHaveBeenCalledTimes(1)
|
|
284
|
+
await leave()
|
|
285
|
+
expect(onCommit).not.toHaveBeenCalled()
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
it.each([
|
|
289
|
+
['File', '/file', 'Items'],
|
|
290
|
+
['Mention', '/mention', 'People'],
|
|
291
|
+
])('/ → %s opens its list', async (_row, typed, list) => {
|
|
278
292
|
vi.useFakeTimers({ toFake: ['requestAnimationFrame'] })
|
|
279
|
-
render(<Doc references={references} />)
|
|
280
|
-
await type(
|
|
293
|
+
render(<Doc references={references} mentions={mentions} />)
|
|
294
|
+
await type(` ${typed}`)
|
|
295
|
+
// The row Enter picks is the one named so, not another the word also finds.
|
|
296
|
+
expect(within(screen.getByRole('listbox', { name: 'Commands' })).getAllByRole('option')[0].textContent).toMatch(new RegExp(`^${_row}`))
|
|
281
297
|
await press('Enter')
|
|
282
298
|
await act(async () => {
|
|
283
299
|
vi.advanceTimersToNextFrame()
|
|
284
300
|
})
|
|
285
|
-
expect(screen.getByRole('listbox', { name:
|
|
301
|
+
expect(screen.getByRole('listbox', { name: list })).toBeTruthy()
|
|
286
302
|
})
|
|
287
303
|
})
|
|
288
304
|
|
|
@@ -485,6 +501,55 @@ describe('blocks', () => {
|
|
|
485
501
|
})
|
|
486
502
|
})
|
|
487
503
|
|
|
504
|
+
describe('a link, by where it sits', () => {
|
|
505
|
+
const run = (uri: string, embed?: string) => ({ type: 'text', text: uri, marks: [{ type: 'reference', attrs: { uri, ...(embed ? { embed } : {}) } }] })
|
|
506
|
+
/** The app's drawing of a link: says where it sits. */
|
|
507
|
+
const Placed = ({ uri, place }: { uri: string; place?: string }) => (
|
|
508
|
+
<a href={`/o/${uri}`} data-place={place ?? 'none'} onClick={(event) => event.preventDefault()}>
|
|
509
|
+
Item
|
|
510
|
+
</a>
|
|
511
|
+
)
|
|
512
|
+
const places = () => [...document.querySelectorAll('[data-place]')].map((el) => el.getAttribute('data-place'))
|
|
513
|
+
|
|
514
|
+
it('draws as its row alone on its line, its chip in a sentence, and its card in the row\'s place once chosen', async () => {
|
|
515
|
+
const value = doc(
|
|
516
|
+
{ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] },
|
|
517
|
+
{ type: 'paragraph', id: 'a2', content: [{ type: 'text', text: 'See ' }, run(ITEM_URI)] },
|
|
518
|
+
{ type: 'paragraph', id: 'a3', content: [run(ITEM_URI, 'detailed')] },
|
|
519
|
+
)
|
|
520
|
+
render(<Doc value={value} referenceView={Placed} />)
|
|
521
|
+
await screen.findAllByRole('link', { name: 'Item' })
|
|
522
|
+
expect(places()).toEqual(['row', 'chip', 'card'])
|
|
523
|
+
})
|
|
524
|
+
|
|
525
|
+
it('turns from its row into its chip as words are typed before it, and back when they are taken away', async () => {
|
|
526
|
+
render(<Doc value={doc({ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] })} referenceView={Placed} />)
|
|
527
|
+
await screen.findByRole('link', { name: 'Item' })
|
|
528
|
+
expect(places()).toEqual(['row'])
|
|
529
|
+
await act(async () => editorOf().chain().focus().insertContentAt(1, 'See ').run())
|
|
530
|
+
expect(places()).toEqual(['chip'])
|
|
531
|
+
await act(async () => editorOf().chain().focus().deleteRange({ from: 1, to: 5 }).run())
|
|
532
|
+
expect(places()).toEqual(['row'])
|
|
533
|
+
})
|
|
534
|
+
|
|
535
|
+
it('Show as Card on a lone link saves its card, and Show as Row saves it without one', async () => {
|
|
536
|
+
const onCommit = vi.fn<DocumentEditorProps['onCommit']>(async () => true)
|
|
537
|
+
render(<Doc value={doc({ type: 'paragraph', id: 'a1', content: [run(ITEM_URI)] })} referenceView={Placed} onCommit={onCommit} />)
|
|
538
|
+
const choose = async (label: 'Row' | 'Card') => {
|
|
539
|
+
await act(async () => editorOf().view.focus())
|
|
540
|
+
fireEvent.click(await screen.findByRole('link', { name: 'Item' }))
|
|
541
|
+
fireEvent.mouseDown(await screen.findByRole('menuitemradio', { name: label }))
|
|
542
|
+
await leave()
|
|
543
|
+
}
|
|
544
|
+
await choose('Card')
|
|
545
|
+
expect(places()).toEqual(['card'])
|
|
546
|
+
expect(saved(onCommit.mock.calls[0][0])[0].runs[0].marks).toEqual([{ type: 'reference', attrs: { uri: ITEM_URI, embed: 'detailed' } }])
|
|
547
|
+
await choose('Row')
|
|
548
|
+
expect(places()).toEqual(['row'])
|
|
549
|
+
expect(saved(onCommit.mock.calls[1][0])[0].runs[0].marks).toEqual([{ type: 'reference', attrs: { uri: ITEM_URI } }])
|
|
550
|
+
})
|
|
551
|
+
})
|
|
552
|
+
|
|
488
553
|
describe('reading', () => {
|
|
489
554
|
it('read only, nothing can be typed or saved, and the text is drawn the same', async () => {
|
|
490
555
|
const onCommit = vi.fn(async () => true)
|
package/src/DocumentEditor.tsx
CHANGED
|
@@ -18,7 +18,7 @@ import { LinkChips, type LinkChipsOptions } from './LinkChips'
|
|
|
18
18
|
import { BareLinks, DocumentKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'
|
|
19
19
|
import { PastedImages } from './PastedImages'
|
|
20
20
|
import { PastedMarkdown } from './PastedMarkdown'
|
|
21
|
-
import {
|
|
21
|
+
import { LinkPlaces } from './LinkPlaces'
|
|
22
22
|
import { ReferenceMenu, ReferenceMenuView, isReferenceMenuOpen } from './ReferenceMenu'
|
|
23
23
|
import { richTextClassName } from './RichText'
|
|
24
24
|
import { KeptSelection, SelectionToolbar } from './SelectionToolbar'
|
|
@@ -102,13 +102,13 @@ export interface DocumentEditorProps {
|
|
|
102
102
|
/** Where text typed when the sign-in ends is held, under `holdKey`. */
|
|
103
103
|
hold?: HeldTyping
|
|
104
104
|
holdKey?: string
|
|
105
|
-
/** `[` and `/` →
|
|
105
|
+
/** `[` and `/` → File. */
|
|
106
106
|
references?: DocumentReferences
|
|
107
|
-
/**
|
|
107
|
+
/** `@` and `/` → Mention. */
|
|
108
108
|
mentions?: DocumentMentions
|
|
109
109
|
/** A pasted app URL drawn as the chip of what it names (`LinkChips`). */
|
|
110
110
|
linkChips?: LinkChipsOptions
|
|
111
|
-
/** `/` →
|
|
111
|
+
/** `/` → Upload, and a pasted picture: upload one file and answer the attachment's attributes (its `imeta` fields). */
|
|
112
112
|
upload?: (file: File) => Promise<Record<string, unknown>>
|
|
113
113
|
/** Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document. */
|
|
114
114
|
readMarkdown?: (text: string) => JSONContent | undefined
|
|
@@ -118,12 +118,13 @@ export interface DocumentEditorProps {
|
|
|
118
118
|
onCommentOnSelection?: (anchor: SelectionAnchor) => void
|
|
119
119
|
/** The app's rows in a block's handle menu, after the editing ones: Copy link, Comment. */
|
|
120
120
|
blockRows?: (block: HandleBlock) => ReactNode
|
|
121
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Draws a link: the app's own, which resolves what it names — its chip, its
|
|
123
|
+
* row or its card in the row's place, as `place` says (§13.3).
|
|
124
|
+
*/
|
|
122
125
|
referenceView?: ComponentType<ReferenceViewProps>
|
|
123
126
|
/** Draws a placed file: the app's own card. */
|
|
124
127
|
attachmentView?: ComponentType<AttachmentViewProps>
|
|
125
|
-
/** Drawn after the text: the cards chips ask for, as the app draws them. */
|
|
126
|
-
cards?: (editor: Editor | null) => ReactNode
|
|
127
128
|
/** Around everything the editor draws: the app's providers, which may read the editor. */
|
|
128
129
|
wrap?: (children: ReactNode, editor: Editor | null) => ReactNode
|
|
129
130
|
/** The editor, once it is there, and `null` as it goes. */
|
|
@@ -186,7 +187,6 @@ export function DocumentEditor({
|
|
|
186
187
|
blockRows,
|
|
187
188
|
referenceView,
|
|
188
189
|
attachmentView,
|
|
189
|
-
cards,
|
|
190
190
|
wrap,
|
|
191
191
|
onEditor,
|
|
192
192
|
extensions = [],
|
|
@@ -363,13 +363,13 @@ export function DocumentEditor({
|
|
|
363
363
|
Checklist,
|
|
364
364
|
Callout,
|
|
365
365
|
ReferenceNode.configure({ view: referenceView ?? null }),
|
|
366
|
-
//
|
|
367
|
-
|
|
368
|
-
// A click on a
|
|
366
|
+
// A link's chip in a sentence, its row alone on its line, its card in the row's place (SPEC §13.3).
|
|
367
|
+
LinkPlaces,
|
|
368
|
+
// A click on a link offers Open, and alone on its line Show as Row or Card.
|
|
369
369
|
ReferenceMenu,
|
|
370
370
|
UnknownBlock,
|
|
371
371
|
AttachmentNode.configure({ view: attachmentView ?? null }),
|
|
372
|
-
SlashCommands.configure({ sections: slashSections({ table,
|
|
372
|
+
SlashCommands.configure({ sections: slashSections({ table, upload: !!upload, pickFile }) }),
|
|
373
373
|
...(references
|
|
374
374
|
? [
|
|
375
375
|
ReferenceTrigger.configure({
|
|
@@ -410,7 +410,15 @@ export function DocumentEditor({
|
|
|
410
410
|
editable: !readOnly,
|
|
411
411
|
editorProps: {
|
|
412
412
|
// Focusable when read only too: the selection strip, and so Comment on its words, shows only in a focused view.
|
|
413
|
-
attributes: {
|
|
413
|
+
attributes: {
|
|
414
|
+
'aria-label': label,
|
|
415
|
+
role: 'textbox',
|
|
416
|
+
'aria-multiline': 'true',
|
|
417
|
+
tabindex: '0',
|
|
418
|
+
// A row or a card is its whole line (`LinkPlaces`), drawn on that line: a block inside it would push the
|
|
419
|
+
// separator and trailing break ProseMirror puts beside it onto empty lines of their own (code review).
|
|
420
|
+
class: richTextClassName('default', 'outline-none [&_[data-link-place]]:inline-block [&_[data-link-place]]:w-full [&_[data-link-place]]:align-top'),
|
|
421
|
+
},
|
|
414
422
|
handleKeyDown: (view, event) => {
|
|
415
423
|
if (event.key !== 'Escape') return false
|
|
416
424
|
// An open list or chip menu closes first; the next Escape leaves.
|
|
@@ -507,7 +515,6 @@ export function DocumentEditor({
|
|
|
507
515
|
</span>
|
|
508
516
|
)}
|
|
509
517
|
</EditorBlockHandle>
|
|
510
|
-
{cards?.(editor)}
|
|
511
518
|
{/* Read only with comments off, the strip would have nothing in it: no strip. */}
|
|
512
519
|
{(!readOnly || onCommentOnSelection) && <SelectionToolbar
|
|
513
520
|
editor={editor}
|
|
@@ -554,15 +561,18 @@ export function DocumentEditor({
|
|
|
554
561
|
|
|
555
562
|
/**
|
|
556
563
|
* `/`: the shared Format section with a document's checklist and callouts,
|
|
557
|
-
* then Insert with what this editor can do.
|
|
558
|
-
*
|
|
564
|
+
* then Insert with what this editor can do. File and Mention type `[` and `@`,
|
|
565
|
+
* so their lists open; Upload picks a file from the computer (Miky, 15 October
|
|
566
|
+
* QA and 20 October at the Storybook: "File" for `[`, a Mention row, "Upload").
|
|
559
567
|
*/
|
|
560
|
-
function slashSections({ table,
|
|
568
|
+
function slashSections({ table, upload, pickFile }: { table: boolean; upload: boolean; pickFile: { current: () => void } }): SlashSection[] {
|
|
561
569
|
const insert: SlashCommand[] = [
|
|
562
570
|
// Three by three with a header row, as every app's Insert → Table makes it.
|
|
563
571
|
...(table ? [{ key: 'insert-table', row: { label: 'Table' }, run: (editor: Editor) => void editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() }] : []),
|
|
564
|
-
|
|
565
|
-
|
|
572
|
+
// Offered only where the editor has the list the row opens.
|
|
573
|
+
{ key: 'insert-link', row: { label: 'File', shortcut: '[' }, keywords: ['[', 'link', 'reference'], needs: ['referenceTrigger'], run: typeTrigger('[') },
|
|
574
|
+
...(upload ? [{ key: 'insert-upload', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: () => pickFile.current() }] : []),
|
|
575
|
+
{ key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'person', 'people'], needs: ['personReference'], run: typeTrigger('@') },
|
|
566
576
|
]
|
|
567
577
|
return [formatSection('block'), ...(insert.length > 0 ? [{ label: 'Insert', commands: insert }] : [])]
|
|
568
578
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Meta, Canvas } from '@storybook/addon-docs/blocks'
|
|
2
|
+
import * as LinkPlacesStories from './LinkPlaces.stories'
|
|
3
|
+
|
|
4
|
+
<Meta of={LinkPlacesStories} />
|
|
5
|
+
|
|
6
|
+
# LinkPlaces
|
|
7
|
+
|
|
8
|
+
Where a link in a document sits decides how it draws: its chip in a sentence,
|
|
9
|
+
its row alone on its line, and its card in the row's place when its writer
|
|
10
|
+
chose one (`embed` `detailed`). This tells each link's view its place; the
|
|
11
|
+
app's view draws the chip, row or card.
|
|
12
|
+
|
|
13
|
+
<Canvas of={LinkPlacesStories.InAnEditor} />
|
|
14
|
+
|
|
15
|
+
## When
|
|
16
|
+
|
|
17
|
+
- **An editor of a document**: pair it with **ReferenceNode**, whose view is
|
|
18
|
+
handed `place`, and **ReferenceMenu**, whose Show as Row or Card changes it.
|
|
19
|
+
**DocumentEditor** has both.
|
|
20
|
+
|
|
21
|
+
## When not
|
|
22
|
+
|
|
23
|
+
- A message's box, where every link is a chip while it is written → leave it
|
|
24
|
+
out: without it every view is told `chip`.
|
|
25
|
+
- A document that is only read, outside an editor → **RichText**, with the
|
|
26
|
+
lines drawn by the protocol's `documentLineDraws`, the same rule.
|
|
27
|
+
|
|
28
|
+
## How
|
|
29
|
+
|
|
30
|
+
```tsx
|
|
31
|
+
import { EditorContent, useEditor } from '@tiptap/react'
|
|
32
|
+
import StarterKit from '@tiptap/starter-kit'
|
|
33
|
+
import { LinkCard, LinkChip, LinkRow } from '@estiva-app/ui'
|
|
34
|
+
import { BlockId, LinkPlaces, ReferenceNode, type ReferenceViewProps } from '@estiva-app/ui/editor'
|
|
35
|
+
|
|
36
|
+
function Link({ uri, place = 'chip', editing }: ReferenceViewProps) {
|
|
37
|
+
const link = useResolved(uri) // the app's own lookup
|
|
38
|
+
if (place === 'card') return <LinkCard link={link} />
|
|
39
|
+
if (place === 'row') return <LinkRow link={link} preview={!editing} />
|
|
40
|
+
return <LinkChip link={link} preview={!editing} />
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const editor = useEditor({ extensions: [StarterKit, BlockId, ReferenceNode.configure({ view: Link }), LinkPlaces] })
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- **Alone on its line** is a top-level paragraph's line, or a list item's, up
|
|
47
|
+
to a hard break, holding the link and nothing but spaces. A heading, a quote,
|
|
48
|
+
a callout and a table cell are sentences. So is a link inside a marker
|
|
49
|
+
(bold, italic, code).
|
|
50
|
+
- **A person or a Folder alone on its line stays a chip** (`staysChip`).
|
|
51
|
+
- **Only `detailed` draws the card.** No `embed`, `compact` or a value this
|
|
52
|
+
version does not know draws the row.
|
|
53
|
+
- **The same rule as the protocol's** `documentLineDrawOf`, read off the
|
|
54
|
+
editor's tree on every change; a test holds the two to one answer.
|
|
55
|
+
- **A row or a card is the whole line**: its view's wrapper is a block.
|
|
56
|
+
|
|
57
|
+
## What it owns
|
|
58
|
+
|
|
59
|
+
Nothing. It only draws. Clicks and keys are yours.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { Meta, StoryObj } from '@storybook/react-vite'
|
|
2
|
+
import { EditorContent, useEditor } from '@tiptap/react'
|
|
3
|
+
import StarterKit from '@tiptap/starter-kit'
|
|
4
|
+
import { BlockId, ReferenceNode, type ReferenceViewProps } from './BlockNodes'
|
|
5
|
+
import { Card } from './Card'
|
|
6
|
+
import { InlineChip } from './InlineChip'
|
|
7
|
+
import { LinkPlaces } from './LinkPlaces'
|
|
8
|
+
import { richTextClassName } from './RichText'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Each link in a document is told where it sits, and the app draws it there:
|
|
12
|
+
* its chip in a sentence, its row alone on its line, its card in the row's
|
|
13
|
+
* place. Here the row and card are stand-in boxes naming the place; the real
|
|
14
|
+
* ones are the app's, which knows how to resolve what the link points at.
|
|
15
|
+
*/
|
|
16
|
+
const meta = {
|
|
17
|
+
title: 'Primitives/LinkPlaces',
|
|
18
|
+
parameters: { layout: 'padded' },
|
|
19
|
+
} satisfies Meta
|
|
20
|
+
|
|
21
|
+
export default meta
|
|
22
|
+
type Story = StoryObj
|
|
23
|
+
|
|
24
|
+
const ref = (uri: string, embed?: string) => ({ type: 'reference', attrs: { uri, ...(embed ? { embed } : {}) } })
|
|
25
|
+
|
|
26
|
+
/** A stand-in for the app's drawing of a link, by its place. */
|
|
27
|
+
function Placed({ uri, place = 'chip' }: ReferenceViewProps) {
|
|
28
|
+
const name = uri.endsWith('one') ? 'Item one' : uri.endsWith('two') ? 'Item two' : 'Item three'
|
|
29
|
+
if (place === 'chip') return <InlineChip>{name}</InlineChip>
|
|
30
|
+
return (
|
|
31
|
+
<Card fill="inset" className={place === 'card' ? 'flex h-24 items-start p-3' : 'flex h-9 items-center px-3'}>
|
|
32
|
+
<span className="text-body-2 text-text-secondary">
|
|
33
|
+
{name}, its {place}
|
|
34
|
+
</span>
|
|
35
|
+
</Card>
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function Box() {
|
|
40
|
+
const editor = useEditor({
|
|
41
|
+
extensions: [StarterKit, BlockId, ReferenceNode.configure({ view: Placed }), LinkPlaces],
|
|
42
|
+
content: {
|
|
43
|
+
type: 'doc',
|
|
44
|
+
content: [
|
|
45
|
+
{ type: 'paragraph', attrs: { blockId: 'p1' }, content: [{ type: 'text', text: 'A sentence that names ' }, ref('nostr:naddr1one'), { type: 'text', text: ' in passing.' }] },
|
|
46
|
+
{ type: 'paragraph', attrs: { blockId: 'p2' }, content: [ref('nostr:naddr1two')] },
|
|
47
|
+
{ type: 'paragraph', attrs: { blockId: 'p3' }, content: [ref('nostr:naddr1three', 'detailed')] },
|
|
48
|
+
],
|
|
49
|
+
},
|
|
50
|
+
editorProps: { attributes: { class: richTextClassName('default', 'outline-none'), 'aria-label': 'Text' } },
|
|
51
|
+
})
|
|
52
|
+
return (
|
|
53
|
+
<Card fill="surface" className="flex w-[520px] flex-col gap-2 p-3">
|
|
54
|
+
<EditorContent editor={editor} />
|
|
55
|
+
</Card>
|
|
56
|
+
)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A chip in a sentence, a row alone on its line, and a card chosen for the third. Type beside the row: it becomes a chip. */
|
|
60
|
+
export const InAnEditor: Story = { render: () => <Box /> }
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
/**
|
|
3
|
+
* Where a link in a document sits decides how it draws (SPEC §13.3, C22): its
|
|
4
|
+
* chip in a sentence, its row alone on its line, its card in the row's place.
|
|
5
|
+
* The editor reads the rule off its own tree; the protocol reads it off the
|
|
6
|
+
* saved document. Both must give the same answer, or a page reads one way
|
|
7
|
+
* while it is written and another once it is saved.
|
|
8
|
+
*/
|
|
9
|
+
import { afterEach, describe, expect, it } from 'vitest'
|
|
10
|
+
import { Editor, type JSONContent } from '@tiptap/core'
|
|
11
|
+
import { TableKit } from '@tiptap/extension-table'
|
|
12
|
+
import { documentForEditing, documentLineDraws, encodeNaddr, encodeNpub, publishableFromEditor, toEditorDocument, toRenderTree, type EditorDocument } from '@estiva-app/protocol'
|
|
13
|
+
import { BlockId, Callout, Checklist, ReferenceNode, UnknownBlock } from './BlockNodes'
|
|
14
|
+
import { LinkPlaces, linkPlaceAt, linkPlaces, staysChip, type LinkPlace } from './LinkPlaces'
|
|
15
|
+
import { DocumentKit } from './links'
|
|
16
|
+
|
|
17
|
+
const naddr = (kind: number, identifier: string) => `nostr:${encodeNaddr({ kind, pubkey: 'a'.repeat(64), identifier, relays: [] })}`
|
|
18
|
+
const V = naddr(30851, 'item-one')
|
|
19
|
+
const FOLDER = naddr(39000, 'place-one')
|
|
20
|
+
const PERSON = `nostr:${encodeNpub('b'.repeat(64))}`
|
|
21
|
+
|
|
22
|
+
const ref = (uri: string, attrs: Record<string, unknown> = {}): JSONContent => ({ type: 'reference', attrs: { uri, ...attrs } })
|
|
23
|
+
const text = (t: string): JSONContent => ({ type: 'text', text: t })
|
|
24
|
+
const p = (...content: JSONContent[]): JSONContent => ({ type: 'paragraph', content })
|
|
25
|
+
const doc = (...content: JSONContent[]): JSONContent => ({ type: 'doc', content })
|
|
26
|
+
|
|
27
|
+
let editor: Editor | undefined
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
editor?.destroy()
|
|
30
|
+
editor = undefined
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
const make = (content: JSONContent | string) => {
|
|
34
|
+
editor = new Editor({
|
|
35
|
+
extensions: [DocumentKit.configure({ link: false }), TableKit, BlockId, Checklist, Callout, ReferenceNode, UnknownBlock, LinkPlaces],
|
|
36
|
+
content,
|
|
37
|
+
})
|
|
38
|
+
return editor
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The place of the one reference in `content`. */
|
|
42
|
+
function placeIn(content: JSONContent): LinkPlace {
|
|
43
|
+
const ed = make(content)
|
|
44
|
+
let at = -1
|
|
45
|
+
ed.state.doc.descendants((node, pos) => {
|
|
46
|
+
if (node.type.name === 'reference' && at < 0) at = pos
|
|
47
|
+
})
|
|
48
|
+
return linkPlaceAt(ed.state.doc, at)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Each case: a document holding one reference, and how it draws. */
|
|
52
|
+
const CASES: [string, JSONContent, LinkPlace][] = [
|
|
53
|
+
['alone in a paragraph', doc(p(ref(V))), 'row'],
|
|
54
|
+
['alone with a space after it, as a `[` pick leaves it', doc(p(ref(V), text(' '))), 'row'],
|
|
55
|
+
['in a sentence', doc(p(text('See '), ref(V), text(' today.'))), 'chip'],
|
|
56
|
+
['followed by a full stop', doc(p(ref(V), text('.'))), 'chip'],
|
|
57
|
+
['alone on the second line of a paragraph, after a hard break', doc(p(text('First line'), { type: 'hardBreak' }, ref(V))), 'row'],
|
|
58
|
+
['in a heading', doc({ type: 'heading', attrs: { level: 2 }, content: [ref(V)] }), 'chip'],
|
|
59
|
+
['in a quote', doc({ type: 'blockquote', content: [p(ref(V))] }), 'chip'],
|
|
60
|
+
['in a callout', doc({ type: 'blockquote', attrs: { tone: 'note' }, content: [p(ref(V))] }), 'chip'],
|
|
61
|
+
['alone in a list item', doc({ type: 'bulletList', content: [{ type: 'listItem', content: [p(ref(V))] }] }), 'row'],
|
|
62
|
+
['alone in a checklist item', doc({ type: 'bulletList', content: [{ type: 'listItem', attrs: { checked: false }, content: [p(ref(V))] }] }), 'row'],
|
|
63
|
+
['alone in a numbered list item', doc({ type: 'orderedList', content: [{ type: 'listItem', content: [p(ref(V))] }] }), 'row'],
|
|
64
|
+
['in a table cell', doc({ type: 'table', content: [{ type: 'tableRow', content: [{ type: 'tableCell', content: [p(ref(V))] }] }] }), 'chip'],
|
|
65
|
+
['alone with its card chosen', doc(p(ref(V, { embed: 'detailed' }))), 'card'],
|
|
66
|
+
['alone with an older writer\'s compact card', doc(p(ref(V, { embed: 'compact' }))), 'row'],
|
|
67
|
+
['alone with a card value this version does not know', doc(p(ref(V, { embed: 'wide' }))), 'row'],
|
|
68
|
+
['in a sentence with its card chosen', doc(p(text('See '), ref(V, { embed: 'detailed' }))), 'chip'],
|
|
69
|
+
['alone but bold', doc(p(ref(V, { marks: ['bold'] }))), 'chip'],
|
|
70
|
+
['a person alone', doc(p(ref(PERSON))), 'chip'],
|
|
71
|
+
['a Folder alone', doc(p(ref(FOLDER))), 'chip'],
|
|
72
|
+
['a Folder alone with a card chosen', doc(p(ref(FOLDER, { embed: 'detailed' }))), 'chip'],
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
describe('linkPlaceAt', () => {
|
|
76
|
+
it.each(CASES)('draws a link %s as its %s', (_name, content, place) => {
|
|
77
|
+
expect(placeIn(content)).toBe(place)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('draws two links on one line as chips', () => {
|
|
81
|
+
const ed = make(doc(p(ref(V), text(' '), ref(naddr(30851, 'item-two')))))
|
|
82
|
+
expect(linkPlaces(ed.state.doc)).toEqual([])
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('draws a pasted URL not resolved yet as its URL, a chip, even alone', () => {
|
|
86
|
+
expect(placeIn(doc(p(ref('', { href: 'https://app.example/item/one' }))))).toBe('chip')
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it('turns a row into a chip as soon as words are typed beside it, and back when they are deleted', () => {
|
|
90
|
+
const ed = make(doc(p(ref(V))))
|
|
91
|
+
expect(linkPlaceAt(ed.state.doc, 1)).toBe('row')
|
|
92
|
+
ed.commands.insertContentAt(2, 'and more')
|
|
93
|
+
expect(linkPlaceAt(ed.state.doc, 1)).toBe('chip')
|
|
94
|
+
ed.commands.deleteRange({ from: 2, to: 2 + 'and more'.length })
|
|
95
|
+
expect(linkPlaceAt(ed.state.doc, 1)).toBe('row')
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('tells the view of each lone link its place, through a node decoration', () => {
|
|
99
|
+
const ed = make(doc(p(ref(V)), p(ref(V, { embed: 'detailed' })), p(text('See '), ref(V))))
|
|
100
|
+
const places = [...ed.view.dom.querySelectorAll('[data-reference]')].map((el) => el.closest('[data-link-place]')?.getAttribute('data-link-place') ?? 'chip')
|
|
101
|
+
expect(places).toEqual(['row', 'card', 'chip'])
|
|
102
|
+
})
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
describe('staysChip', () => {
|
|
106
|
+
it('keeps a person and a Folder as chips, and nothing else', () => {
|
|
107
|
+
expect(staysChip(PERSON)).toBe(true)
|
|
108
|
+
expect(staysChip(FOLDER)).toBe(true)
|
|
109
|
+
expect(staysChip(FOLDER.toUpperCase())).toBe(true)
|
|
110
|
+
expect(staysChip(V)).toBe(false)
|
|
111
|
+
expect(staysChip(naddr(30850, 'group-one'))).toBe(false)
|
|
112
|
+
expect(staysChip('nostr:naddr1notbech32')).toBe(false)
|
|
113
|
+
})
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
describe('the editor and the protocol agree', () => {
|
|
117
|
+
/** How the protocol draws the saved document's one link: `row` or `card` where it says so, else its chip. */
|
|
118
|
+
function protocolPlace(value: string): LinkPlace {
|
|
119
|
+
for (const draws of documentLineDraws(toRenderTree(value, 'blocks')).values()) {
|
|
120
|
+
for (const line of draws) if (line.draw === 'row' || line.draw === 'card') return line.draw
|
|
121
|
+
}
|
|
122
|
+
return 'chip'
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
it.each(CASES)('on a link %s, once saved and opened again', (_name, content, place) => {
|
|
126
|
+
const { value } = publishableFromEditor(make(content).getJSON() as EditorDocument)
|
|
127
|
+
editor?.destroy()
|
|
128
|
+
// Opened again as an app opens it: the saved bytes, read back into the editor.
|
|
129
|
+
const reopened = make(toEditorDocument(documentForEditing(value, 'blocks'), { links: true }) as JSONContent)
|
|
130
|
+
const editorPlaces = linkPlaces(reopened.state.doc).map((one) => one.place)
|
|
131
|
+
expect(protocolPlace(value)).toBe(place)
|
|
132
|
+
expect(editorPlaces[0] ?? 'chip').toBe(place)
|
|
133
|
+
})
|
|
134
|
+
})
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a reference in a block document sits, and so how it draws — SPEC §13.3,
|
|
3
|
+
* "A reference's card" (C22, C24): its chip in a sentence, its row alone on its
|
|
4
|
+
* line, and its card in the row's place when its writer chose one.
|
|
5
|
+
*
|
|
6
|
+
* The rule is the protocol's (`documentLineDrawOf` in `@estiva-app/protocol`),
|
|
7
|
+
* read here off the editor's own tree so it can be asked on every keystroke
|
|
8
|
+
* without writing the document out. `linkPlaces.test.ts` runs the same
|
|
9
|
+
* documents through both and holds them to one answer.
|
|
10
|
+
*
|
|
11
|
+
* - **Alone on its line**: a top-level paragraph, or a list item's, whose line
|
|
12
|
+
* (up to a hard break) holds this reference and nothing but spaces besides.
|
|
13
|
+
* A heading, a quote, a callout and a table cell are sentences, and so is
|
|
14
|
+
* anything inside a block this rule does not name.
|
|
15
|
+
* - **A marker around it** (bold, italic, code…) makes it a sentence.
|
|
16
|
+
* - **A person or a Folder** alone on its line stays a chip.
|
|
17
|
+
* - **Its card** is `embed` `detailed`; anything else (none, `compact`, a value
|
|
18
|
+
* this version does not know) draws the row.
|
|
19
|
+
*
|
|
20
|
+
* `LinkPlaces` puts each reference's place on a node decoration, which
|
|
21
|
+
* `ReferenceNode`'s view reads and hands to the app's view as `place`.
|
|
22
|
+
*
|
|
23
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md
|
|
24
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md
|
|
25
|
+
*/
|
|
26
|
+
import { Extension } from '@tiptap/core'
|
|
27
|
+
import type { Node as PmNode } from '@tiptap/pm/model'
|
|
28
|
+
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
|
29
|
+
import { Decoration, DecorationSet } from '@tiptap/pm/view'
|
|
30
|
+
|
|
31
|
+
/** How a reference draws: its chip, its row, or its card in the row's place. */
|
|
32
|
+
export type LinkPlace = 'chip' | 'row' | 'card'
|
|
33
|
+
|
|
34
|
+
/** The blocks a line may sit inside and still be alone: a list and its items. */
|
|
35
|
+
const CONTAINERS = new Set(['bulletList', 'orderedList', 'listItem'])
|
|
36
|
+
|
|
37
|
+
const BECH32 = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
|
|
38
|
+
|
|
39
|
+
/** The 5-bit words of a bech32 string's data part, checksum dropped, or null. */
|
|
40
|
+
function bech32Words(text: string): number[] | null {
|
|
41
|
+
const at = text.lastIndexOf('1')
|
|
42
|
+
if (at < 1 || text.length - at < 7) return null
|
|
43
|
+
const words: number[] = []
|
|
44
|
+
for (const char of text.slice(at + 1, -6)) {
|
|
45
|
+
const word = BECH32.indexOf(char)
|
|
46
|
+
if (word < 0) return null
|
|
47
|
+
words.push(word)
|
|
48
|
+
}
|
|
49
|
+
return words
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** An `naddr`'s kind (TLV type 3), or null when it does not hold one. */
|
|
53
|
+
function naddrKind(naddr: string): number | null {
|
|
54
|
+
const words = bech32Words(naddr)
|
|
55
|
+
if (!words) return null
|
|
56
|
+
const bytes: number[] = []
|
|
57
|
+
let acc = 0
|
|
58
|
+
let bits = 0
|
|
59
|
+
for (const word of words) {
|
|
60
|
+
acc = (acc << 5) | word
|
|
61
|
+
bits += 5
|
|
62
|
+
while (bits >= 8) {
|
|
63
|
+
bits -= 8
|
|
64
|
+
bytes.push((acc >> bits) & 0xff)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (let i = 0; i + 1 < bytes.length; ) {
|
|
68
|
+
const type = bytes[i]
|
|
69
|
+
const length = bytes[i + 1]
|
|
70
|
+
if (type === 3 && length === 4 && i + 6 <= bytes.length) return ((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i + 4] << 8) | bytes[i + 5]) >>> 0
|
|
71
|
+
i += 2 + length
|
|
72
|
+
}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A Folder's kind. */
|
|
77
|
+
const FOLDER = 39000
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Whether what `uri` names stays a chip alone on its line: a person (`npub`,
|
|
81
|
+
* `nprofile`) or a Folder (an `naddr` of kind 39000).
|
|
82
|
+
*/
|
|
83
|
+
export function staysChip(uri: string): boolean {
|
|
84
|
+
const bare = uri.toLowerCase().replace(/^nostr:/, '')
|
|
85
|
+
if (bare.startsWith('npub1') || bare.startsWith('nprofile1')) return true
|
|
86
|
+
return bare.startsWith('naddr1') && naddrKind(bare) === FOLDER
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether the textblock holding `pos` keeps the line rule: a paragraph at the top, or a list item's. */
|
|
90
|
+
function keepsLineRule(doc: PmNode, pos: number): boolean {
|
|
91
|
+
const $pos = doc.resolve(pos)
|
|
92
|
+
if ($pos.parent.type.name !== 'paragraph' && $pos.parent.type.name !== 'listItem') return false
|
|
93
|
+
for (let depth = 1; depth < $pos.depth; depth++) if (!CONTAINERS.has($pos.node(depth).type.name)) return false
|
|
94
|
+
return true
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Whether the reference at `index` of `block` is alone on its line: only spaces beside it, up to a hard break either side. */
|
|
98
|
+
function aloneOnLine(block: PmNode, index: number): boolean {
|
|
99
|
+
for (const step of [-1, 1]) {
|
|
100
|
+
for (let i = index + step; i >= 0 && i < block.childCount; i += step) {
|
|
101
|
+
const child = block.child(i)
|
|
102
|
+
if (child.type.name === 'hardBreak') break
|
|
103
|
+
if (!child.isText || (child.text ?? '').trim() !== '') return false
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return true
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** How the reference node at `pos` draws. Anything that is not a reference with a `uri` draws as a chip. */
|
|
110
|
+
export function linkPlaceAt(doc: PmNode, pos: number): LinkPlace {
|
|
111
|
+
const node = doc.nodeAt(pos)
|
|
112
|
+
if (!node || node.type.name !== 'reference') return 'chip'
|
|
113
|
+
const uri = String(node.attrs.uri ?? '')
|
|
114
|
+
// A URL chip whose URL is not resolved yet names nothing: it reads as the URL.
|
|
115
|
+
if (!uri || staysChip(uri)) return 'chip'
|
|
116
|
+
if (Array.isArray(node.attrs.marks) && node.attrs.marks.length > 0) return 'chip'
|
|
117
|
+
if (!keepsLineRule(doc, pos)) return 'chip'
|
|
118
|
+
const $pos = doc.resolve(pos)
|
|
119
|
+
if (!aloneOnLine($pos.parent, $pos.index())) return 'chip'
|
|
120
|
+
return node.attrs.embed === 'detailed' ? 'card' : 'row'
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Every reference that does not draw as its chip, with its place. */
|
|
124
|
+
export function linkPlaces(doc: PmNode): { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] {
|
|
125
|
+
const out: { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] = []
|
|
126
|
+
doc.descendants((node, pos) => {
|
|
127
|
+
if (node.type.name !== 'reference') return true
|
|
128
|
+
const place = linkPlaceAt(doc, pos)
|
|
129
|
+
if (place !== 'chip') out.push({ pos, size: node.nodeSize, place })
|
|
130
|
+
return false
|
|
131
|
+
})
|
|
132
|
+
return out
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The place a node view's decorations give it; `chip` without one. */
|
|
136
|
+
export function placeOf(decorations: readonly Decoration[] | undefined): LinkPlace {
|
|
137
|
+
for (const decoration of decorations ?? []) {
|
|
138
|
+
const place = (decoration.spec as { linkPlace?: LinkPlace }).linkPlace
|
|
139
|
+
if (place) return place
|
|
140
|
+
}
|
|
141
|
+
return 'chip'
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const key = new PluginKey<DecorationSet>('linkPlaces')
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Marks each reference that draws as its row or its card, for `ReferenceNode`'s
|
|
148
|
+
* view. Without it every reference is a chip, as in a message's box.
|
|
149
|
+
*/
|
|
150
|
+
export const LinkPlaces = Extension.create({
|
|
151
|
+
name: 'linkPlaces',
|
|
152
|
+
addProseMirrorPlugins() {
|
|
153
|
+
const decorate = (doc: PmNode) =>
|
|
154
|
+
DecorationSet.create(
|
|
155
|
+
doc,
|
|
156
|
+
linkPlaces(doc).map(({ pos, size, place }) => Decoration.node(pos, pos + size, { 'data-link-place': place }, { linkPlace: place })),
|
|
157
|
+
)
|
|
158
|
+
return [
|
|
159
|
+
new Plugin<DecorationSet>({
|
|
160
|
+
key,
|
|
161
|
+
state: {
|
|
162
|
+
init: (_, state) => decorate(state.doc),
|
|
163
|
+
apply: (tr, set) => (tr.docChanged ? decorate(tr.doc) : set),
|
|
164
|
+
},
|
|
165
|
+
props: { decorations: (state) => key.getState(state) },
|
|
166
|
+
}),
|
|
167
|
+
]
|
|
168
|
+
},
|
|
169
|
+
})
|