@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,477 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import type { Editor } from "@tiptap/core"
5
+ import type { Node as PmNode } from "@tiptap/pm/model"
6
+ import { NodeSelection, TextSelection } from "@tiptap/pm/state"
7
+ import { useEditorState } from "@tiptap/react"
8
+
9
+ import { Button } from "../button"
10
+ import { IconButton } from "../icon-button"
11
+ import { ToggleGroup } from "../toggle-group"
12
+ import { cn } from "../utils"
13
+ import type { Inline } from "./contract"
14
+ import { deleteBlock } from "./behaviour"
15
+ import { fill, type EditorLabels } from "./labels"
16
+ import { inlineText, textToInline, useEditorServices } from "./services"
17
+
18
+ const RICH = new Set(["callout", "table", "image", "file", "record", "chart", "signature", "barcode", "qr", "math"])
19
+
20
+ /** The rich block the selection is on or in: its node and position. */
21
+ function selectedRich(editor: Editor): { node: PmNode; pos: number } | null {
22
+ const sel = editor.state.selection
23
+ if (sel instanceof NodeSelection && RICH.has(sel.node.type.name)) return { node: sel.node, pos: sel.from }
24
+ const { $from } = sel
25
+ for (let d = $from.depth; d > 0; d--) {
26
+ const node = $from.node(d)
27
+ if (node.type.name === "table" || node.type.name === "callout") return { node, pos: $from.before(d) }
28
+ }
29
+ return null
30
+ }
31
+
32
+ function Sep() {
33
+ return <span aria-hidden="true" className="mx-[3px] h-[18px] w-px bg-border" />
34
+ }
35
+
36
+ /** A labelled text field the toolbar opens for one attribute; Enter keeps it, Esc leaves it. */
37
+ function FieldRow({ label, value, onDone, onCancel, mono }: { label: string; value: string; onDone: (v: string) => void; onCancel: () => void; mono?: boolean }) {
38
+ const [text, setText] = React.useState(value)
39
+ const ref = React.useRef<HTMLInputElement>(null)
40
+ React.useEffect(() => ref.current?.focus(), [])
41
+ const { labels } = useEditorServices()
42
+ return (
43
+ <div className="flex items-center gap-1.5 border-t border-border pt-1">
44
+ <label className="flex flex-1 items-center gap-2 text-[0.8125rem] text-muted-foreground">
45
+ {label}
46
+ <input
47
+ ref={ref}
48
+ value={text}
49
+ dir="auto"
50
+ onChange={(e) => setText(e.target.value)}
51
+ onKeyDown={(e) => {
52
+ if (e.key === "Enter") {
53
+ e.preventDefault()
54
+ onDone(text)
55
+ } else if (e.key === "Escape") {
56
+ e.preventDefault()
57
+ onCancel()
58
+ }
59
+ }}
60
+ className={cn(
61
+ "h-7 min-w-0 flex-1 rounded-control-sm border border-input bg-card px-2 text-[0.8125rem] text-foreground outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
62
+ mono && "font-mono"
63
+ )}
64
+ />
65
+ </label>
66
+ <Button size="sm" variant="outline" onClick={() => onDone(text)}>
67
+ {labels.done}
68
+ </Button>
69
+ </div>
70
+ )
71
+ }
72
+
73
+ type Editing = { key: string; label: string; value: string; apply: (v: string) => void; mono?: boolean } | null
74
+
75
+ /**
76
+ * A selected rich block's own toolbar, above it (E.8, EditorBlockChrome):
77
+ * image width, caption, alt text, replace; table header row, rows and columns;
78
+ * callout kind; record and chart source; signature signers and stamp; barcode
79
+ * and QR value; the maths formula. Agents never use it (E.4).
80
+ */
81
+ function BlockToolbar({ editor, labels, container }: { editor: Editor; labels: EditorLabels; container: React.RefObject<HTMLDivElement | null> }) {
82
+ const { services } = useEditorServices()
83
+ const target = useEditorState({ editor, selector: ({ editor: e }) => (e.isEditable ? selectedRich(e) : null) })
84
+ const [editing, setEditing] = React.useState<Editing>(null)
85
+ const [busy, setBusy] = React.useState(false)
86
+ const [error, setError] = React.useState<string | null>(null)
87
+ const fileInput = React.useRef<HTMLInputElement>(null)
88
+ const [top, setTop] = React.useState<number | null>(null)
89
+ // On a label sheet (E.43) the label is small and its neighbours repeat it, so
90
+ // the bar opens below the block, where it covers nothing the author needs.
91
+ const [below, setBelow] = React.useState(false)
92
+
93
+ const pos = target?.pos
94
+ React.useEffect(() => setEditing(null), [pos])
95
+ React.useLayoutEffect(() => {
96
+ if (pos === undefined || !container.current) {
97
+ setTop(null)
98
+ return
99
+ }
100
+ const dom = editor.view.nodeDOM(pos) as HTMLElement | null
101
+ if (!dom) return
102
+ const box = container.current.getBoundingClientRect()
103
+ const rect = dom.getBoundingClientRect()
104
+ const inLabel = !!dom.closest(".wy-ls__label")
105
+ setBelow(inLabel)
106
+ setTop((inLabel ? rect.bottom + 10 : rect.top) - box.top)
107
+ }, [editor, pos, container, target?.node])
108
+
109
+ if (!target || top === null) return null
110
+ const { node } = target
111
+ const type = node.type.name
112
+ const attrs = node.attrs as Record<string, unknown>
113
+ const set = (next: Record<string, unknown>) => {
114
+ const current = editor.state.doc.nodeAt(target.pos)
115
+ if (!current) return
116
+ const tr = editor.state.tr.setNodeMarkup(target.pos, undefined, { ...current.attrs, ...next })
117
+ if (editor.state.selection instanceof NodeSelection) tr.setSelection(NodeSelection.create(tr.doc, target.pos))
118
+ editor.view.dispatch(tr)
119
+ }
120
+ const edit = (key: string, label: string, value: string, apply: (v: string) => void, mono?: boolean) => setEditing({ key, label, value, apply, mono })
121
+ const remove = () => deleteBlock(editor, target.pos)
122
+ const del = <IconButton icon="delete" label={labels.deleteBlock} size="sm" onClick={remove} />
123
+
124
+ const upload = async (file: File) => {
125
+ if (!services.uploadFile) return
126
+ setBusy(true)
127
+ setError(null)
128
+ try {
129
+ const up = await services.uploadFile(file)
130
+ if (type === "image") set({ src: up.url, alt: (attrs.alt as string) || file.name.replace(/\.[^.]+$/, "") })
131
+ else set({ fileId: up.fileId, name: up.name, size: up.size, mime: up.mime })
132
+ } catch {
133
+ setError(labels.uploadFailed)
134
+ } finally {
135
+ setBusy(false)
136
+ }
137
+ }
138
+
139
+ let controls: React.ReactNode = null
140
+ if (type === "callout") {
141
+ controls = (
142
+ <ToggleGroup
143
+ size="sm"
144
+ label={labels.blockCallout}
145
+ required
146
+ value={attrs.kind === "important" ? "important" : "note"}
147
+ onChange={(v) => set({ kind: v })}
148
+ options={[
149
+ { value: "note", label: labels.calloutNote, icon: "info" },
150
+ { value: "important", label: labels.calloutImportant, icon: "alert" },
151
+ ]}
152
+ />
153
+ )
154
+ } else if (type === "image" || type === "file") {
155
+ controls = (
156
+ <>
157
+ {type === "image" && (
158
+ <>
159
+ <ToggleGroup
160
+ size="sm"
161
+ label={labels.blockImage}
162
+ required
163
+ value={String(attrs.width ?? "full")}
164
+ onChange={(v) => set({ width: v })}
165
+ options={[
166
+ { value: "half", label: labels.widthHalf, icon: "columns", iconOnly: true },
167
+ { value: "wide", label: labels.widthWide, icon: "continuous", iconOnly: true },
168
+ { value: "full", label: labels.widthFull, icon: "page", iconOnly: true },
169
+ ]}
170
+ />
171
+ <Sep />
172
+ <Button variant="ghost" size="sm" onClick={() => edit("caption", labels.caption, inlineText(attrs.caption as Inline[] | null), (v) => set({ caption: v.trim() ? textToInline(v, attrs.caption as Inline[] | null) : null }))}>
173
+ {labels.caption}
174
+ </Button>
175
+ <Button variant="ghost" size="sm" onClick={() => edit("alt", labels.altText, String(attrs.alt ?? ""), (v) => set({ alt: v.trim() }))}>
176
+ {labels.altText}
177
+ </Button>
178
+ </>
179
+ )}
180
+ {services.uploadFile && (
181
+ <Button variant="ghost" size="sm" loading={busy} onClick={() => fileInput.current?.click()}>
182
+ {busy ? labels.uploading : (type === "image" ? attrs.src : attrs.fileId) ? labels.replace : labels.upload}
183
+ </Button>
184
+ )}
185
+ <input
186
+ ref={fileInput}
187
+ type="file"
188
+ hidden
189
+ /* What the server stores (FormUploadPolicy): PNG and JPEG images, and PDF for files. */
190
+ accept={type === "image" ? "image/png,image/jpeg" : "application/pdf,image/png,image/jpeg"}
191
+ onChange={(e) => {
192
+ const file = e.target.files?.[0]
193
+ e.target.value = ""
194
+ if (file) void upload(file)
195
+ }}
196
+ />
197
+ <Sep />
198
+ {del}
199
+ </>
200
+ )
201
+ } else if (type === "table") {
202
+ const sel = editor.state.selection
203
+ const cellPos = (() => {
204
+ const { $from } = sel
205
+ for (let d = $from.depth; d > 0; d--) if ($from.node(d).type.name === "tableCell") return { row: $from.index(d - 2), col: $from.index(d - 1) }
206
+ return null
207
+ })()
208
+ const columns = ((attrs.columns as { align: string; widthPct?: number }[]) ?? []).slice()
209
+ const width = Math.max(columns.length, ...Array.from({ length: node.childCount }, (_, i) => node.child(i).childCount))
210
+ const setRows = (mutate: (rows: Inline[][][]) => Inline[][][], nextColumns = columns) => {
211
+ // Rebuild through the contract so cells keep their content and marks.
212
+ const json = node.toJSON() as { content?: { content?: { content?: unknown[] }[] }[] }
213
+ const rows: Inline[][][] = (json.content ?? []).map((r) => (r.content ?? []).map((c) => (c.content ?? []) as Inline[]))
214
+ const next = mutate(rows)
215
+ const table = editor.schema.nodeFromJSON({
216
+ type: "table",
217
+ attrs: { ...node.attrs, columns: nextColumns },
218
+ content: next.map((r) => ({ type: "tableRow", content: r.map((c) => ({ type: "tableCell", ...(c.length ? { content: c } : {}) })) })),
219
+ })
220
+ const tr = editor.state.tr.replaceWith(target.pos, target.pos + node.nodeSize, table)
221
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(target.pos + 3, tr.doc.content.size))))
222
+ editor.view.dispatch(tr)
223
+ }
224
+ const blankRow = () => Array.from({ length: width }, () => [] as Inline[])
225
+ controls = (
226
+ <>
227
+ <Button variant="ghost" size="sm" icon={attrs.headerRow ? "check" : undefined} active={Boolean(attrs.headerRow)} onClick={() => set({ headerRow: !attrs.headerRow })}>
228
+ {labels.headerRow}
229
+ </Button>
230
+ <Sep />
231
+ <Button variant="ghost" size="sm" icon="plus" onClick={() => setRows((rows) => { const r = rows.slice(); r.splice(cellPos ? cellPos.row + 1 : r.length, 0, blankRow()); return r })}>
232
+ {labels.addRow}
233
+ </Button>
234
+ <Button
235
+ variant="ghost"
236
+ size="sm"
237
+ icon="plus"
238
+ onClick={() => {
239
+ const at = cellPos ? cellPos.col + 1 : width
240
+ const nextColumns = Array.from({ length: width }, (_, i) => columns[i] ?? { align: "start" as const })
241
+ nextColumns.splice(at, 0, { align: "start" })
242
+ setRows((rows) => rows.map((r) => { const c = r.slice(); while (c.length < width) c.push([]); c.splice(at, 0, []); return c }), nextColumns)
243
+ }}
244
+ >
245
+ {labels.addColumn}
246
+ </Button>
247
+ {cellPos && (
248
+ <>
249
+ <Sep />
250
+ <ToggleGroup
251
+ size="sm"
252
+ label={labels.columnAlign}
253
+ required
254
+ value={columns[cellPos.col]?.align === "end" ? "end" : "start"}
255
+ onChange={(v) => {
256
+ const next = Array.from({ length: width }, (_, i) => columns[i] ?? { align: "start" as const })
257
+ next[cellPos.col] = { ...next[cellPos.col], align: v === "end" ? "end" : "start" }
258
+ set({ columns: next })
259
+ }}
260
+ options={[
261
+ { value: "start", label: labels.alignStart },
262
+ { value: "end", label: labels.alignEnd },
263
+ ]}
264
+ />
265
+ <IconButton icon="minus" label={labels.deleteRow} size="sm" disabled={node.childCount <= 1} onClick={() => setRows((rows) => rows.filter((_, i) => i !== cellPos.row))} />
266
+ <IconButton
267
+ icon="close"
268
+ label={labels.deleteColumn}
269
+ size="sm"
270
+ disabled={width <= 1}
271
+ onClick={() => setRows((rows) => rows.map((r) => r.filter((_, i) => i !== cellPos.col)), columns.filter((_, i) => i !== cellPos.col))}
272
+ />
273
+ </>
274
+ )}
275
+ <Sep />
276
+ {del}
277
+ </>
278
+ )
279
+ } else if (type === "record") {
280
+ const ref = attrs.ref as { type: string; id: string } | null
281
+ controls = (
282
+ <>
283
+ {services.recordTypes && services.recordTypes.length > 0 && (
284
+ <select
285
+ aria-label={labels.recordType}
286
+ value={ref?.type ?? ""}
287
+ onChange={(e) => set({ ref: e.target.value ? { type: e.target.value, id: ref?.id ?? "" } : null })}
288
+ className="h-7 rounded-control-sm border border-input bg-card px-1.5 text-[0.8125rem]"
289
+ >
290
+ <option value="">{labels.recordType}</option>
291
+ {services.recordTypes.map((t) => (
292
+ <option key={t.key} value={t.key}>
293
+ {t.label}
294
+ </option>
295
+ ))}
296
+ </select>
297
+ )}
298
+ <Button variant="ghost" size="sm" disabled={!ref?.type} onClick={() => edit("record", labels.recordId, ref?.id ?? "", (v) => set({ ref: { type: ref!.type, id: v.trim() } }), true)}>
299
+ {labels.recordChoose}
300
+ </Button>
301
+ <Sep />
302
+ <ToggleGroup
303
+ size="sm"
304
+ label={labels.blockRecord}
305
+ required
306
+ value={attrs.view === "summary" ? "summary" : "card"}
307
+ onChange={(v) => set({ view: v })}
308
+ options={[
309
+ { value: "card", label: labels.viewCard },
310
+ { value: "summary", label: labels.viewSummary },
311
+ ]}
312
+ />
313
+ <Sep />
314
+ {del}
315
+ </>
316
+ )
317
+ } else if (type === "chart") {
318
+ const source = attrs.source as { query: string; params?: Record<string, string> } | null
319
+ controls = (
320
+ <>
321
+ <ToggleGroup
322
+ size="sm"
323
+ label={labels.blockChart}
324
+ required
325
+ value={String(attrs.chart ?? "bar")}
326
+ onChange={(v) => set({ chart: v })}
327
+ options={[
328
+ { value: "bar", label: labels.chartBar },
329
+ { value: "line", label: labels.chartLine },
330
+ { value: "donut", label: labels.chartDonut },
331
+ ]}
332
+ />
333
+ {services.chartSources && services.chartSources.length > 0 && (
334
+ <>
335
+ <Sep />
336
+ <select
337
+ aria-label={labels.chartSource}
338
+ value={source?.query ?? ""}
339
+ onChange={(e) => set({ source: e.target.value ? { query: e.target.value } : null })}
340
+ className="h-7 rounded-control-sm border border-input bg-card px-1.5 text-[0.8125rem]"
341
+ >
342
+ <option value="">{labels.chartSource}</option>
343
+ {services.chartSources.map((s) => (
344
+ <option key={s.key} value={s.key}>
345
+ {s.label}
346
+ </option>
347
+ ))}
348
+ </select>
349
+ </>
350
+ )}
351
+ <Button variant="ghost" size="sm" onClick={() => edit("title", labels.chartTitle, String(attrs.title ?? ""), (v) => set({ title: v.trim() || null }))}>
352
+ {labels.chartTitle}
353
+ </Button>
354
+ <Sep />
355
+ {del}
356
+ </>
357
+ )
358
+ } else if (type === "signature") {
359
+ const signers = (attrs.signers as { name: Inline[]; role: Inline[] }[]) ?? []
360
+ controls = (
361
+ <>
362
+ {signers.map((s, i) => (
363
+ <Button
364
+ key={i}
365
+ variant="ghost"
366
+ size="sm"
367
+ onClick={() =>
368
+ edit(`signer-${i}`, fill(labels.signatureName, {}), `${inlineText(s.name)} | ${inlineText(s.role)}`, (v) => {
369
+ const [name, role = ""] = v.split("|").map((x) => x.trim())
370
+ const next = signers.slice()
371
+ next[i] = { name: textToInline(name, s.name), role: textToInline(role, s.role) }
372
+ set({ signers: next })
373
+ })
374
+ }
375
+ >
376
+ {inlineText(s.name) || labels.signatureName}
377
+ </Button>
378
+ ))}
379
+ <Button variant="ghost" size="sm" icon="plus" disabled={signers.length >= 3} onClick={() => set({ signers: [...signers, { name: [], role: [] }] })}>
380
+ {labels.addSigner}
381
+ </Button>
382
+ <Button variant="ghost" size="sm" onClick={() => edit("date", labels.signatureDate, inlineText(attrs.date as Inline[]), (v) => set({ date: textToInline(v, attrs.date as Inline[]) }))}>
383
+ {/* @date-display-ignore: the signature date is text the author typed or a merge field (Inline[]), not a record timestamp; this is its label. */}
384
+ {labels.signatureDate}
385
+ </Button>
386
+ <Button variant="ghost" size="sm" active={Boolean(attrs.stamp)} onClick={() => set({ stamp: !attrs.stamp })}>
387
+ {labels.stamp}
388
+ </Button>
389
+ <Sep />
390
+ {del}
391
+ </>
392
+ )
393
+ } else if (type === "barcode" || type === "qr") {
394
+ controls = (
395
+ <>
396
+ {type === "barcode" && (
397
+ <select
398
+ aria-label={labels.symbology}
399
+ value={String(attrs.symbology ?? "code128")}
400
+ onChange={(e) => set({ symbology: e.target.value })}
401
+ className="h-7 rounded-control-sm border border-input bg-card px-1.5 text-[0.8125rem]"
402
+ >
403
+ <option value="code128">Code 128</option>
404
+ <option value="ean13">EAN-13</option>
405
+ <option value="code39">Code 39</option>
406
+ </select>
407
+ )}
408
+ <Button variant="ghost" size="sm" onClick={() => edit("value", labels.value, inlineText(attrs.value as Inline[]), (v) => set({ value: textToInline(v, attrs.value as Inline[]) }), true)}>
409
+ {labels.value}
410
+ </Button>
411
+ {type === "barcode" ? (
412
+ <Button variant="ghost" size="sm" active={Boolean(attrs.showText)} onClick={() => set({ showText: !attrs.showText })}>
413
+ {labels.showText}
414
+ </Button>
415
+ ) : (
416
+ <Button variant="ghost" size="sm" onClick={() => edit("caption", labels.caption, inlineText(attrs.caption as Inline[] | null), (v) => set({ caption: v.trim() ? textToInline(v, attrs.caption as Inline[] | null) : null }))}>
417
+ {labels.caption}
418
+ </Button>
419
+ )}
420
+ <Sep />
421
+ {del}
422
+ </>
423
+ )
424
+ } else if (type === "math") {
425
+ controls = (
426
+ <>
427
+ <Button variant="ghost" size="sm" onClick={() => edit("tex", labels.formula, String(attrs.tex ?? ""), (v) => set({ tex: v }), true)}>
428
+ {labels.formula}
429
+ </Button>
430
+ <Sep />
431
+ {del}
432
+ </>
433
+ )
434
+ }
435
+ if (!controls) return null
436
+
437
+ return (
438
+ <div
439
+ role="toolbar"
440
+ aria-label={labels.blockToolbar}
441
+ data-slot="block-toolbar"
442
+ className={cn(
443
+ "absolute start-0 z-20 grid gap-1 rounded-control border border-border bg-popover p-[3px] shadow-float",
444
+ below ? "w-max max-w-[420px]" : "max-w-full"
445
+ )}
446
+ style={below ? { top } : { top, transform: "translateY(calc(-100% - 10px))" }}
447
+ onMouseDown={(e) => {
448
+ if ((e.target as HTMLElement).tagName !== "INPUT" && (e.target as HTMLElement).tagName !== "SELECT") e.preventDefault()
449
+ }}
450
+ >
451
+ <div className="flex flex-wrap items-center gap-0.5">{controls}</div>
452
+ {error && (
453
+ <div role="alert" className="px-1.5 pb-0.5 text-xs text-error-text">
454
+ {error}
455
+ </div>
456
+ )}
457
+ {editing && (
458
+ <FieldRow
459
+ key={editing.key}
460
+ label={editing.label}
461
+ value={editing.value}
462
+ mono={editing.mono}
463
+ onCancel={() => {
464
+ setEditing(null)
465
+ editor.commands.focus()
466
+ }}
467
+ onDone={(v) => {
468
+ editing.apply(v)
469
+ setEditing(null)
470
+ }}
471
+ />
472
+ )}
473
+ </div>
474
+ )
475
+ }
476
+
477
+ export { BlockToolbar }
@@ -0,0 +1,93 @@
1
+ "use client"
2
+
3
+ import type { Editor } from "@tiptap/core"
4
+ import { isTextSelection } from "@tiptap/core"
5
+ import { useEditorState } from "@tiptap/react"
6
+ import { BubbleMenu } from "@tiptap/react/menus"
7
+
8
+ import type { IconName } from "../icon"
9
+ import { IconButton } from "../icon-button"
10
+ import type { EditorLabels } from "./labels"
11
+
12
+ /**
13
+ * The selection bubble (EditorInline): after a short pause above a text
14
+ * selection, bold, italic, underline, strikethrough, code · link, highlight.
15
+ * · Comment (M5). Rewrite with an agent (M6) joins it later. Without edit
16
+ * rights (Viewing) only Comment shows.
17
+ */
18
+ function SelectionBubble({
19
+ editor,
20
+ labels,
21
+ onLink,
22
+ onComment,
23
+ }: {
24
+ editor: Editor
25
+ labels: EditorLabels
26
+ onLink: () => void
27
+ /** M5: Comment on the selection; with it the bubble shows even where nothing can be edited. */
28
+ onComment?: () => void
29
+ }) {
30
+ const s = useEditorState({
31
+ editor,
32
+ selector: ({ editor: e }) => ({
33
+ bold: e.isActive("bold"),
34
+ italic: e.isActive("italic"),
35
+ underline: e.isActive("underline"),
36
+ strike: e.isActive("strike"),
37
+ code: e.isActive("code"),
38
+ link: e.isActive("link"),
39
+ highlight: e.isActive("highlight"),
40
+ editable: e.isEditable,
41
+ }),
42
+ })
43
+ const b = (icon: IconName, label: string, on: boolean, onClick: () => void, shortcut?: string) => (
44
+ <IconButton
45
+ icon={icon}
46
+ label={label}
47
+ size="sm"
48
+ shortcut={shortcut}
49
+ pressed={on}
50
+ onMouseDown={(e) => e.preventDefault()}
51
+ onClick={onClick}
52
+ />
53
+ )
54
+ const mark = (name: string) => () => editor.chain().focus().toggleMark(name).run()
55
+ return (
56
+ <BubbleMenu
57
+ editor={editor}
58
+ updateDelay={250}
59
+ shouldShow={({ editor: e, state, from, to }) =>
60
+ (e.isEditable || !!onComment) && isTextSelection(state.selection) && from !== to && !e.isActive("codeBlock")
61
+ }
62
+ options={{ placement: "top-start", offset: 8 }}
63
+ >
64
+ <div
65
+ role="toolbar"
66
+ aria-label={labels.selection}
67
+ data-slot="selection-bubble"
68
+ className="flex items-center gap-0.5 rounded-control border border-border bg-popover p-[3px] whitespace-nowrap shadow-float"
69
+ >
70
+ {s.editable && (
71
+ <>
72
+ {b("bold", labels.bold, s.bold, mark("bold"), "⌘B")}
73
+ {b("italic", labels.italic, s.italic, mark("italic"), "⌘I")}
74
+ {b("underline", labels.underline, s.underline, mark("underline"), "⌘U")}
75
+ {b("strike", labels.strike, s.strike, mark("strike"), "⇧⌘X")}
76
+ {b("code", labels.code, s.code, mark("code"), "⌘E")}
77
+ <span aria-hidden="true" className="mx-[3px] h-[18px] w-px bg-border" />
78
+ {b("link", labels.link, s.link, onLink, "⌘K")}
79
+ {b("highlight", labels.highlight, s.highlight, mark("highlight"))}
80
+ </>
81
+ )}
82
+ {onComment && (
83
+ <>
84
+ {s.editable && <span aria-hidden="true" className="mx-[3px] h-[18px] w-px bg-border" />}
85
+ {b("comment-add", labels.comment, false, onComment, "⌥⌘M")}
86
+ </>
87
+ )}
88
+ </div>
89
+ </BubbleMenu>
90
+ )
91
+ }
92
+
93
+ export { SelectionBubble }
@@ -0,0 +1,103 @@
1
+ import type { Editor, JSONContent } from "@tiptap/core"
2
+
3
+ import type { IconName } from "../icon"
4
+ import { currentBlock } from "./behaviour"
5
+ import type { EditorLabels } from "./labels"
6
+
7
+ /**
8
+ * The blocks the editor inserts in this version, grouped as the / menu shows
9
+ * them (EditorInsert, E.13). The same list feeds the + inserter, Insert ▾ and
10
+ * Turn into. Media, Whity, saved and plugin blocks join in later milestones.
11
+ */
12
+ export interface CatalogueItem {
13
+ id: string
14
+ group: "groupBasic" | "groupLists" | "groupStructure" | "groupMedia" | "groupWhity"
15
+ label: keyof EditorLabels
16
+ hint: keyof EditorLabels
17
+ icon: IconName
18
+ /** The Markdown shortcut, shown beside the item. */
19
+ markdown?: string
20
+ keywords: string[]
21
+ /** Text blocks can be a "Turn into" target. */
22
+ textBlock: boolean
23
+ node: { type: string; attrs?: Record<string, unknown>; content?: JSONContent[] }
24
+ }
25
+
26
+ const cell = (text = "") => ({ type: "tableCell", ...(text ? { content: [{ type: "text", text }] } : {}) })
27
+ const row = (n: number) => ({ type: "tableRow", content: Array.from({ length: n }, () => cell()) })
28
+
29
+ export const CATALOGUE: CatalogueItem[] = [
30
+ { id: "text", group: "groupBasic", label: "blockText", hint: "blockTextHint", icon: "text", keywords: ["paragraph", "plain"], textBlock: true, node: { type: "paragraph" } },
31
+ { id: "h1", group: "groupBasic", label: "blockH1", hint: "blockH1Hint", icon: "heading-1", markdown: "#", keywords: ["title", "h1"], textBlock: true, node: { type: "heading", attrs: { level: 1 } } },
32
+ { id: "h2", group: "groupBasic", label: "blockH2", hint: "blockH2Hint", icon: "heading-2", markdown: "##", keywords: ["subtitle", "h2"], textBlock: true, node: { type: "heading", attrs: { level: 2 } } },
33
+ { id: "h3", group: "groupBasic", label: "blockH3", hint: "blockH3Hint", icon: "heading-3", markdown: "###", keywords: ["h3"], textBlock: true, node: { type: "heading", attrs: { level: 3 } } },
34
+ { id: "quote", group: "groupBasic", label: "blockQuote", hint: "blockQuoteHint", icon: "blockquote", markdown: ">", keywords: ["citation"], textBlock: true, node: { type: "quote" } },
35
+ { id: "code", group: "groupBasic", label: "blockCode", hint: "blockCodeHint", icon: "code", markdown: "```", keywords: ["snippet", "monospace"], textBlock: true, node: { type: "codeBlock" } },
36
+ { id: "bullet", group: "groupLists", label: "blockBullet", hint: "blockBulletHint", icon: "list-bullet", markdown: "-", keywords: ["unordered", "ul"], textBlock: true, node: { type: "listItem", attrs: { kind: "bullet", level: 0 } } },
37
+ { id: "number", group: "groupLists", label: "blockNumber", hint: "blockNumberHint", icon: "list-numbered", markdown: "1.", keywords: ["ordered", "ol"], textBlock: true, node: { type: "listItem", attrs: { kind: "number", level: 0 } } },
38
+ { id: "checklist", group: "groupLists", label: "blockChecklist", hint: "blockChecklistHint", icon: "list-todo", markdown: "[]", keywords: ["todo", "task", "check"], textBlock: true, node: { type: "checkItem", attrs: { level: 0, checked: false } } },
39
+ { id: "callout", group: "groupBasic", label: "blockCallout", hint: "blockCalloutHint", icon: "info", keywords: ["note", "important", "warning", "aside"], textBlock: true, node: { type: "callout", attrs: { kind: "note" } } },
40
+ { id: "math", group: "groupBasic", label: "blockMath", hint: "blockMathHint", icon: "text", keywords: ["formula", "equation", "tex", "latex", "katex"], textBlock: false, node: { type: "math", attrs: { tex: "" } } },
41
+ { id: "toggle", group: "groupStructure", label: "blockToggle", hint: "blockToggleHint", icon: "chevron-right", keywords: ["collapse", "expand", "details", "faq"], textBlock: false, node: { type: "toggle", attrs: { open: true }, content: [{ type: "toggleSummary" }, { type: "paragraph" }] } },
42
+ { id: "columns", group: "groupStructure", label: "blockColumns", hint: "blockColumnsHint", icon: "columns", keywords: ["layout", "side by side", "split"], textBlock: false, node: { type: "columns", content: [{ type: "column", content: [{ type: "paragraph" }] }, { type: "column", content: [{ type: "paragraph" }] }] } },
43
+ { id: "divider", group: "groupStructure", label: "blockDivider", hint: "blockDividerHint", icon: "divider", markdown: "---", keywords: ["line", "separator", "hr", "rule"], textBlock: false, node: { type: "divider" } },
44
+ { id: "pageBreak", group: "groupStructure", label: "blockPageBreak", hint: "blockPageBreakHint", icon: "page-break", keywords: ["new page", "print"], textBlock: false, node: { type: "pageBreak" } },
45
+ { id: "table", group: "groupMedia", label: "blockTable", hint: "blockTableHint", icon: "table", keywords: ["grid", "rows", "columns"], textBlock: false, node: { type: "table", attrs: { headerRow: true, columns: [{ align: "start" }, { align: "start" }, { align: "end" }] }, content: [row(3), row(3)] } },
46
+ { id: "image", group: "groupMedia", label: "blockImage", hint: "blockImageHint", icon: "image", keywords: ["picture", "photo", "logo"], textBlock: false, node: { type: "image", attrs: { src: "", alt: "", width: "full" } } },
47
+ { id: "file", group: "groupMedia", label: "blockFile", hint: "blockFileHint", icon: "document", keywords: ["attachment", "pdf", "download"], textBlock: false, node: { type: "file" } },
48
+ { id: "record", group: "groupWhity", label: "blockRecord", hint: "blockRecordHint", icon: "invoice", keywords: ["invoice", "customer", "live", "embed"], textBlock: false, node: { type: "record", attrs: { ref: null, view: "card" } } },
49
+ { id: "chart", group: "groupWhity", label: "blockChart", hint: "blockChartHint", icon: "chart", keywords: ["graph", "bars", "line", "donut", "live"], textBlock: false, node: { type: "chart", attrs: { chart: "bar", source: null } } },
50
+ { id: "signature", group: "groupWhity", label: "blockSignature", hint: "blockSignatureHint", icon: "edit", keywords: ["sign", "stamp", "signer"], textBlock: false, node: { type: "signature", attrs: { signers: [{ name: [], role: [] }], date: [], stamp: true } } },
51
+ { id: "barcode", group: "groupWhity", label: "blockBarcode", hint: "blockBarcodeHint", icon: "qr", keywords: ["code128", "ean", "code39", "label"], textBlock: false, node: { type: "barcode", attrs: { symbology: "code128", value: [], showText: true } } },
52
+ { id: "qr", group: "groupWhity", label: "blockQr", hint: "blockQrHint", icon: "qr", keywords: ["qrcode", "scan", "link"], textBlock: false, node: { type: "qr", attrs: { value: [] } } },
53
+ ]
54
+
55
+ /** Filter by the item's name, hint and keywords, in the current language and in English. */
56
+ export function filterCatalogue(query: string, labels: EditorLabels, english: EditorLabels): CatalogueItem[] {
57
+ const q = query.trim().toLowerCase()
58
+ if (!q) return CATALOGUE
59
+ return CATALOGUE.filter((item) =>
60
+ [labels[item.label], labels[item.hint], english[item.label], english[item.hint], item.id, ...item.keywords]
61
+ .some((word) => String(word).toLowerCase().includes(q))
62
+ )
63
+ }
64
+
65
+ /** The catalogue item that matches the current block, for the style menu and Turn into. */
66
+ export function currentItem(editor: Editor): CatalogueItem | undefined {
67
+ const block = currentBlock(editor)
68
+ if (!block) return undefined
69
+ const { name } = block.node.type
70
+ return CATALOGUE.find(
71
+ (item) =>
72
+ item.node.type === name &&
73
+ (name !== "heading" || item.node.attrs?.level === block.node.attrs.level) &&
74
+ (name !== "listItem" || item.node.attrs?.kind === block.node.attrs.kind)
75
+ )
76
+ }
77
+
78
+ /**
79
+ * Put the item where the caret is (E.13, EditorInsert): an empty text line
80
+ * turns into the block; a line with text gets the block after it.
81
+ */
82
+ export function applyItem(editor: Editor, item: CatalogueItem, { after }: { after?: number } = {}): void {
83
+ const block = currentBlock(editor)
84
+ const atPos = after ?? (block ? block.pos + block.node.nodeSize : editor.state.doc.content.size)
85
+ const empty = after === undefined && block && block.node.isTextblock && block.node.content.size === 0
86
+ const chain = editor.chain().focus()
87
+ if (empty && item.textBlock) {
88
+ chain.setNode(item.node.type, { ...item.node.attrs, id: block.node.attrs.id }).run()
89
+ return
90
+ }
91
+ const node: JSONContent = { type: item.node.type, attrs: item.node.attrs, ...(item.node.content ? { content: item.node.content } : {}) }
92
+ if (empty && block) {
93
+ // A block on an empty line takes its place, with a fresh line after it.
94
+ chain.insertContentAt({ from: block.pos, to: block.pos + block.node.nodeSize }, [node, { type: "paragraph" }]).run()
95
+ return
96
+ }
97
+ const content = item.textBlock ? [node] : [node, { type: "paragraph" }]
98
+ // The caret lands in the new text block, or in the fresh line after a divider.
99
+ chain
100
+ .insertContentAt(atPos, content)
101
+ .setTextSelection(atPos + (item.textBlock ? 1 : 2))
102
+ .run()
103
+ }