@whity/ui 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +107 -3
  2. package/package.json +192 -6
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +302 -0
  6. package/src/actor-chip.tsx +71 -0
  7. package/src/agent-activity.tsx +163 -0
  8. package/src/agent-collaboration.stories.tsx +156 -0
  9. package/src/agent-run-status.tsx +196 -0
  10. package/src/alert-dialog.stories.tsx +45 -0
  11. package/src/alert-dialog.tsx +147 -0
  12. package/src/alert.stories.tsx +91 -0
  13. package/src/alert.tsx +89 -0
  14. package/src/app-sidebar.stories.tsx +195 -0
  15. package/src/app-sidebar.tsx +500 -0
  16. package/src/approval-queue.tsx +108 -0
  17. package/src/audience-group-picker.stories.tsx +198 -0
  18. package/src/audience-group-picker.tsx +362 -0
  19. package/src/audience-people-picker.stories.tsx +102 -0
  20. package/src/audience-people-picker.tsx +279 -0
  21. package/src/avatar.tsx +83 -0
  22. package/src/badge.stories.tsx +105 -0
  23. package/src/badge.tsx +68 -0
  24. package/src/beta-warning.stories.tsx +79 -0
  25. package/src/beta-warning.tsx +189 -0
  26. package/src/bilingual-input.stories.tsx +82 -0
  27. package/src/bilingual-input.tsx +183 -0
  28. package/src/breadcrumb.stories.tsx +51 -0
  29. package/src/breadcrumb.tsx +90 -0
  30. package/src/button.stories.tsx +87 -0
  31. package/src/button.tsx +118 -0
  32. package/src/card.stories.tsx +423 -0
  33. package/src/card.tsx +180 -0
  34. package/src/chart.stories.tsx +66 -0
  35. package/src/chart.tsx +228 -0
  36. package/src/checkbox.stories.tsx +62 -0
  37. package/src/checkbox.tsx +54 -0
  38. package/src/collapsible.stories.tsx +48 -0
  39. package/src/collapsible.tsx +34 -0
  40. package/src/color-card.stories.tsx +61 -0
  41. package/src/color-card.tsx +270 -0
  42. package/src/color-picker.stories.tsx +65 -0
  43. package/src/color-picker.tsx +425 -0
  44. package/src/command-palette.tsx +306 -0
  45. package/src/copy-block.stories.tsx +38 -0
  46. package/src/copy-block.tsx +85 -0
  47. package/src/data-table.stories.tsx +200 -0
  48. package/src/data-table.tsx +1106 -0
  49. package/src/date-picker.stories.tsx +61 -0
  50. package/src/date-picker.tsx +422 -0
  51. package/src/design-cards.stories.tsx +458 -0
  52. package/src/dialog.stories.tsx +48 -0
  53. package/src/dialog.tsx +166 -0
  54. package/src/documents/barcode-svg.stories.tsx +72 -0
  55. package/src/documents/barcode-svg.tsx +79 -0
  56. package/src/dropdown-menu.stories.tsx +77 -0
  57. package/src/dropdown-menu.tsx +271 -0
  58. package/src/editor/behaviour.ts +279 -0
  59. package/src/editor/block-ids.ts +44 -0
  60. package/src/editor/block-list.tsx +101 -0
  61. package/src/editor/block-toolbar.tsx +477 -0
  62. package/src/editor/bubble.tsx +93 -0
  63. package/src/editor/catalogue.ts +103 -0
  64. package/src/editor/collab-rail.tsx +746 -0
  65. package/src/editor/collab.stories.tsx +207 -0
  66. package/src/editor/collab.ts +87 -0
  67. package/src/editor/contract.ts +408 -0
  68. package/src/editor/convert.ts +362 -0
  69. package/src/editor/doc-editor.stories.tsx +98 -0
  70. package/src/editor/doc-editor.tsx +1287 -0
  71. package/src/editor/editor.css +536 -0
  72. package/src/editor/extensions.ts +86 -0
  73. package/src/editor/field-picker.tsx +107 -0
  74. package/src/editor/fields.ts +100 -0
  75. package/src/editor/gutter.tsx +367 -0
  76. package/src/editor/index.ts +22 -0
  77. package/src/editor/label-sheet.tsx +289 -0
  78. package/src/editor/labels.ts +310 -0
  79. package/src/editor/link-tools.tsx +141 -0
  80. package/src/editor/node-views.tsx +450 -0
  81. package/src/editor/page-view.tsx +353 -0
  82. package/src/editor/publish-check.tsx +182 -0
  83. package/src/editor/rich-blocks.stories.tsx +146 -0
  84. package/src/editor/sample.ts +40 -0
  85. package/src/editor/schema-rich.ts +150 -0
  86. package/src/editor/schema.ts +315 -0
  87. package/src/editor/services.tsx +127 -0
  88. package/src/editor/slash.ts +64 -0
  89. package/src/editor/suggesting.ts +372 -0
  90. package/src/editor/suggestions.ts +763 -0
  91. package/src/editor/table-keys.ts +66 -0
  92. package/src/editor/templates.stories.tsx +324 -0
  93. package/src/editor/toolbar.tsx +358 -0
  94. package/src/empty-state.stories.tsx +51 -0
  95. package/src/empty-state.tsx +100 -0
  96. package/src/empty-state.usage-notes.md +30 -0
  97. package/src/form.stories.tsx +112 -0
  98. package/src/form.tsx +176 -0
  99. package/src/globals.css +20 -0
  100. package/src/icon-button.tsx +85 -0
  101. package/src/icon-map.ts +244 -0
  102. package/src/icon.tsx +41 -0
  103. package/src/index.ts +67 -0
  104. package/src/input.stories.tsx +157 -0
  105. package/src/input.tsx +759 -0
  106. package/src/locked-screen.stories.tsx +29 -0
  107. package/src/locked-screen.tsx +61 -0
  108. package/src/mark.tsx +62 -0
  109. package/src/math-text.stories.tsx +33 -0
  110. package/src/math-text.tsx +43 -0
  111. package/src/menu-bar.stories.tsx +198 -0
  112. package/src/menu-bar.tsx +373 -0
  113. package/src/money/currency.ts +230 -0
  114. package/src/page-header.stories.tsx +95 -0
  115. package/src/page-header.tsx +122 -0
  116. package/src/page-shell.stories.tsx +42 -0
  117. package/src/page-shell.tsx +32 -0
  118. package/src/pagination.stories.tsx +45 -0
  119. package/src/pagination.tsx +98 -0
  120. package/src/plugin-card.stories.tsx +180 -0
  121. package/src/plugin-card.tsx +848 -0
  122. package/src/popover.stories.tsx +48 -0
  123. package/src/popover.tsx +55 -0
  124. package/src/radio-group.stories.tsx +26 -0
  125. package/src/radio-group.tsx +44 -0
  126. package/src/route-flow/editor.tsx +1014 -0
  127. package/src/route-flow/model.ts +716 -0
  128. package/src/scope-grant.tsx +139 -0
  129. package/src/screen-too-small.stories.tsx +61 -0
  130. package/src/screen-too-small.tsx +104 -0
  131. package/src/select.stories.tsx +44 -0
  132. package/src/select.tsx +197 -0
  133. package/src/separator.stories.tsx +34 -0
  134. package/src/separator.tsx +34 -0
  135. package/src/sheet.stories.tsx +49 -0
  136. package/src/sheet.tsx +168 -0
  137. package/src/skeleton.stories.tsx +28 -0
  138. package/src/skeleton.tsx +19 -0
  139. package/src/slider.stories.tsx +78 -0
  140. package/src/slider.tsx +300 -0
  141. package/src/spinner.stories.tsx +33 -0
  142. package/src/spinner.tsx +55 -0
  143. package/src/switch.stories.tsx +42 -0
  144. package/src/switch.tsx +41 -0
  145. package/src/switcher.stories.tsx +111 -0
  146. package/src/switcher.tsx +131 -0
  147. package/src/table.stories.tsx +48 -0
  148. package/src/table.tsx +121 -0
  149. package/src/tabs.stories.tsx +74 -0
  150. package/src/tabs.tsx +90 -0
  151. package/src/tag-input.stories.tsx +67 -0
  152. package/src/tag-input.tsx +117 -0
  153. package/src/tenant-logo.tsx +63 -0
  154. package/src/tenant-switcher.stories.tsx +38 -0
  155. package/src/tenant-switcher.tsx +164 -0
  156. package/src/textarea.stories.tsx +27 -0
  157. package/src/textarea.tsx +18 -0
  158. package/src/theme-mode.ts +52 -0
  159. package/src/time-picker.stories.tsx +62 -0
  160. package/src/time-picker.tsx +615 -0
  161. package/src/toggle-group.tsx +138 -0
  162. package/src/tooltip.stories.tsx +43 -0
  163. package/src/tooltip.tsx +73 -0
  164. package/src/top-nav.stories.tsx +58 -0
  165. package/src/top-nav.tsx +324 -0
  166. package/src/undo-bar.tsx +107 -0
  167. package/src/utils.ts +45 -0
  168. package/src/view-toggle.stories.tsx +84 -0
  169. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,279 @@
1
+ import {
2
+ Extension,
3
+ InputRule,
4
+ markInputRule,
5
+ nodeInputRule,
6
+ type Editor,
7
+ } from "@tiptap/core"
8
+ import type { NodeType, Node as PmNode } from "@tiptap/pm/model"
9
+ import { NodeSelection, Plugin, PluginKey, TextSelection } from "@tiptap/pm/state"
10
+ import { Decoration, DecorationSet } from "@tiptap/pm/view"
11
+
12
+ /**
13
+ * Editing behaviour for the document schema (schema.ts): flat lists with
14
+ * levels, Markdown shortcuts (E.28; ⌘Z straight after one turns it back into
15
+ * what was typed), Google Docs shortcuts, and moving blocks from the keyboard.
16
+ */
17
+
18
+ const LIST_TYPES = new Set(["listItem", "checkItem"])
19
+ const MAX_LEVEL = 2
20
+
21
+ /** The top-level block holding the selection: its node, position and index. */
22
+ export function currentBlock(editor: Editor): { node: PmNode; pos: number; index: number } | null {
23
+ const { $from } = editor.state.selection
24
+ if ($from.depth < 1) {
25
+ const node = editor.state.doc.nodeAt($from.pos)
26
+ return node ? { node, pos: $from.pos, index: $from.index(0) } : null
27
+ }
28
+ return { node: $from.node(1), pos: $from.before(1), index: $from.index(0) }
29
+ }
30
+
31
+ /** Move the block holding the selection one place up (-1) or down (+1). */
32
+ export function moveBlock(editor: Editor, dir: -1 | 1): boolean {
33
+ const block = currentBlock(editor)
34
+ if (!block) return false
35
+ const { doc } = editor.state
36
+ const target = block.index + dir
37
+ if (target < 0 || target >= doc.childCount) return false
38
+ const { node, pos } = block
39
+ const offset = editor.state.selection.from - pos
40
+ const tr = editor.state.tr.delete(pos, pos + node.nodeSize)
41
+ let insertAt = 0
42
+ for (let i = 0; i < target; i++) insertAt += tr.doc.child(i).nodeSize
43
+ tr.insert(insertAt, node)
44
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(insertAt + offset, tr.doc.content.size))))
45
+ editor.view.dispatch(tr.scrollIntoView())
46
+ return true
47
+ }
48
+
49
+ /** Put a copy of the current block right after it; the copy gets a new id. */
50
+ export function duplicateBlock(editor: Editor, pos?: number): boolean {
51
+ const at = pos ?? currentBlock(editor)?.pos
52
+ if (at === undefined) return false
53
+ const node = editor.state.doc.nodeAt(at)
54
+ if (!node) return false
55
+ const copy = node.type.create({ ...node.attrs, id: null }, node.content, node.marks)
56
+ editor.view.dispatch(editor.state.tr.insert(at + node.nodeSize, copy).scrollIntoView())
57
+ return true
58
+ }
59
+
60
+ /** Delete the block at `pos` (or the current one). */
61
+ export function deleteBlock(editor: Editor, pos?: number): boolean {
62
+ const at = pos ?? currentBlock(editor)?.pos
63
+ if (at === undefined) return false
64
+ const node = editor.state.doc.nodeAt(at)
65
+ if (!node) return false
66
+ const tr = editor.state.tr.delete(at, at + node.nodeSize)
67
+ if (tr.doc.childCount === 0) tr.insert(0, editor.schema.nodes.paragraph.create())
68
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(at, tr.doc.content.size))))
69
+ editor.view.dispatch(tr.scrollIntoView())
70
+ return true
71
+ }
72
+
73
+ /** Move the block at `from` (a position) to be the `index`-th block. */
74
+ export function moveBlockTo(editor: Editor, from: number, index: number): boolean {
75
+ const node = editor.state.doc.nodeAt(from)
76
+ if (!node) return false
77
+ const tr = editor.state.tr.delete(from, from + node.nodeSize)
78
+ const target = Math.max(0, Math.min(index, tr.doc.childCount))
79
+ let insertAt = 0
80
+ for (let i = 0; i < target; i++) insertAt += tr.doc.child(i).nodeSize
81
+ tr.insert(insertAt, node)
82
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(insertAt + 1, tr.doc.content.size))))
83
+ editor.view.dispatch(tr.scrollIntoView())
84
+ return true
85
+ }
86
+
87
+ /** Turn the current block into another text block type, keeping its id and content. */
88
+ export function turnInto(editor: Editor, type: string, attrs: Record<string, unknown> = {}): boolean {
89
+ const block = currentBlock(editor)
90
+ if (!block) return false
91
+ return editor.chain().focus().setNode(type, { id: block.node.attrs.id, ...attrs }).run()
92
+ }
93
+
94
+ function setLevel(editor: Editor, delta: 1 | -1): boolean {
95
+ const block = currentBlock(editor)
96
+ if (!block || !LIST_TYPES.has(block.node.type.name)) return false
97
+ const level = Math.max(0, Math.min(MAX_LEVEL, Number(block.node.attrs.level) + delta))
98
+ if (level === block.node.attrs.level) return true
99
+ editor.view.dispatch(editor.state.tr.setNodeMarkup(block.pos, undefined, { ...block.node.attrs, level }))
100
+ return true
101
+ }
102
+
103
+ /* --------------------------------------------------- list numbering */
104
+
105
+ const ALPHA = "abcdefghijklmnopqrstuvwxyz"
106
+ const ROMAN = ["i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii"]
107
+ const BULLETS = ["•", "◦", "▪"]
108
+
109
+ function numberLabel(n: number, level: number): string {
110
+ if (level === 1) return `${ALPHA[(n - 1) % 26]}.`
111
+ if (level === 2) return `${ROMAN[(n - 1) % ROMAN.length] ?? n}.`
112
+ return `${n}.`
113
+ }
114
+
115
+ /** The markers of flat list items. Numbering restarts after any other block. */
116
+ export function listMarkers(doc: PmNode): Map<number, string> {
117
+ const markers = new Map<number, string>()
118
+ let counters = [0, 0, 0]
119
+ doc.forEach((node, pos) => {
120
+ if (node.type.name !== "listItem" || node.attrs.kind !== "number") {
121
+ counters = [0, 0, 0]
122
+ if (node.type.name === "listItem") markers.set(pos, BULLETS[Number(node.attrs.level)] ?? "•")
123
+ return
124
+ }
125
+ const level = Number(node.attrs.level)
126
+ counters[level] += 1
127
+ for (let l = level + 1; l <= MAX_LEVEL; l++) counters[l] = 0
128
+ markers.set(pos, numberLabel(counters[level], level))
129
+ })
130
+ return markers
131
+ }
132
+
133
+ const listMarkerPlugin = new Plugin({
134
+ key: new PluginKey("listMarkers"),
135
+ props: {
136
+ decorations(state) {
137
+ const decos: Decoration[] = []
138
+ for (const [pos, marker] of listMarkers(state.doc)) {
139
+ const node = state.doc.nodeAt(pos)
140
+ if (node) decos.push(Decoration.node(pos, pos + node.nodeSize, { "data-marker": marker }))
141
+ }
142
+ return DecorationSet.create(state.doc, decos)
143
+ },
144
+ },
145
+ })
146
+
147
+ /**
148
+ * A Markdown block shortcut at the start of a line: like TipTap's
149
+ * textblockTypeInputRule, but the block keeps its id (BlockId is stable).
150
+ */
151
+ function blockRule(
152
+ find: RegExp,
153
+ type: NodeType,
154
+ attrs: Record<string, unknown> | ((match: RegExpMatchArray) => Record<string, unknown>) = {}
155
+ ): InputRule {
156
+ return new InputRule({
157
+ find,
158
+ handler: ({ state, range, match }) => {
159
+ const $start = state.doc.resolve(range.from)
160
+ if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), type)) return null
161
+ const extra = typeof attrs === "function" ? attrs(match) : attrs
162
+ state.tr
163
+ .delete(range.from, range.to)
164
+ .setBlockType(range.from, range.from, type, { ...extra, id: $start.parent.attrs.id ?? null })
165
+ },
166
+ })
167
+ }
168
+
169
+ /* ------------------------------------------------------- the extension */
170
+
171
+ export const DocumentBehaviour = Extension.create<{ onBlockMenu: (pos: number) => void }>({
172
+ name: "documentBehaviour",
173
+
174
+ addOptions: () => ({ onBlockMenu: () => {} }),
175
+
176
+ addProseMirrorPlugins() {
177
+ return [listMarkerPlugin]
178
+ },
179
+
180
+ addInputRules() {
181
+ const s = this.editor.schema
182
+ const n = s.nodes
183
+ const m = s.marks
184
+ return [
185
+ blockRule(/^#\s$/, n.heading, { level: 1 }),
186
+ blockRule(/^##\s$/, n.heading, { level: 2 }),
187
+ blockRule(/^###\s$/, n.heading, { level: 3 }),
188
+ blockRule(/^[-*]\s$/, n.listItem, { kind: "bullet", level: 0 }),
189
+ blockRule(/^1[.)]\s$/, n.listItem, { kind: "number", level: 0 }),
190
+ blockRule(/^\[ ?\]\s$/, n.checkItem, { level: 0, checked: false }),
191
+ blockRule(/^>\s$/, n.quote),
192
+ blockRule(/^```([a-z0-9-]*)[\s\n]$/, n.codeBlock, (match) => ({ language: match[1] || null })),
193
+ nodeInputRule({ find: /^(?:---|—-|___)$/, type: n.divider }),
194
+ markInputRule({ find: /(?:^|\s)(\*\*(?!\s)([^*]+)(?<!\s)\*\*)$/, type: m.bold }),
195
+ markInputRule({ find: /(?:^|\s)(_(?!\s)([^_]+)(?<!\s)_)$/, type: m.italic }),
196
+ markInputRule({ find: /(?:^|\s)(`(?!\s)([^`]+)(?<!\s)`)$/, type: m.code }),
197
+ markInputRule({ find: /(?:^|\s)(~~(?!\s)([^~]+)(?<!\s)~~)$/, type: m.strike }),
198
+ markInputRule({ find: /(?:^|\s)(==(?!\s)([^=]+)(?<!\s)==)$/, type: m.highlight }),
199
+ ]
200
+ },
201
+
202
+ addKeyboardShortcuts() {
203
+ const editor = this.editor
204
+ const toggleMark = (name: string) => () => editor.chain().focus().toggleMark(name).run()
205
+ const listToggle = (type: string, attrs: Record<string, unknown>) => () => {
206
+ const block = currentBlock(editor)
207
+ const on = block?.node.type.name === type && (type !== "listItem" || block.node.attrs.kind === attrs.kind)
208
+ return on ? turnInto(editor, "paragraph") : turnInto(editor, type, { level: 0, ...attrs })
209
+ }
210
+ return {
211
+ // E.28: straight after a Markdown shortcut, ⌘Z turns it back into what was typed.
212
+ "Mod-z": () => editor.commands.undoInputRule() || editor.commands.undo(),
213
+ "Mod-Shift-z": () => editor.commands.redo(),
214
+ "Mod-y": () => editor.commands.redo(),
215
+ "Mod-b": toggleMark("bold"),
216
+ "Mod-i": toggleMark("italic"),
217
+ "Mod-u": toggleMark("underline"),
218
+ "Mod-Shift-x": toggleMark("strike"),
219
+ "Mod-e": toggleMark("code"),
220
+ "Mod-Shift-h": toggleMark("highlight"),
221
+ "Mod-Alt-0": () => turnInto(editor, "paragraph"),
222
+ "Mod-Alt-1": () => turnInto(editor, "heading", { level: 1 }),
223
+ "Mod-Alt-2": () => turnInto(editor, "heading", { level: 2 }),
224
+ "Mod-Alt-3": () => turnInto(editor, "heading", { level: 3 }),
225
+ "Mod-Shift-8": listToggle("listItem", { kind: "bullet" }),
226
+ "Mod-Shift-7": listToggle("listItem", { kind: "number" }),
227
+ "Mod-Shift-9": listToggle("checkItem", { checked: false }),
228
+ "Mod-d": () => duplicateBlock(editor),
229
+ // Esc selects the whole block; Enter on a selected block opens its menu (EditorBlockChrome).
230
+ Escape: () => {
231
+ const block = currentBlock(editor)
232
+ if (!block || editor.state.selection instanceof NodeSelection) return false
233
+ editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, block.pos)))
234
+ return true
235
+ },
236
+ "Alt-Shift-ArrowUp": () => moveBlock(editor, -1),
237
+ "Alt-Shift-ArrowDown": () => moveBlock(editor, 1),
238
+ Tab: () => setLevel(editor, 1),
239
+ "Shift-Tab": () => setLevel(editor, -1),
240
+ Enter: () => {
241
+ const sel = editor.state.selection
242
+ if (sel instanceof NodeSelection && sel.$from.depth === 0) {
243
+ this.options.onBlockMenu(sel.from)
244
+ return true
245
+ }
246
+ const block = currentBlock(editor)
247
+ if (!block || !LIST_TYPES.has(block.node.type.name) || !editor.state.selection.empty) return false
248
+ if (block.node.content.size === 0) {
249
+ // An empty item steps out a level, then out of the list.
250
+ if (Number(block.node.attrs.level) > 0) return setLevel(editor, -1)
251
+ return turnInto(editor, "paragraph")
252
+ }
253
+ const { kind, level } = block.node.attrs
254
+ return editor
255
+ .chain()
256
+ .splitBlock()
257
+ .command(({ tr, state }) => {
258
+ const pos = state.selection.$from.before(1)
259
+ const type = block.node.type
260
+ const attrs = type.name === "checkItem" ? { level, checked: false } : { kind, level }
261
+ tr.setNodeMarkup(pos, type, { ...attrs, id: null, suggestion: null })
262
+ return true
263
+ })
264
+ .run()
265
+ },
266
+ Backspace: () => {
267
+ const { selection } = editor.state
268
+ const block = currentBlock(editor)
269
+ if (!block || !selection.empty || selection.$from.parentOffset !== 0) return false
270
+ const name = block.node.type.name
271
+ // At the start of a list item, heading, quote or code block, Backspace makes it text first.
272
+ if (LIST_TYPES.has(name) || name === "heading" || name === "quote" || name === "codeBlock") {
273
+ return turnInto(editor, "paragraph")
274
+ }
275
+ return false
276
+ },
277
+ }
278
+ },
279
+ })
@@ -0,0 +1,44 @@
1
+ import { Extension } from "@tiptap/core"
2
+ import { Plugin, PluginKey, type Transaction } from "@tiptap/pm/state"
3
+
4
+ /** A short random id, unique within a document (BlockId in the contract). */
5
+ export function newBlockId(): string {
6
+ const bytes = new Uint8Array(9)
7
+ crypto.getRandomValues(bytes)
8
+ return Array.from(bytes, (b) => "abcdefghijklmnopqrstuvwxyz0123456789"[b % 36]).join("")
9
+ }
10
+
11
+ /**
12
+ * Every block, nested ones included, keeps a stable, unique `id`: a new block (typed,
13
+ * split, pasted or duplicated) gets a fresh one, and a duplicate of an
14
+ * existing id is renamed, the first occurrence keeping it.
15
+ */
16
+ export const BlockIds = Extension.create({
17
+ name: "blockIds",
18
+ addProseMirrorPlugins() {
19
+ return [
20
+ new Plugin({
21
+ key: new PluginKey("blockIds"),
22
+ appendTransaction: (transactions, _old, state) => {
23
+ if (!transactions.some((t) => t.docChanged)) return null
24
+ const seen = new Set<string>()
25
+ let tr: Transaction | null = null
26
+ // Every block, including those inside toggles and columns, has a document-wide unique id.
27
+ state.doc.descendants((node, pos) => {
28
+ if (!("id" in node.attrs)) return
29
+ const id = node.attrs.id as string | null
30
+ if (id && !seen.has(id)) {
31
+ seen.add(id)
32
+ return
33
+ }
34
+ const fresh = newBlockId()
35
+ seen.add(fresh)
36
+ tr = (tr ?? state.tr).setNodeMarkup(pos, undefined, { ...node.attrs, id: fresh })
37
+ })
38
+ // Id bookkeeping isn't an edit: it never becomes its own undo step.
39
+ return tr ? (tr as Transaction).setMeta("addToHistory", false) : null
40
+ },
41
+ }),
42
+ ]
43
+ },
44
+ })
@@ -0,0 +1,101 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { Icon } from "../icon"
6
+ import { cn } from "../utils"
7
+ import type { CatalogueItem } from "./catalogue"
8
+ import type { EditorLabels } from "./labels"
9
+
10
+ /**
11
+ * The grouped block list the / menu and the + inserter share (EditorInsert,
12
+ * `.wy-slash`): an icon tile, the name, a one-line hint and the Markdown
13
+ * shortcut; the active row is on the tint.
14
+ */
15
+ function BlockList({
16
+ items,
17
+ active,
18
+ onActive,
19
+ onPick,
20
+ labels,
21
+ footer,
22
+ search,
23
+ id,
24
+ }: {
25
+ items: CatalogueItem[]
26
+ active: number
27
+ onActive: (index: number) => void
28
+ onPick: (item: CatalogueItem) => void
29
+ labels: EditorLabels
30
+ /** The hints along the bottom. */
31
+ footer: React.ReactNode
32
+ /** The + inserter's search box. */
33
+ search?: React.ReactNode
34
+ id: string
35
+ }) {
36
+ const listRef = React.useRef<HTMLDivElement>(null)
37
+ React.useEffect(() => {
38
+ listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" })
39
+ }, [active])
40
+
41
+ let lastGroup = ""
42
+ return (
43
+ <div
44
+ data-slot="block-list"
45
+ className="grid w-[320px] gap-0.5 rounded-lg border border-border bg-popover p-1 text-sm text-popover-foreground shadow-float"
46
+ >
47
+ {search}
48
+ <div ref={listRef} id={id} role="listbox" aria-label={labels.insert} className="grid max-h-[320px] gap-0.5 overflow-y-auto">
49
+ {items.length === 0 && <div className="px-2 py-3 text-muted-foreground">{labels.noBlocks}</div>}
50
+ {items.map((item, index) => {
51
+ const heading = item.group !== lastGroup ? labels[item.group] : null
52
+ lastGroup = item.group
53
+ const on = index === active
54
+ return (
55
+ <React.Fragment key={item.id}>
56
+ {heading && (
57
+ <div role="presentation" className="px-2 pt-1.5 pb-0.5 text-xs font-medium text-muted-foreground">
58
+ {heading}
59
+ </div>
60
+ )}
61
+ <div
62
+ role="option"
63
+ id={`${id}-${item.id}`}
64
+ aria-selected={on}
65
+ data-index={index}
66
+ onMouseDown={(e) => e.preventDefault()}
67
+ onMouseMove={() => onActive(index)}
68
+ onClick={() => onPick(item)}
69
+ className={cn(
70
+ "flex min-h-10 cursor-pointer items-center gap-2.5 rounded-control py-1 ps-1 pe-2",
71
+ on && "bg-primary-tint text-primary-tint-foreground"
72
+ )}
73
+ >
74
+ <span
75
+ className={cn(
76
+ "grid size-8 shrink-0 place-items-center rounded-[8px] border border-border bg-card text-foreground",
77
+ on && "border-[color-mix(in_oklab,var(--primary)_40%,var(--border))] text-primary-tint-foreground"
78
+ )}
79
+ >
80
+ <Icon name={item.icon} />
81
+ </span>
82
+ <span className="grid min-w-0 flex-1 leading-[1.3]">
83
+ {labels[item.label]}
84
+ <span className={cn("truncate text-xs text-muted-foreground", on && "text-current opacity-80")}>
85
+ {labels[item.hint]}
86
+ </span>
87
+ </span>
88
+ {item.markdown && <span className="font-mono text-2xs text-muted-foreground">{item.markdown}</span>}
89
+ </div>
90
+ </React.Fragment>
91
+ )
92
+ })}
93
+ </div>
94
+ <div className="-mx-1 -mb-1 mt-0.5 flex gap-3 border-t border-border px-2 pt-1.5 pb-1 text-2xs text-muted-foreground">
95
+ {footer}
96
+ </div>
97
+ </div>
98
+ )
99
+ }
100
+
101
+ export { BlockList }