@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.
package/src/links.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { Extension, type Mark } from '@tiptap/core'
2
+ import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
3
+ import { Decoration, DecorationSet } from '@tiptap/pm/view'
4
+ import StarterKit from '@tiptap/starter-kit'
5
+
6
+ /*
7
+ * Links in the kit's editors: a URL pasted over words, the link mark that holds
8
+ * it, and a bare address drawn as a link. `CommentBox` and `DocumentEditor`
9
+ * share the paste and the mark's end, so a link on words is made the same way
10
+ * wherever it is written.
11
+ */
12
+
13
+ /** A link a message can carry on words, `[words](url)`: no `)` and no space in it (conversation's `composerText`). */
14
+ const LINK_ON_WORDS_TARGET = /^https?:\/\/[^\s)]+$/
15
+
16
+ /**
17
+ * A URL pasted over words links them, as in Peek, when the message can carry
18
+ * them as a link on words: plain words on one line, no chip, no line break, no
19
+ * bracket, no code. Otherwise the words stay and the URL goes in after them,
20
+ * so neither is lost. Ahead of StarterKit's own link-on-paste.
21
+ */
22
+ export const PasteOverWords = Extension.create({
23
+ name: 'commentBoxPasteOverWords',
24
+ priority: 1001,
25
+ addProseMirrorPlugins() {
26
+ return [
27
+ new Plugin({
28
+ key: new PluginKey('commentBoxPasteOverWords'),
29
+ props: {
30
+ handlePaste: (view, event) => {
31
+ // A URL copied with the end of its sentence names what it names without it, as LinkChips reads one.
32
+ const url = (event.clipboardData?.getData('text/plain').trim() ?? '').replace(/[.,;:!?]+$/, '')
33
+ const { state } = view
34
+ const { schema } = state
35
+ if (state.selection.empty || !schema.marks.link || !/^https?:\/\/\S+$/.test(url)) return false
36
+ // Select-all spans the document itself: read it as the text it holds.
37
+ const { $from, $to, from, to } = TextSelection.between(state.selection.$from, state.selection.$to)
38
+ let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code
39
+ state.doc.nodesBetween(from, to, (node) => {
40
+ // A quote or a list around the line holds it, and is not in the words: look inside.
41
+ if (!node.isInline) return true
42
+ if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) plain = false
43
+ return false
44
+ })
45
+ if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
46
+ view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })))
47
+ return true
48
+ }
49
+ const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '')
50
+ const inserted = before && !/\s/.test(before) ? ` ${url}` : url
51
+ const tr = state.tr.insertText(inserted, to)
52
+ view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to + inserted.length)).scrollIntoView())
53
+ return true
54
+ },
55
+ },
56
+ }),
57
+ ]
58
+ },
59
+ })
60
+
61
+ /** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */
62
+ export const BoxKit = StarterKit.extend({
63
+ addExtensions() {
64
+ return (this.parent?.() ?? []).map((extension) => (extension.name === 'link' ? extension.extend({ inclusive: () => false }) : extension))
65
+ },
66
+ })
67
+
68
+ /**
69
+ * {@link BoxKit} for a document: the same link, which also keeps `extra` —
70
+ * every key a saved link carries that this version does not know — so a save
71
+ * writes it back. ProseMirror drops an attribute its schema does not name, and
72
+ * the key with it. Protocol's `toEditorDocument(doc, { links: true })` fills it.
73
+ */
74
+ export const DocumentKit = StarterKit.extend({
75
+ addExtensions() {
76
+ return (this.parent?.() ?? []).map((extension) =>
77
+ extension.name === 'link'
78
+ ? (extension as Mark).extend({
79
+ inclusive: () => false,
80
+ addAttributes() {
81
+ return { ...this.parent?.(), extra: { default: null, rendered: false, parseHTML: () => null } }
82
+ },
83
+ })
84
+ : extension,
85
+ )
86
+ },
87
+ })
88
+
89
+ /*
90
+ * A bare address looks like a link while you write it, and a click opens it, as
91
+ * a link in a read page does (Katerina, 30 September: the always-editable
92
+ * description had made its links unclickable). Ship's `LinkDecoration`, moved
93
+ * into the kit with the document editor.
94
+ *
95
+ * A decoration, not a mark: the address is saved as the text it is, byte for
96
+ * byte. The patterns are `RichText`'s, so the editor marks what the reader links.
97
+ */
98
+ const LINK_SPLIT = /\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\)|https?:\/\/[^\s]+/g
99
+ /** Punctuation after a bare address ends the sentence, not the address. */
100
+ const TRAILING = /[.,;:!?)\]]+$/
101
+ /** A link's look in an editor: the package `Link variant="text"`, spelled out for a mark's element and a decoration's range. */
102
+ export const LINK_CLASS = 'text-info-default underline underline-offset-2 cursor-pointer'
103
+
104
+ /** What a click may open: an address a reader may follow (SPEC §13.1), never `javascript:` and the like. */
105
+ const OPENABLE = /^(https?:\/\/|mailto:)/i
106
+
107
+ /** 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. */
108
+ export const LINK_MARK_ATTRIBUTES = { class: LINK_CLASS, 'data-link-mark': '', target: '_blank', rel: 'noopener noreferrer nofollow' }
109
+ /** `[words](url)` names its address in the brackets; a bare address is its own. */
110
+ const LINK_TARGET = /\]\(([^\s)]+)\)$/
111
+
112
+ export const BareLinks = Extension.create({
113
+ name: 'bareLinks',
114
+ addProseMirrorPlugins() {
115
+ return [
116
+ new Plugin({
117
+ key: new PluginKey('bareLinks'),
118
+ props: {
119
+ // The one way a click opens an address: a bare one's decoration, or, while editing, a link on words (read only,
120
+ // the link is a plain anchor and opens itself). Only its own attributes are read — never a chip's — and only an
121
+ // address a reader may follow opens, always without handing the new tab this window.
122
+ handleClick: (view, _pos, event) => {
123
+ if (event.button !== 0) return false
124
+ const target = event.target as HTMLElement | null
125
+ const bare = target?.closest?.('[data-bare-link]')?.getAttribute('data-bare-link')
126
+ const onWords = view.editable ? target?.closest?.('a[data-link-mark]')?.getAttribute('href') : null
127
+ const href = bare ?? onWords
128
+ if (!href || !OPENABLE.test(href)) return false
129
+ window.open(href, '_blank', 'noopener,noreferrer')
130
+ return true
131
+ },
132
+ decorations: ({ doc }) => {
133
+ const found: Decoration[] = []
134
+ doc.descendants((node, pos) => {
135
+ if (!node.isText || !node.text) return
136
+ // A code run is literal, so an address quoted as an example is not a link; one already linked is the mark's.
137
+ if (node.marks.some((mark) => mark.type.name === 'code' || mark.type.name === 'link')) return
138
+ for (const match of node.text.matchAll(LINK_SPLIT)) {
139
+ if (match.index === undefined) continue
140
+ const text = match[0].startsWith('[') ? match[0] : match[0].replace(TRAILING, '')
141
+ const href = text.startsWith('[') ? (LINK_TARGET.exec(text)?.[1] ?? '') : text
142
+ found.push(Decoration.inline(pos + match.index, pos + match.index + text.length, { class: LINK_CLASS, ...(href ? { 'data-bare-link': href } : {}) }))
143
+ }
144
+ })
145
+ return found.length ? DecorationSet.create(doc, found) : null
146
+ },
147
+ },
148
+ }),
149
+ ]
150
+ },
151
+ })
@@ -26,7 +26,7 @@ import { SCHEMA_VERSION, validateRegistry, type Registry, type RegistryEntry } f
26
26
  const root = process.cwd()
27
27
  const registry = buildRegistry({ root })
28
28
  /** Editor extensions: named like components by the catalogue, and not React components. */
29
- const EDITOR_EXTENSIONS = ['KeptSelection', 'BlockId', 'UnknownBlock', 'ReferenceNode', 'AttachmentNode', 'PersonMention', 'UrgentPersonMention', 'CaptionedReference', 'ReferenceTrigger', 'SlashCommands', 'PastedImages', 'PastedMarkdown', 'CodeBlockColours', 'Checklist', 'Callout', 'ReferenceCards', 'LinkChips', 'ReferenceMenu', 'CommentHighlights', 'ComposeKeys']
29
+ const EDITOR_EXTENSIONS = ['KeptSelection', 'BlockId', 'UnknownBlock', 'ReferenceNode', 'AttachmentNode', 'PersonMention', 'UrgentPersonMention', 'PersonReference', 'CaptionedReference', 'ReferenceTrigger', 'SlashCommands', 'PastedImages', 'PastedMarkdown', 'CodeBlockColours', 'Checklist', 'Callout', 'ReferenceCards', 'LinkChips', 'ReferenceMenu', 'CommentHighlights', 'ComposeKeys']
30
30
  const entry = (name: string): RegistryEntry => {
31
31
  const found = registry.entries.find((candidate) => candidate.name === name)
32
32
  if (!found) throw new Error(`no entry for ${name}`)
@@ -48,20 +48,20 @@ describe('the registry builds', () => {
48
48
  expect(registry.entries.map((one) => one.name).sort()).toEqual(values.map((one) => one.name).sort())
49
49
  })
50
50
 
51
- it('counts 204 names over 95 files: 138 components, 63 helpers and 3 hooks (toggleTableHeaderRow, a table’s header row on and off (LEAF-12), on 19 October;EntryShell, the screen while nobody is signed in, moved from Peek (AUT-3), on 17 October; CommentBox with commentBoxRows, and ReactionRow with AddReactionButton and whoReacted, the shared comment box and reaction row (COMM-2), on 17 October; the link widgets — LinkChip, LinkRow, LinkCard, CardUnder, PartCard, LinkPreview and their parts, with useCanHover, chosenOf, loadingShapeOf and unavailableMemory — from the Widgets 2 prototype, on 16 October; InlineText, a title or the line under it edited where it stands (SUM-4), on 16 October; ComposeBox with ComposeKeys and its classes, CommentHighlights with its five helpers, and keepSelection and releaseSelection, from the Leaf prototype (LEAF-4), on 16 October;NavTree, NavTreeSection, the composer triggers and UnreadDot joined on 2 October; BlockHandle and EditorBlockHandle (RIC-18) on 2 October, moveBlock and blockDropCursor, the drop in the gutter, on 5 October, MembersPill and MembersDialog, moved from Peek (SHI-31), on 6 October, ShowMore on 7 October, AppProvider on 8 October, and KindIcon, thingKindOf and PastedImages with its two helpers, moved from Peek, on 8 October; CodeBlockColours, the coloured code block of the editor, on 9 October; Checklist, Callout, isChecklistTick and calloutLook (RIC-19) on 13 October; EditorTableControls and its four actions (RIC-21) on 13 October; ReferenceCards, useReferenceCards and its three helpers, the card a chip in a document asks for, on 14 October; LinkChips and its two helpers, a URL in a document read as its chip, on 14 October; ReferenceMenu, ReferenceMenuView and three helpers, the menu of a chip while writing, on 14 October; PastedMarkdown, markdown pasted as the blocks it spells (LEAF-10), on 15 October; turnIntoRows, turnListInto and turnQuoteInto, the block menu’s Turn into for a list and a quote (LEAF-11), on 15 October)', () => {
51
+ it('counts 206 names over 96 files: 140 components, 63 helpers and 3 hooks (DocumentEditor, one document editor for every app, and PersonReference, `@` in a document (WBD-3), on 20 October; toggleTableHeaderRow, a table’s header row on and off (LEAF-12), on 19 October;EntryShell, the screen while nobody is signed in, moved from Peek (AUT-3), on 17 October; CommentBox with commentBoxRows, and ReactionRow with AddReactionButton and whoReacted, the shared comment box and reaction row (COMM-2), on 17 October; the link widgets — LinkChip, LinkRow, LinkCard, CardUnder, PartCard, LinkPreview and their parts, with useCanHover, chosenOf, loadingShapeOf and unavailableMemory — from the Widgets 2 prototype, on 16 October; InlineText, a title or the line under it edited where it stands (SUM-4), on 16 October; ComposeBox with ComposeKeys and its classes, CommentHighlights with its five helpers, and keepSelection and releaseSelection, from the Leaf prototype (LEAF-4), on 16 October;NavTree, NavTreeSection, the composer triggers and UnreadDot joined on 2 October; BlockHandle and EditorBlockHandle (RIC-18) on 2 October, moveBlock and blockDropCursor, the drop in the gutter, on 5 October, MembersPill and MembersDialog, moved from Peek (SHI-31), on 6 October, ShowMore on 7 October, AppProvider on 8 October, and KindIcon, thingKindOf and PastedImages with its two helpers, moved from Peek, on 8 October; CodeBlockColours, the coloured code block of the editor, on 9 October; Checklist, Callout, isChecklistTick and calloutLook (RIC-19) on 13 October; EditorTableControls and its four actions (RIC-21) on 13 October; ReferenceCards, useReferenceCards and its three helpers, the card a chip in a document asks for, on 14 October; LinkChips and its two helpers, a URL in a document read as its chip, on 14 October; ReferenceMenu, ReferenceMenuView and three helpers, the menu of a chip while writing, on 14 October; PastedMarkdown, markdown pasted as the blocks it spells (LEAF-10), on 15 October; turnIntoRows, turnListInto and turnQuoteInto, the block menu’s Turn into for a list and a quote (LEAF-11), on 15 October)', () => {
52
52
  // The reconciliation GATES.md §24 explains. If this changes, that changes.
53
53
  // The `EDITOR_EXTENSIONS` count as components by their names; they are
54
54
  // editor extensions, documented on SelectionToolbar's, BlockNodes' and
55
55
  // ComposerTriggers' pages.
56
56
  const kinds = registry.entries.reduce<Record<string, number>>((all, one) => ({ ...all, [one.kind]: (all[one.kind] ?? 0) + 1 }), {})
57
- expect(kinds).toEqual({ component: 138, helper: 63, hook: 3 })
58
- expect(new Set(registry.entries.map((one) => one.sourceFile)).size).toBe(95)
57
+ expect(kinds).toEqual({ component: 140, helper: 63, hook: 3 })
58
+ expect(new Set(registry.entries.map((one) => one.sourceFile)).size).toBe(96)
59
59
  })
60
60
 
61
61
  it('gives every entry a purpose, from its own page or from the comment above it', () => {
62
62
  expect(registry.entries.filter((one) => one.purpose.trim() === '')).toEqual([])
63
- expect(registry.entries.filter((one) => one.purposeFrom === 'page').length).toBe(89)
64
- expect(registry.entries.filter((one) => one.purposeFrom === 'comment').length).toBe(115)
63
+ expect(registry.entries.filter((one) => one.purposeFrom === 'page').length).toBe(90)
64
+ expect(registry.entries.filter((one) => one.purposeFrom === 'comment').length).toBe(116)
65
65
  })
66
66
 
67
67
  it('takes a name with a page of its own from the page, and a name without one from the code', () => {
@@ -72,6 +72,7 @@ fork freely, owe nothing back, mention it on the package's ticket.
72
72
  | A list that opens as you type in an editor — `/` for commands, `@` for people | **SuggestionMenu** — the editor keeps the caret and hands it the arrow keys; `suggestionPopup` from `@estiva-app/ui/editor` wires it to a Tiptap plugin |
73
73
  | Bold, italic and the like over selected text in an editor | **SelectionToolbar**, from `@estiva-app/ui/editor` — it follows the selection by itself |
74
74
  | A composer's `@`, `!@`, `[` and `/` — mention a person, reference something, format or insert | **ComposerTriggers** — `PersonMention`, `UrgentPersonMention`, `CaptionedReference`, `ReferenceTrigger` and `SlashCommands` from `@estiva-app/ui/editor`; the app passes its people, its items and its own `/` rows |
75
+ | A document's text, written where it is read, in any app | **DocumentEditor**, from `@estiva-app/ui/editor` — `/`, `[`, `@`, links on words, files, saving when you leave, someone else's save and held typing; the app supplies its codec, its lists, its upload and its views |
75
76
  | An editor that saves a block document and must keep its block ids | **BlockNodes** — `BlockId`, `UnknownBlock`, `ReferenceNode` and `AttachmentNode` from `@estiva-app/ui/editor`, beside StarterKit and TableKit |
76
77
  | A page's title or the line under it, edited where it stands, as in a document | **InlineText**, from `@estiva-app/ui/editor` — no box; Enter saves and moves on |
77
78
  | A comment, a reply or a line written and sent, in any app | **CommentBox**, from `@estiva-app/ui/editor` — triggers, keys, drafts, files, editing and a refused send; the app supplies its people, its `[` sections, its `/` rows and a send |