@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,1287 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import type { Editor } from "@tiptap/core"
5
+ import { TextSelection } from "@tiptap/pm/state"
6
+ import { EditorContent, useEditor, useEditorState } from "@tiptap/react"
7
+
8
+ import { Badge } from "../badge"
9
+ import { Button } from "../button"
10
+ import {
11
+ DropdownMenu,
12
+ DropdownMenuContent,
13
+ DropdownMenuItem,
14
+ DropdownMenuTrigger,
15
+ } from "../dropdown-menu"
16
+ import { Icon, type IconName } from "../icon"
17
+ import { IconButton } from "../icon-button"
18
+ import { cn } from "../utils"
19
+ import { BlockList } from "./block-list"
20
+ import { SelectionBubble } from "./bubble"
21
+ import { applyItem, filterCatalogue } from "./catalogue"
22
+ import type { Actor, DocumentKind, EditorMode, PublishBlocker, ResolvedThemeTokens, WhityDocument } from "./contract"
23
+ import { fromEditorContent, toEditorContent } from "./convert"
24
+ import { DocumentBehaviour } from "./behaviour"
25
+ import { documentExtensions } from "./extensions"
26
+ import { BlockGutter } from "./gutter"
27
+ import { EDITOR_LABELS, fill, type EditorLabels } from "./labels"
28
+ import { LinkCard, LinkPopover } from "./link-tools"
29
+ import { SlashCommand, type SlashState } from "./slash"
30
+ import { EditorToolbar, insertField, type EditorView, type PageZoom } from "./toolbar"
31
+ import { UnknownBlock } from "./schema"
32
+ import { BlockToolbar } from "./block-toolbar"
33
+ import { EditorServicesProvider, type EditorServices, type FieldPreview } from "./services"
34
+ import { FieldTrigger, filterFields, type FieldDef, type FieldGroup, type FieldTriggerState } from "./fields"
35
+ import { FieldPicker, flatFields } from "./field-picker"
36
+ import { DEFAULT_LABEL_GRID, LabelSetup, LabelSheetView, labelCells, type SheetSize } from "./label-sheet"
37
+ import { PagePagination, PageView, fitZoom, themeStyle, type Letterhead } from "./page-view"
38
+ import { PublishCheck } from "./publish-check"
39
+ import type { EditorCollab, RailSuggestion } from "./collab"
40
+ import { CollabDrawer, CollabRail, useWideRail, type RailActions, type RailItem } from "./collab-rail"
41
+ import { collectPatches, hasSuggestionMarks, renderSuggestions, stripSuggestions, type LocalChange } from "./suggestions"
42
+ import {
43
+ LOCAL_PREFIX,
44
+ findBlockNode,
45
+ pendingFormats,
46
+ renameSuggestion,
47
+ suggestingKey,
48
+ suggestionPos,
49
+ threadRange,
50
+ Suggesting,
51
+ type CollabThreadAnchor,
52
+ } from "./suggesting"
53
+
54
+ export type SaveState =
55
+ | { state: "saved"; at: string }
56
+ | { state: "saving" }
57
+ | { state: "offline" }
58
+ | { state: "error" }
59
+
60
+ const KIND_ICON: Record<DocumentKind, IconName> = {
61
+ template: "template",
62
+ letter: "mail",
63
+ report: "chart",
64
+ note: "document",
65
+ wiki: "world",
66
+ label: "print",
67
+ }
68
+ const KIND_LABEL: Record<DocumentKind, keyof EditorLabels> = {
69
+ template: "kindTemplate",
70
+ letter: "kindLetter",
71
+ report: "kindReport",
72
+ note: "kindNote",
73
+ wiki: "kindWiki",
74
+ label: "kindLabel",
75
+ }
76
+
77
+ export interface DocEditorProps {
78
+ document: WhityDocument
79
+ /** Debounced by the caller; fires with the whole document on every change. */
80
+ onChange: (doc: WhityDocument) => void
81
+ canEdit: boolean
82
+ mode?: EditorMode
83
+ onModeChange?: (mode: EditorMode) => void
84
+ /** Where Back goes, and where the document lives ("Notes · Finance"). */
85
+ back?: { label: string; onClick: () => void }
86
+ path?: string
87
+ save?: SaveState
88
+ /** The command palette, for ⌘K with nothing selected (E.36, 2.1c). */
89
+ onCommandPalette?: () => void
90
+ /** The address "Copy link to block" copies. */
91
+ blockUrl?: (blockId: string) => string
92
+ /** Every string has an English default; Arabic comes in here. */
93
+ labels?: Partial<EditorLabels>
94
+ /** Live data for rich blocks: records, charts, uploads (M3). Each checks the reader's permissions. */
95
+ services?: EditorServices
96
+ /** The fields the template's record type offers (E.26); Field ▾ and {{ show them. */
97
+ fields?: FieldGroup[]
98
+ /** Continuous or page view; starts at the document's default (E.7). */
99
+ view?: EditorView
100
+ onViewChange?: (view: EditorView) => void
101
+ /** The tenant's letterhead on page 1; `null` for none. */
102
+ letterhead?: Letterhead | null
103
+ /**
104
+ * The document's resolved theme (E.44): the page view and label sheet use
105
+ * `accent` (`--doc-accent`), H1-H3 too with `title-and-headings` (E.45); the
106
+ * continuous sheet's title uses `accentOnDark` in dark mode only (E.11).
107
+ */
108
+ theme?: ResolvedThemeTokens | null
109
+ /** The letterhead's end side: the reference ("Ref INV-1042") and the date, as fields. */
110
+ pageFields?: { reference?: FieldDef; date?: FieldDef }
111
+ /** E.12: preview with a record. Read-only while set, unless `editWhilePreviewing`. */
112
+ preview?: FieldPreview | null
113
+ /**
114
+ * Issuing a one-off letter (M4c): the pages stay editable while previewing,
115
+ * so each edit shows with the record's values as it will print.
116
+ */
117
+ editWhilePreviewing?: boolean
118
+ /** Starts a preview (the screen asks which record) or changes the record. */
119
+ onPreview?: () => void
120
+ /** Show fields: leaves the preview. */
121
+ onClosePreview?: () => void
122
+ /** E.9: templates only. The header says what's in use; Publish opens the check. */
123
+ publish?: {
124
+ publishedVersion: number | null
125
+ /** The server's check (E.37); the editor adds the fields it can see aren't offered. */
126
+ check: () => Promise<PublishBlocker[]>
127
+ publish: () => Promise<void>
128
+ /** What the template prints, plural, for the check's sentence. */
129
+ recordLabel?: string
130
+ /** Fix actions: Review opens the rail (M5); Show selects the block. */
131
+ onFix?: (blocker: PublishBlocker) => void
132
+ }
133
+ /** Downloads the PDF through Whity Render. */
134
+ onExportPdf?: () => Promise<void> | void
135
+ /** Label sheets: Print fills one label per record or CSV row (E.43); the screen asks which. */
136
+ onPrintLabels?: () => void
137
+ /**
138
+ * Comments and suggestions (M5): the margin rail, Suggesting mode and
139
+ * Comment. Without it the editor offers Editing and Viewing only.
140
+ */
141
+ collab?: EditorCollab
142
+ className?: string
143
+ }
144
+
145
+ /** How long Suggesting waits after the last edit before sending it (spec: about 1.5 s idle). */
146
+ const FLUSH_DELAY_MS = 1500
147
+ const NO_SUGGESTIONS: RailSuggestion[] = []
148
+
149
+ const NO_SERVICES: EditorServices = {}
150
+
151
+ function actorName(actor: Actor): string {
152
+ return actor.kind === "system" ? "Whity" : actor.name
153
+ }
154
+
155
+ function countWords(editor: Editor): number {
156
+ const text = editor.state.doc.textBetween(0, editor.state.doc.content.size, " ", " ")
157
+ return text.split(/\s+/).filter(Boolean).length
158
+ }
159
+
160
+ /**
161
+ * The document editor (section 18, EditorShell): header, the fixed toolbar,
162
+ * the outline, the continuous sheet and the status bar. Blocks, the / menu,
163
+ * the + inserter, Markdown shortcuts, the selection bubble, links and the
164
+ * block gutter came in M2, rich blocks in M3; fields, the page view, preview
165
+ * with a record and Publish are M4's; comments and suggestions, agents and
166
+ * plugin blocks join in M5–M7.
167
+ */
168
+ /** A key for a new own field from its name: lowercase letters, digits and _, unique. */
169
+ export function ownFieldKey(label: string, taken: string[]): string {
170
+ const base =
171
+ label
172
+ .normalize("NFKD")
173
+ .toLowerCase()
174
+ .replace(/[^a-z0-9]+/g, "_")
175
+ .replace(/^_+|_+$/g, "")
176
+ .slice(0, 32) || "field"
177
+ let key = base
178
+ for (let n = 2; taken.includes(key); n++) key = `${base}_${n}`
179
+ return key
180
+ }
181
+
182
+ function DocEditor({
183
+ document: doc,
184
+ onChange,
185
+ canEdit,
186
+ mode: modeProp,
187
+ onModeChange,
188
+ back,
189
+ path,
190
+ save,
191
+ onCommandPalette,
192
+ blockUrl = (id) => `${typeof window === "undefined" ? "" : window.location.href.split("#")[0]}#block-${id}`,
193
+ labels: labelProp,
194
+ services = NO_SERVICES,
195
+ fields,
196
+ view: viewProp,
197
+ onViewChange,
198
+ letterhead,
199
+ theme,
200
+ pageFields,
201
+ preview = null,
202
+ editWhilePreviewing = false,
203
+ onPreview,
204
+ onClosePreview,
205
+ publish,
206
+ onExportPdf,
207
+ onPrintLabels,
208
+ collab,
209
+ className,
210
+ }: DocEditorProps) {
211
+ const labels = React.useMemo(() => ({ ...EDITOR_LABELS, ...labelProp }), [labelProp])
212
+ // E.10: Editing needs edit permission; without it Suggesting is the default, with Editing locked.
213
+ const canSuggest = !!collab?.onSuggest && collab.canSuggest !== false
214
+ const canComment = !!collab?.onComment && !!collab.canComment
215
+ const defaultMode: EditorMode = canEdit ? "editing" : canSuggest ? "suggesting" : "viewing"
216
+ const wanted = modeProp ?? defaultMode
217
+ const mode: EditorMode =
218
+ wanted === "viewing"
219
+ ? "viewing"
220
+ : wanted === "suggesting" && canSuggest
221
+ ? "suggesting"
222
+ : wanted === "editing" && canEdit
223
+ ? "editing"
224
+ : defaultMode
225
+ const suggesting = mode === "suggesting"
226
+ // E.12: the pages are read-only while previewing with a record, except when issuing a letter (M4c).
227
+ // Previewing hides comments and suggestions, so Suggesting is read-only then too.
228
+ const editable = (mode === "editing" && (!preview || editWhilePreviewing)) || (suggesting && !preview)
229
+ const showCollab = !!collab && !preview
230
+ const allSuggestions = collab?.suggestions ?? NO_SUGGESTIONS
231
+ // Only open suggestions are drawn and carded; stale or decided ones have left the rail.
232
+ const suggestions = React.useMemo(() => allSuggestions.filter((s) => s.status === "open"), [allSuggestions])
233
+ const revision = collab?.revision
234
+ const rendered = React.useMemo(
235
+ () => renderSuggestions(doc.blocks, suggestions.map((s) => ({ id: s.id, patch: s.patch }))),
236
+ // Drawn from the draft as it is when the suggestions or the revision change, not on every keystroke.
237
+ // eslint-disable-next-line react-hooks/exhaustive-deps
238
+ [suggestions, revision]
239
+ )
240
+ const [viewState, setViewState] = React.useState<EditorView>(doc.defaultView === "page" || doc.kind === "label" ? "page" : "continuous")
241
+ const view: EditorView = doc.kind === "label" ? "page" : (viewProp ?? viewState)
242
+ const setView = (v: EditorView) => {
243
+ setViewState(v)
244
+ onViewChange?.(v)
245
+ }
246
+ const [zoom, setZoom] = React.useState<PageZoom>("fit")
247
+ // E.43: a label sheet is one sheet of identical labels, page view only.
248
+ const isLabel = doc.kind === "label"
249
+ const labelGrid = doc.labels ?? DEFAULT_LABEL_GRID
250
+ const sheetSize: SheetSize = doc.page?.size === "Letter" ? "Letter" : "A4"
251
+ const [labelOverflow, setLabelOverflow] = React.useState(false)
252
+ const [canvasWidth, setCanvasWidth] = React.useState(1000)
253
+ const [pages, setPages] = React.useState(1)
254
+ const [fieldQuery, setFieldQuery] = React.useState<FieldTriggerState>({ open: false, query: "", range: null, rect: null })
255
+ const [fieldActive, setFieldActive] = React.useState(0)
256
+ const fieldKeys = React.useRef<(e: KeyboardEvent) => boolean>(() => false)
257
+ const [checkOpen, setCheckOpen] = React.useState(false)
258
+ const [blockers, setBlockers] = React.useState<PublishBlocker[]>([])
259
+ const [checking, setChecking] = React.useState(false)
260
+ const canvasRef = React.useRef<HTMLDivElement>(null)
261
+ const [outlineOpen, setOutlineOpen] = React.useState(true)
262
+ const [slash, setSlash] = React.useState<SlashState>({ open: false, query: "", range: null, rect: null })
263
+ const [slashActive, setSlashActive] = React.useState(0)
264
+ const [linkAt, setLinkAt] = React.useState<{ top: number; left: number } | null>(null)
265
+ const [linkCard, setLinkCard] = React.useState<{ href: string; pos: number; top: number; left: number } | null>(null)
266
+ const [menuAt, setMenuAt] = React.useState<number | null>(null)
267
+ const contentRef = React.useRef<HTMLDivElement>(null)
268
+ const latest = React.useRef(doc)
269
+ latest.current = doc
270
+ const slashKeys = React.useRef<(e: KeyboardEvent) => boolean>(() => false)
271
+ const cardTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
272
+ // M5: Suggesting mode's local changes and their flush.
273
+ const suggestingRef = React.useRef(suggesting)
274
+ suggestingRef.current = suggesting
275
+ const inFlight = React.useRef(new Set<string>())
276
+ const isLocal = React.useCallback((id: string) => id.startsWith(LOCAL_PREFIX) && !inFlight.current.has(id), [])
277
+ const quiet = React.useRef(false)
278
+ const flushTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
279
+ const flushRef = React.useRef<() => Promise<void>>(async () => undefined)
280
+ const [active, setActive] = React.useState<string | null>(null)
281
+ const activeRef = React.useRef<(id: string | null) => void>(() => undefined)
282
+ const [composer, setComposer] = React.useState<{ blockId: string; quote: string } | null>(null)
283
+ const [railOpen, setRailOpen] = React.useState(true)
284
+ const [drawerOpen, setDrawerOpen] = React.useState(false)
285
+ const [pendingChanges, setPendingChanges] = React.useState<LocalChange[]>([])
286
+ const [collabError, setCollabError] = React.useState(false)
287
+ const [tick, setTick] = React.useState(0)
288
+ const wide = useWideRail()
289
+
290
+ const editor = useEditor({
291
+ immediatelyRender: false,
292
+ editable,
293
+ extensions: [
294
+ SlashCommand.configure({ onState: setSlash, onKeyDown: (e) => slashKeys.current(e) }),
295
+ FieldTrigger.configure({ onState: setFieldQuery, onKeyDown: (e) => fieldKeys.current(e) }),
296
+ PagePagination,
297
+ ...documentExtensions({ placeholder: labels.placeholder }).map((ext) =>
298
+ ext.name === "documentBehaviour"
299
+ ? DocumentBehaviour.configure({ onBlockMenu: setMenuAt })
300
+ : ext.name === "unknownBlock"
301
+ ? UnknownBlock.configure({ label: (type) => fill(labels.laterBlock, { block: type }) })
302
+ : ext.name === "suggesting"
303
+ ? Suggesting.configure({ isLocal, onActivate: (id) => activeRef.current(id) })
304
+ : ext
305
+ ),
306
+ ],
307
+ content: toEditorContent(collab ? rendered.blocks : doc.blocks),
308
+ editorProps: {
309
+ attributes: {
310
+ class: "wy-doc",
311
+ "aria-label": doc.title || labels.untitled,
312
+ "aria-multiline": "true",
313
+ role: "textbox",
314
+ },
315
+ },
316
+ onUpdate: ({ editor: e }) => {
317
+ setTick((n) => n + 1)
318
+ if (quiet.current) return
319
+ if (suggestingRef.current) {
320
+ // Nothing is saved to the draft in Suggesting: the changes go out as suggestions.
321
+ clearTimeout(flushTimer.current)
322
+ flushTimer.current = setTimeout(() => void flushRef.current(), FLUSH_DELAY_MS)
323
+ return
324
+ }
325
+ const blocks = fromEditorContent(e.getJSON())
326
+ // Suggestions are drawn onto the draft as marks; they are never saved into it.
327
+ onChange({ ...latest.current, blocks: hasSuggestionMarks(blocks) ? stripSuggestions(blocks) : blocks })
328
+ },
329
+ onBlur: () => {
330
+ if (suggestingRef.current) void flushRef.current()
331
+ },
332
+ })
333
+
334
+ React.useEffect(() => {
335
+ editor?.setEditable(editable)
336
+ }, [editor, editable])
337
+
338
+ /* ------------------------------------------- Comments and suggestions */
339
+
340
+ // The plugin's switches: Suggesting on or off, the threads to highlight, format suggestions, the active card.
341
+ React.useEffect(() => {
342
+ if (!editor) return
343
+ editor.view.dispatch(editor.state.tr.setMeta(suggestingKey, { enabled: suggesting && editable }).setMeta("addToHistory", false))
344
+ }, [editor, suggesting, editable])
345
+ const threads = collab?.threads
346
+ React.useEffect(() => {
347
+ if (!editor) return
348
+ const anchors: CollabThreadAnchor[] = showCollab
349
+ ? (threads ?? []).filter((t) => !t.resolved).map((t) => ({ id: t.id, blockId: t.anchorBlockId, quote: t.quote }))
350
+ : []
351
+ if (composer) anchors.push({ id: "composer", blockId: composer.blockId, quote: composer.quote })
352
+ editor.view.dispatch(editor.state.tr.setMeta(suggestingKey, { threads: anchors }).setMeta("addToHistory", false))
353
+ }, [editor, threads, composer, showCollab])
354
+ React.useEffect(() => {
355
+ if (!editor) return
356
+ editor.view.dispatch(
357
+ editor.state.tr.setMeta(suggestingKey, { serverFormats: showCollab ? rendered.formats : [] }).setMeta("addToHistory", false)
358
+ )
359
+ }, [editor, rendered, showCollab])
360
+ React.useEffect(() => {
361
+ if (!editor) return
362
+ editor.view.dispatch(editor.state.tr.setMeta(suggestingKey, { active }).setMeta("addToHistory", false))
363
+ }, [editor, active])
364
+ // Clicking a highlight or a suggestion makes its card active too (E.6).
365
+ activeRef.current = (id) => {
366
+ if (id === null) return
367
+ setActive(id)
368
+ if (wide) setRailOpen(true)
369
+ }
370
+
371
+ /** Has the document any change of yours not yet sent? */
372
+ const hasLocal = React.useCallback(() => {
373
+ if (!editor) return false
374
+ if (pendingFormats(editor.state).length) return true
375
+ return JSON.stringify(editor.getJSON()).includes(`"${LOCAL_PREFIX}`)
376
+ }, [editor])
377
+
378
+ // Draw the server's suggestions onto the draft again when they or the draft changed (a decision,
379
+ // someone else's suggestion), once nothing of yours is waiting to be sent.
380
+ const redraw = React.useCallback(() => {
381
+ if (!editor || !collab || hasLocal()) return
382
+ const current = fromEditorContent(editor.getJSON())
383
+ if (JSON.stringify(current) === JSON.stringify(rendered.blocks)) return
384
+ const { from, to } = editor.state.selection
385
+ const content = toEditorContent(rendered.blocks)
386
+ const nodes = (content.content ?? []).map((n) => editor.schema.nodeFromJSON(n))
387
+ const tr = editor.state.tr.replaceWith(0, editor.state.doc.content.size, nodes)
388
+ const size = tr.doc.content.size
389
+ try {
390
+ tr.setSelection(TextSelection.create(tr.doc, Math.min(from, size), Math.min(to, size)))
391
+ } catch {
392
+ // The old caret isn't a text position any more: keep the mapped one.
393
+ }
394
+ tr.setMeta(suggestingKey, { skip: true }).setMeta("addToHistory", false)
395
+ quiet.current = true
396
+ try {
397
+ editor.view.dispatch(tr)
398
+ } finally {
399
+ quiet.current = false
400
+ }
401
+ }, [editor, collab, rendered, hasLocal])
402
+ const [redrawAsk, setRedrawAsk] = React.useState(0)
403
+ React.useEffect(() => {
404
+ redraw()
405
+ }, [redraw, redrawAsk])
406
+
407
+ const flush = React.useCallback(async () => {
408
+ clearTimeout(flushTimer.current)
409
+ if (!editor || !collab?.onSuggest || inFlight.current.size) return
410
+ const changes = collectPatches(fromEditorContent(editor.getJSON()), pendingFormats(editor.state), isLocal)
411
+ if (!changes.length) return
412
+ const ids = changes.flatMap((c) => c.localIds)
413
+ ids.forEach((id) => inFlight.current.add(id))
414
+ let failed = false
415
+ try {
416
+ for (const change of changes) {
417
+ try {
418
+ const saved = await collab.onSuggest({ kind: change.kind, summary: change.summary, patch: change.patch })
419
+ if (change.kind === "format") {
420
+ // The server's format suggestion draws its own underline from now on.
421
+ editor.view.dispatch(editor.state.tr.setMeta(suggestingKey, { dropFormats: change.localIds }).setMeta("addToHistory", false))
422
+ } else {
423
+ for (const id of change.localIds) editor.view.dispatch(renameSuggestion(editor.state, id, saved.id))
424
+ }
425
+ } catch {
426
+ failed = true
427
+ }
428
+ }
429
+ } finally {
430
+ ids.forEach((id) => inFlight.current.delete(id))
431
+ setCollabError(failed)
432
+ }
433
+ if (failed) {
434
+ // Kept as local changes: the next edit, or this retry, sends them again.
435
+ clearTimeout(flushTimer.current)
436
+ flushTimer.current = setTimeout(() => void flushRef.current(), FLUSH_DELAY_MS * 4)
437
+ }
438
+ // Draw again on the next render, with the suggestions the server returned (they arrive as props).
439
+ else setRedrawAsk((n) => n + 1)
440
+ }, [editor, collab, isLocal])
441
+ flushRef.current = flush
442
+ React.useEffect(() => () => clearTimeout(flushTimer.current), [])
443
+ // Leaving Suggesting sends what's waiting.
444
+ React.useEffect(() => {
445
+ if (!suggesting) void flushRef.current()
446
+ }, [suggesting])
447
+
448
+ // Your changes not yet sent show as cards too.
449
+ React.useEffect(() => {
450
+ if (!editor || !suggesting) {
451
+ setPendingChanges((prev) => (prev.length ? [] : prev))
452
+ return
453
+ }
454
+ setPendingChanges(collectPatches(fromEditorContent(editor.getJSON()), pendingFormats(editor.state), (id) => id.startsWith(LOCAL_PREFIX)))
455
+ }, [editor, suggesting, tick])
456
+
457
+ const startComment = React.useCallback(() => {
458
+ if (!editor || !canComment) return
459
+ const { from, to, $from } = editor.state.selection
460
+ const blockId = $from.parent.attrs.id as string | null
461
+ if (from === to || !blockId || !$from.parent.isTextblock) return
462
+ // The quote is the selection's text within its first block (E.39 matches it there).
463
+ const end = Math.min(to, $from.end())
464
+ const quote = editor.state.doc.textBetween(from, end, undefined, "\uFFFC")
465
+ if (!quote.trim()) return
466
+ setComposer({ blockId, quote })
467
+ setActive("composer")
468
+ if (wide) setRailOpen(true)
469
+ else setDrawerOpen(true)
470
+ }, [editor, canComment, wide])
471
+
472
+ // ⌥⌘M (Ctrl+Alt+M): comment on the selection.
473
+ React.useEffect(() => {
474
+ if (!editor || !canComment) return
475
+ const onKey = (e: KeyboardEvent) => {
476
+ if (!(e.metaKey || e.ctrlKey) || !e.altKey || e.code !== "KeyM") return
477
+ e.preventDefault()
478
+ startComment()
479
+ }
480
+ const dom = editor.view.dom
481
+ dom.addEventListener("keydown", onKey)
482
+ return () => dom.removeEventListener("keydown", onKey)
483
+ }, [editor, canComment, startComment])
484
+
485
+ const meId = collab?.me?.id
486
+ const railItems = React.useMemo<RailItem[]>(() => {
487
+ if (!collab) return []
488
+ const unplaced = new Set(rendered.unplaced)
489
+ const me = collab.me ?? { kind: "person" as const, id: "", name: labels.you }
490
+ const items: RailItem[] = [
491
+ ...suggestions.map((s) => ({ kind: "suggestion" as const, id: s.id, suggestion: s, unplaced: unplaced.has(s.id) })),
492
+ ...pendingChanges.map((c) => ({
493
+ kind: "suggestion" as const,
494
+ id: c.localIds[0],
495
+ pending: true,
496
+ suggestion: { id: c.localIds[0], by: me, at: "", summary: c.summary, kind: c.kind, patch: c.patch, status: "open" as const },
497
+ })),
498
+ ...collab.threads.filter((t) => !t.resolved).map((t) => ({ kind: "thread" as const, id: t.id, thread: t })),
499
+ ]
500
+ if (composer) items.push({ kind: "composer", id: "composer", quote: composer.quote })
501
+ return items
502
+ }, [collab, suggestions, rendered.unplaced, pendingChanges, composer, labels.you])
503
+ const resolvedItems = React.useMemo<RailItem[]>(
504
+ () => (collab?.threads ?? []).filter((t) => t.resolved).map((t) => ({ kind: "thread" as const, id: t.id, thread: t })),
505
+ [collab?.threads]
506
+ )
507
+
508
+ const anchorPos = React.useCallback(
509
+ (item: RailItem): number | null => {
510
+ if (!editor) return null
511
+ const pmDoc = editor.state.doc
512
+ let pos: number | null = null
513
+ if (item.kind === "suggestion") {
514
+ pos = suggestionPos(pmDoc, item.id, rendered.formats)
515
+ if (pos === null && item.pending) {
516
+ const f = suggestingKey.getState(editor.state)?.formats.find((x) => x.id === item.id)
517
+ pos = f ? f.from : null
518
+ }
519
+ } else if (item.kind === "thread") {
520
+ const anchor = { id: item.id, blockId: item.thread.anchorBlockId, quote: item.thread.quote }
521
+ // A thread whose text has gone stays beside its block.
522
+ pos = threadRange(pmDoc, anchor)?.from ?? findBlockNode(pmDoc, anchor.blockId)?.pos ?? null
523
+ } else if (composer) {
524
+ pos = threadRange(pmDoc, { id: "composer", blockId: composer.blockId, quote: composer.quote })?.from ?? null
525
+ }
526
+ return pos === null ? null : Math.min(pos, pmDoc.content.size)
527
+ },
528
+ [editor, rendered.formats, composer]
529
+ )
530
+ const anchorTop = React.useCallback(
531
+ (item: RailItem): number | null => {
532
+ const pos = anchorPos(item)
533
+ if (!editor || pos === null) return null
534
+ try {
535
+ return editor.view.coordsAtPos(pos).top
536
+ } catch {
537
+ return null
538
+ }
539
+ },
540
+ [editor, anchorPos]
541
+ )
542
+
543
+ const railActions = React.useMemo<RailActions>(
544
+ () => ({
545
+ canEdit,
546
+ canComment,
547
+ onDecide: collab?.onDecide
548
+ ? (id, decision) => {
549
+ setActive(null)
550
+ collab.onDecide!(id, decision).then(
551
+ () => setCollabError(false),
552
+ () => setCollabError(true)
553
+ )
554
+ }
555
+ : undefined,
556
+ onDecideAll: collab?.onDecideAll
557
+ ? (decision, filter) =>
558
+ void collab.onDecideAll!(decision, filter).then(
559
+ () => setCollabError(false),
560
+ () => setCollabError(true)
561
+ )
562
+ : undefined,
563
+ onReply: collab?.onReply,
564
+ onResolve: collab?.onResolve
565
+ ? (id) => {
566
+ setActive(null)
567
+ collab.onResolve!(id).catch(() => setCollabError(true))
568
+ }
569
+ : undefined,
570
+ onReopen: collab?.onReopen ? (id) => void collab.onReopen!(id).catch(() => setCollabError(true)) : undefined,
571
+ onComment: collab?.onComment
572
+ ? async (body, mentions) => {
573
+ if (!composer) return
574
+ const thread = await collab.onComment!({ anchorBlockId: composer.blockId, quote: composer.quote, body, mentions })
575
+ setComposer(null)
576
+ setActive(thread.id)
577
+ }
578
+ : undefined,
579
+ onCancelComment: () => {
580
+ setComposer(null)
581
+ setActive(null)
582
+ },
583
+ searchPeople: collab?.searchPeople,
584
+ }),
585
+ [canEdit, canComment, collab, composer]
586
+ )
587
+ const collabCount = railItems.filter((i) => i.kind !== "composer").length
588
+ const railShown = showCollab && wide && railOpen
589
+ const refused = useEditorState({ editor, selector: ({ editor: e }) => (e ? (suggestingKey.getState(e.state)?.refused ?? 0) : 0) })
590
+ const [refusedNote, setRefusedNote] = React.useState(false)
591
+ React.useEffect(() => {
592
+ if (!refused) return
593
+ setRefusedNote(true)
594
+ const timer = setTimeout(() => setRefusedNote(false), 4000)
595
+ return () => clearTimeout(timer)
596
+ }, [refused])
597
+
598
+ const relative = React.useCallback((rect: { top: number; bottom: number; left: number }) => {
599
+ const box = contentRef.current?.getBoundingClientRect()
600
+ if (!box) return { top: 0, left: 0 }
601
+ return { top: rect.bottom - box.top + 6, left: Math.max(0, rect.left - box.left) }
602
+ }, [])
603
+
604
+ const openLink = React.useCallback(
605
+ (at?: number) => {
606
+ if (!editor) return
607
+ if (at !== undefined) editor.chain().focus().setTextSelection(at).extendMarkRange("link").run()
608
+ const { from, to } = editor.state.selection
609
+ if (from === to && !editor.isActive("link")) return
610
+ const start = editor.view.coordsAtPos(from)
611
+ setLinkCard(null)
612
+ setLinkAt(relative(start))
613
+ },
614
+ [editor, relative]
615
+ )
616
+
617
+ // ⌘K (E.36): with text selected it adds a link; with nothing selected it opens the command palette.
618
+ React.useEffect(() => {
619
+ if (!editor) return
620
+ const onKey = (e: KeyboardEvent) => {
621
+ if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== "k" || e.shiftKey || e.altKey) return
622
+ if (!editor.view.hasFocus()) return
623
+ e.preventDefault()
624
+ e.stopPropagation()
625
+ if (editable && !editor.state.selection.empty) openLink()
626
+ else onCommandPalette?.()
627
+ }
628
+ const dom = editor.view.dom
629
+ dom.addEventListener("keydown", onKey, true)
630
+ return () => dom.removeEventListener("keydown", onKey, true)
631
+ }, [editor, editable, openLink, onCommandPalette])
632
+
633
+ // Hovering a link shows where it goes.
634
+ React.useEffect(() => {
635
+ if (!editor) return
636
+ const dom = editor.view.dom
637
+ const over = (e: MouseEvent) => {
638
+ const a = (e.target as HTMLElement).closest?.("a[href]") as HTMLAnchorElement | null
639
+ if (!a || !dom.contains(a)) return
640
+ clearTimeout(cardTimer.current)
641
+ const pos = editor.view.posAtDOM(a, 0)
642
+ const r = a.getBoundingClientRect()
643
+ setLinkCard({ href: a.getAttribute("href") ?? "", pos, ...relative(r) })
644
+ }
645
+ const out = (e: MouseEvent) => {
646
+ if ((e.target as HTMLElement).closest?.("a[href]")) {
647
+ cardTimer.current = setTimeout(() => setLinkCard(null), 300)
648
+ }
649
+ }
650
+ dom.addEventListener("mouseover", over)
651
+ dom.addEventListener("mouseout", out)
652
+ return () => {
653
+ dom.removeEventListener("mouseover", over)
654
+ dom.removeEventListener("mouseout", out)
655
+ }
656
+ }, [editor, relative])
657
+
658
+ const slashItems = React.useMemo(() => filterCatalogue(slash.query, labels, EDITOR_LABELS), [slash.query, labels])
659
+ React.useEffect(() => setSlashActive(0), [slash.query, slash.open])
660
+ const pickSlash = React.useCallback(
661
+ (index: number) => {
662
+ const item = slashItems[index]
663
+ if (!editor || !item || !slash.range) return
664
+ editor.chain().focus().deleteRange(slash.range).run()
665
+ setSlash({ open: false, query: "", range: null, rect: null })
666
+ applyItem(editor, item)
667
+ },
668
+ [editor, slash.range, slashItems]
669
+ )
670
+ slashKeys.current = (e) => {
671
+ if (!slash.open) return false
672
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
673
+ const n = slashItems.length || 1
674
+ setSlashActive((i) => (i + (e.key === "ArrowDown" ? 1 : n - 1)) % n)
675
+ return true
676
+ }
677
+ if (e.key === "Enter") {
678
+ if (!slashItems.length) return false
679
+ pickSlash(slashActive)
680
+ return true
681
+ }
682
+ return false
683
+ }
684
+
685
+ // A template's own fields (`template.<key>`) join the record type's, as their own group.
686
+ const ownFields = doc.ownFields
687
+ const allFields = React.useMemo<FieldGroup[] | undefined>(() => {
688
+ if (!fields) return undefined
689
+ if (!ownFields?.length) return fields
690
+ const items = ownFields.map((f) => ({ path: `template.${f.key}`, label: f.label, sample: f.sample }))
691
+ return [...fields, { group: labels.fieldsThisTemplate, items }]
692
+ }, [fields, ownFields, labels.fieldsThisTemplate])
693
+ const createField = React.useCallback(
694
+ (label: string): FieldDef => {
695
+ const current = latest.current.ownFields ?? []
696
+ const key = ownFieldKey(label, current.map((f) => f.key))
697
+ onChange({ ...latest.current, ownFields: [...current, { key, label }] })
698
+ return { path: `template.${key}`, label }
699
+ },
700
+ [onChange]
701
+ )
702
+ const fieldGroups = React.useMemo(() => filterFields(allFields ?? [], fieldQuery.query), [allFields, fieldQuery.query])
703
+ const fieldList = flatFields(fieldGroups)
704
+ const fieldOpen = fieldQuery.open && !!allFields?.length
705
+ React.useEffect(() => setFieldActive(0), [fieldQuery.query, fieldQuery.open])
706
+ const pickField = React.useCallback(
707
+ (index: number) => {
708
+ const field = fieldList[index]
709
+ if (!editor || !field || !fieldQuery.range) return
710
+ editor.chain().focus().deleteRange(fieldQuery.range).run()
711
+ setFieldQuery({ open: false, query: "", range: null, rect: null })
712
+ insertField(editor, field)
713
+ },
714
+ [editor, fieldList, fieldQuery.range]
715
+ )
716
+ fieldKeys.current = (e) => {
717
+ if (!fieldOpen) return false
718
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
719
+ const n = fieldList.length || 1
720
+ setFieldActive((i) => (i + (e.key === "ArrowDown" ? 1 : n - 1)) % n)
721
+ return true
722
+ }
723
+ if (e.key === "Enter") {
724
+ if (!fieldList.length) return false
725
+ pickField(fieldActive)
726
+ return true
727
+ }
728
+ return false
729
+ }
730
+
731
+ // Fit width follows the canvas.
732
+ React.useEffect(() => {
733
+ const el = canvasRef.current
734
+ if (!el) return
735
+ const ro = new ResizeObserver(() => setCanvasWidth(el.clientWidth))
736
+ ro.observe(el)
737
+ return () => ro.disconnect()
738
+ }, [view])
739
+ const zoomFactor = zoom === "fit" ? fitZoom(canvasWidth) : zoom / 100
740
+
741
+ const openPublish = React.useCallback(async () => {
742
+ if (!publish || !editor) return
743
+ setCheckOpen(true)
744
+ setChecking(true)
745
+ try {
746
+ setBlockers(await publish.check())
747
+ } catch {
748
+ setBlockers([])
749
+ } finally {
750
+ setChecking(false)
751
+ }
752
+ }, [publish, editor])
753
+
754
+ const fieldLabel = React.useCallback(
755
+ (path: string) => allFields?.flatMap((g) => g.items).find((f) => f.path === path)?.label ?? path,
756
+ [allFields]
757
+ )
758
+ const fixBlocker = React.useCallback(
759
+ (b: PublishBlocker) => {
760
+ if (publish?.onFix) return publish.onFix(b)
761
+ // Review: the suggestions are in the rail, or the drawer under 1024px (E.37).
762
+ if (b.kind === "open-suggestions" && collab) {
763
+ if (wide) setRailOpen(true)
764
+ else setDrawerOpen(true)
765
+ return
766
+ }
767
+ if (!editor) return
768
+ // Show: select the first place the blocker is in the document.
769
+ let at = -1
770
+ editor.state.doc.descendants((node, pos) => {
771
+ if (at >= 0) return false
772
+ if (b.kind === "unknown-field" && node.type.name === "field" && node.attrs.path === b.path) at = pos
773
+ if (b.kind === "block-without-print-view" && node.attrs.id === b.blockId) at = pos
774
+ return true
775
+ })
776
+ if (at >= 0) editor.chain().focus().setNodeSelection(at).scrollIntoView().run()
777
+ },
778
+ [publish, editor, collab, wide]
779
+ )
780
+
781
+ const meta = useEditorState({
782
+ editor,
783
+ selector: ({ editor: e }) => {
784
+ if (!e) return { words: 0, headings: [] as { level: number; text: string; pos: number; current: boolean }[] }
785
+ const caret = e.state.selection.from
786
+ const headings: { level: number; text: string; pos: number; current: boolean }[] = []
787
+ e.state.doc.forEach((node, pos) => {
788
+ if (node.type.name === "heading") headings.push({ level: Number(node.attrs.level), text: node.textContent, pos, current: false })
789
+ })
790
+ const current = [...headings].reverse().find((h) => h.pos <= caret)
791
+ if (current) current.current = true
792
+ // The document's title heads the outline, current until the caret passes the first heading.
793
+ headings.unshift({ level: 0, text: "", pos: -1, current: !current })
794
+ return { words: countWords(e), headings }
795
+ },
796
+ })
797
+
798
+ const lineDir = doc.lang === "ar" ? "rtl" : "ltr"
799
+ const modeLabel = mode === "editing" ? labels.modeEditing : suggesting ? labels.modeSuggesting : labels.modeViewing
800
+ const saveText =
801
+ !save
802
+ ? null
803
+ : save.state === "saved"
804
+ ? fill(labels.saved, { time: save.at })
805
+ : save.state === "saving"
806
+ ? labels.saving
807
+ : save.state === "offline"
808
+ ? labels.offline
809
+ : labels.saveFailed
810
+
811
+ return (
812
+ <div
813
+ data-slot="doc-editor"
814
+ dir={lineDir}
815
+ lang={doc.lang}
816
+ className={cn("grid h-full min-h-0 grid-rows-[auto_auto_1fr_auto] overflow-hidden bg-background text-sm text-foreground", className)}
817
+ >
818
+ {/* Header (56px) */}
819
+ <header className="flex h-14 min-w-0 items-center gap-3 border-b border-border bg-card ps-2 pe-4">
820
+ {back && <IconButton icon="chevron-left" label={back.label} tooltip="bottom" onClick={back.onClick} />}
821
+ <span aria-hidden="true" className="grid size-8 shrink-0 place-items-center rounded-[8px] bg-primary-tint text-primary-tint-foreground">
822
+ <Icon name={KIND_ICON[doc.kind]} />
823
+ </span>
824
+ <div className="grid min-w-0 flex-1 gap-px">
825
+ <input
826
+ aria-label={labels.documentTitle}
827
+ value={doc.title}
828
+ placeholder={labels.untitled}
829
+ readOnly={!editable || suggesting}
830
+ onChange={(e) => onChange({ ...latest.current, title: e.target.value })}
831
+ size={Math.max(12, Math.min(48, doc.title.length + 2))}
832
+ className="-ms-[7px] w-fit max-w-full rounded-[6px] border border-transparent bg-transparent px-1.5 py-px text-[0.9375rem] leading-[1.3] font-semibold text-foreground outline-none hover:border-border focus-visible:border-input"
833
+ />
834
+ <div className="flex items-center gap-1.5 overflow-hidden text-xs whitespace-nowrap text-muted-foreground">
835
+ {path && (
836
+ <>
837
+ {path}
838
+ {saveText && <span aria-hidden="true">·</span>}
839
+ </>
840
+ )}
841
+ {saveText && (
842
+ <span role="status" className="inline-flex items-center gap-1">
843
+ {save?.state === "saved" && <Icon name="check" size={12} />}
844
+ {save?.state === "error" && <Icon name="alert" size={12} className="text-error-text" />}
845
+ {publish && save?.state === "saved" ? fill(labels.draftSaved, { time: save.at }) : saveText}
846
+ {publish && (
847
+ <span>
848
+ {" · "}
849
+ {publish.publishedVersion ? fill(labels.publishedInUse, { n: publish.publishedVersion }) : labels.notPublished}
850
+ </span>
851
+ )}
852
+ </span>
853
+ )}
854
+ </div>
855
+ </div>
856
+ <div className="flex shrink-0 items-center gap-2">
857
+ <DropdownMenu modal={false}>
858
+ <DropdownMenuTrigger asChild>
859
+ <button
860
+ type="button"
861
+ aria-label={`${labels.modeMenu}: ${modeLabel}`}
862
+ className={cn(
863
+ "inline-flex h-7 items-center gap-1.5 rounded-control-sm border border-input bg-card ps-2.5 pe-2 text-[0.8125rem] font-medium text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
864
+ // While suggesting the button sits on the tint, so it's never forgotten (E.10).
865
+ suggesting && "border-primary bg-primary-tint text-primary-tint-foreground"
866
+ )}
867
+ >
868
+ <Icon name={MODE_ICON[mode]} size={14} />
869
+ {modeLabel}
870
+ <Icon name="chevron-down" size={14} />
871
+ </button>
872
+ </DropdownMenuTrigger>
873
+ <DropdownMenuContent align="end" className="w-[300px] p-1">
874
+ <ModeItem
875
+ icon={canEdit ? "edit" : "lock"}
876
+ title={labels.modeEditing}
877
+ hint={canEdit ? labels.modeEditingHint : labels.modeEditingLocked}
878
+ on={mode === "editing"}
879
+ disabled={!canEdit}
880
+ onSelect={() => onModeChange?.("editing")}
881
+ />
882
+ {canSuggest && (
883
+ <ModeItem
884
+ icon="suggest"
885
+ title={labels.modeSuggesting}
886
+ hint={canEdit ? labels.modeSuggestingHint : labels.modeSuggestingHintNoEdit}
887
+ on={suggesting}
888
+ onSelect={() => onModeChange?.("suggesting")}
889
+ />
890
+ )}
891
+ <ModeItem
892
+ icon="view"
893
+ title={labels.modeViewing}
894
+ hint={canComment ? labels.modeViewingCommentHint : labels.modeViewingHint}
895
+ on={mode === "viewing"}
896
+ onSelect={() => onModeChange?.("viewing")}
897
+ />
898
+ </DropdownMenuContent>
899
+ </DropdownMenu>
900
+ {showCollab && (
901
+ <span className="relative">
902
+ <IconButton
903
+ icon="comment"
904
+ label={labels.commentsAndSuggestions}
905
+ tooltip="bottom"
906
+ pressed={railShown || drawerOpen}
907
+ onClick={() => (wide ? setRailOpen((o) => !o) : setDrawerOpen(true))}
908
+ />
909
+ {collabCount > 0 && (
910
+ <b
911
+ aria-hidden="true"
912
+ className="pointer-events-none absolute -top-0.5 -end-0.5 grid h-4 min-w-4 place-items-center rounded-full bg-primary px-1 text-2xs leading-none font-semibold text-primary-foreground"
913
+ >
914
+ {collabCount}
915
+ </b>
916
+ )}
917
+ </span>
918
+ )}
919
+ {onPreview && !preview && (
920
+ <Button variant="outline" size="sm" icon="view" onClick={onPreview}>
921
+ {labels.preview}
922
+ </Button>
923
+ )}
924
+ {isLabel && onPrintLabels && (
925
+ <Button variant="outline" size="sm" icon="print" onClick={onPrintLabels}>
926
+ {labels.printLabels}
927
+ </Button>
928
+ )}
929
+ {onExportPdf && (
930
+ <Button variant="outline" size="sm" icon="download" onClick={() => void onExportPdf()}>
931
+ {labels.pdf}
932
+ </Button>
933
+ )}
934
+ {publish && (
935
+ <Button size="sm" icon="check" disabled={!canEdit} onClick={() => void openPublish()}>
936
+ {labels.publish}
937
+ </Button>
938
+ )}
939
+ </div>
940
+ </header>
941
+
942
+ {/* Toolbar (44px) */}
943
+ {editor ? (
944
+ <EditorToolbar
945
+ editor={editor}
946
+ labels={labels}
947
+ editable={editable}
948
+ outline={outlineOpen}
949
+ onOutline={() => setOutlineOpen((o) => !o)}
950
+ onLink={() => openLink()}
951
+ fields={allFields}
952
+ onCreateField={fields && editable && !suggesting ? createField : undefined}
953
+ onComment={showCollab && canComment ? startComment : undefined}
954
+ view={view}
955
+ onView={doc.kind === "label" ? undefined : setView}
956
+ zoom={zoom}
957
+ onZoom={setZoom}
958
+ sheet={
959
+ isLabel ? (
960
+ <LabelSetup
961
+ grid={labelGrid}
962
+ sheet={sheetSize}
963
+ disabled={!editable}
964
+ labels={labels}
965
+ onChange={(grid, sheet) =>
966
+ onChange({ ...latest.current, labels: grid, page: { size: sheet, marginMm: 16, letterhead: false } })
967
+ }
968
+ />
969
+ ) : undefined
970
+ }
971
+ />
972
+ ) : (
973
+ <div className="h-11 border-b border-border bg-card" />
974
+ )}
975
+
976
+ {/* Body: outline, canvas */}
977
+ <div
978
+ className={cn(
979
+ "relative grid min-h-0 overflow-auto",
980
+ railShown
981
+ ? outlineOpen
982
+ ? "grid-cols-[minmax(0,1fr)_300px] xl:grid-cols-[220px_minmax(0,1fr)_300px]"
983
+ : "grid-cols-[minmax(0,1fr)_300px]"
984
+ : outlineOpen
985
+ ? "xl:grid-cols-[220px_minmax(0,1fr)]"
986
+ : "grid-cols-[minmax(0,1fr)]"
987
+ )}
988
+ >
989
+ {outlineOpen && (
990
+ <nav aria-label={labels.outline} className="sticky top-0 hidden content-start gap-0.5 self-start py-6 ps-4 pe-3 text-[0.8125rem] xl:grid">
991
+ <div className="px-2 pb-1.5 text-xs font-medium text-muted-foreground">{labels.outline}</div>
992
+ {meta && meta.headings.length <= 1 && <div className="order-last px-2 text-xs text-muted-foreground">{labels.outlineEmpty}</div>}
993
+ {meta?.headings.map((h) => (
994
+ <a
995
+ key={h.pos}
996
+ href="#"
997
+ aria-current={h.current ? "location" : undefined}
998
+ onClick={(e) => {
999
+ e.preventDefault()
1000
+ if (h.pos < 0) editor?.chain().focus("start").scrollIntoView().run()
1001
+ else editor?.chain().focus().setTextSelection(h.pos + 1).scrollIntoView().run()
1002
+ }}
1003
+ className={cn(
1004
+ "truncate rounded-[6px] border-s-2 border-transparent px-2 py-1 text-muted-foreground no-underline hover:bg-muted hover:text-foreground",
1005
+ h.level === 1 && "ps-5",
1006
+ h.level === 2 && "ps-8",
1007
+ h.level === 3 && "ps-11",
1008
+ h.current && "rounded-s-none border-primary text-primary-tint-foreground"
1009
+ )}
1010
+ >
1011
+ {(h.pos < 0 ? doc.title : h.text) || labels.untitled}
1012
+ </a>
1013
+ ))}
1014
+ </nav>
1015
+ )}
1016
+ <div ref={canvasRef} className={cn("min-w-0 pb-16", view === "page" ? "overflow-x-auto px-6 pt-5" : "px-6 pt-8")}>
1017
+ {preview && (
1018
+ <div className="wy-previewbar" role="status">
1019
+ <Icon name="view" size={14} />
1020
+ <span>{labels.previewingWith}</span>
1021
+ <b>{preview.label}</b>
1022
+ {onPreview && (
1023
+ <Button variant="ghost" size="sm" onClick={onPreview}>
1024
+ {labels.changeRecord}
1025
+ </Button>
1026
+ )}
1027
+ {onClosePreview && (
1028
+ <Button variant="ghost" size="sm" onClick={onClosePreview}>
1029
+ {labels.showFields}
1030
+ </Button>
1031
+ )}
1032
+ </div>
1033
+ )}
1034
+ {(() => {
1035
+ const content = (
1036
+ <EditorServicesProvider services={services} labels={labels} preview={preview}>
1037
+ <div ref={contentRef} className="relative">
1038
+ <EditorContent editor={editor} />
1039
+ {editor && (
1040
+ <>
1041
+ <BlockToolbar editor={editor} labels={labels} container={contentRef} />
1042
+ <BlockGutter editor={editor} labels={labels} container={contentRef} menuAt={menuAt} onMenuAtChange={setMenuAt} blockUrl={blockUrl} />
1043
+ <SelectionBubble
1044
+ editor={editor}
1045
+ labels={labels}
1046
+ onLink={() => openLink()}
1047
+ onComment={showCollab && canComment ? startComment : undefined}
1048
+ />
1049
+ </>
1050
+ )}
1051
+ {editor && slash.open && slash.rect && (
1052
+ <div className="absolute z-30" style={relative(slash.rect)}>
1053
+ <BlockList
1054
+ id="wy-slash"
1055
+ items={slashItems}
1056
+ active={Math.min(slashActive, Math.max(0, slashItems.length - 1))}
1057
+ onActive={setSlashActive}
1058
+ onPick={(item) => pickSlash(slashItems.indexOf(item))}
1059
+ labels={labels}
1060
+ footer={
1061
+ slash.query && editor.state.selection.$from.parent.textContent.trim() !== `/${slash.query}` ? (
1062
+ <span>{labels.slashInsertAfter}</span>
1063
+ ) : (
1064
+ <>
1065
+ <span>{labels.slashMove}</span>
1066
+ <span>{labels.slashInsert}</span>
1067
+ <span>{labels.slashClose}</span>
1068
+ </>
1069
+ )
1070
+ }
1071
+ />
1072
+ </div>
1073
+ )}
1074
+ {editor && fieldOpen && fieldQuery.rect && (
1075
+ <div className="absolute z-30" style={relative(fieldQuery.rect)}>
1076
+ <FieldPicker
1077
+ id="wy-fieldpick"
1078
+ groups={fieldGroups}
1079
+ query={fieldQuery.query}
1080
+ active={Math.min(fieldActive, Math.max(0, fieldList.length - 1))}
1081
+ onActive={setFieldActive}
1082
+ onPick={(field) => pickField(fieldList.indexOf(field))}
1083
+ labels={labels}
1084
+ />
1085
+ </div>
1086
+ )}
1087
+ {editor && linkAt && <LinkPopover editor={editor} labels={labels} position={linkAt} onClose={() => setLinkAt(null)} />}
1088
+ {editor && linkCard && !linkAt && (
1089
+ <LinkCard
1090
+ editor={editor}
1091
+ labels={labels}
1092
+ href={linkCard.href}
1093
+ pos={linkCard.pos}
1094
+ position={{ top: linkCard.top, left: linkCard.left }}
1095
+ onEdit={(pos) => openLink(pos)}
1096
+ onClose={() => setLinkCard(null)}
1097
+ onPointerEnter={() => clearTimeout(cardTimer.current)}
1098
+ onPointerLeave={() => setLinkCard(null)}
1099
+ />
1100
+ )}
1101
+ </div>
1102
+ </EditorServicesProvider>
1103
+ )
1104
+ if (isLabel) {
1105
+ return (
1106
+ <LabelSheetView editor={editor} grid={labelGrid} sheet={sheetSize} zoom={zoomFactor} theme={theme} labels={labels} onOverflow={setLabelOverflow}>
1107
+ {content}
1108
+ </LabelSheetView>
1109
+ )
1110
+ }
1111
+ return view === "page" ? (
1112
+ <PageView
1113
+ editor={editor}
1114
+ title={doc.title}
1115
+ letterhead={letterhead}
1116
+ theme={theme}
1117
+ reference={pageFields?.reference && <>{labels.reference} <LetterheadField field={pageFields.reference} preview={preview} labels={labels} /></>}
1118
+ // @date-display-ignore: a merge field (its chip, or the record's value the server already formatted as text), not a record timestamp.
1119
+ date={pageFields?.date && <LetterheadField field={pageFields.date} preview={preview} labels={labels} />}
1120
+ footerRef={pageFields?.reference && preview ? (preview.values[pageFields.reference.path] ?? undefined) : undefined}
1121
+ zoom={zoomFactor}
1122
+ labels={labels}
1123
+ onPages={setPages}
1124
+ >
1125
+ {content}
1126
+ </PageView>
1127
+ ) : (
1128
+ <article
1129
+ className="relative mx-auto box-border max-w-[760px] rounded-card border border-border bg-card px-[72px] pt-14 pb-[72px] max-md:px-6"
1130
+ style={themeStyle(theme)}
1131
+ >
1132
+ <h1
1133
+ className="wy-sheet__title m-0 mb-1.5 font-display text-[1.9375rem] leading-[1.15] font-semibold tracking-[-0.01em]"
1134
+ dir="auto"
1135
+ >
1136
+ {doc.title || <span className="text-muted-foreground">{labels.untitled}</span>}
1137
+ </h1>
1138
+ <div className="mb-7 flex items-center gap-2 text-[0.8125rem] text-muted-foreground">
1139
+ <Badge variant="secondary">{labels[KIND_LABEL[doc.kind]]}</Badge>
1140
+ </div>
1141
+ {content}
1142
+ </article>
1143
+ )
1144
+ })()}
1145
+ </div>
1146
+ {railShown && (
1147
+ <CollabRail
1148
+ items={railItems}
1149
+ resolved={resolvedItems}
1150
+ labels={labels}
1151
+ actions={railActions}
1152
+ active={active}
1153
+ onActive={setActive}
1154
+ anchorTop={anchorTop}
1155
+ meId={meId}
1156
+ layoutKey={`${tick}:${view}:${zoomFactor}:${pages}`}
1157
+ />
1158
+ )}
1159
+ </div>
1160
+ {showCollab && !wide && (
1161
+ <CollabDrawer
1162
+ open={drawerOpen}
1163
+ onOpenChange={setDrawerOpen}
1164
+ items={railItems}
1165
+ resolved={resolvedItems}
1166
+ labels={labels}
1167
+ actions={railActions}
1168
+ active={active}
1169
+ onActive={(id) => {
1170
+ setActive(id)
1171
+ // The drawer has no margin to sit beside: show the card's text instead.
1172
+ const item = railItems.find((i) => i.id === id)
1173
+ const pos = item ? anchorPos(item) : null
1174
+ if (pos !== null && editor) editor.chain().setTextSelection(pos).scrollIntoView().run()
1175
+ }}
1176
+ meId={meId}
1177
+ />
1178
+ )}
1179
+
1180
+ {/* Status bar (28px) */}
1181
+ <footer className="flex h-7 items-center gap-4 overflow-hidden border-t border-border bg-card px-4 text-xs whitespace-nowrap text-muted-foreground">
1182
+ <span>{meta?.words === 1 ? labels.word : fill(labels.words, { n: meta?.words ?? 0 })}</span>
1183
+ {isLabel ? (
1184
+ <>
1185
+ <span>{fill(labels.labelsPerSheet, { n: labelCells(labelGrid, sheetSize).length })}</span>
1186
+ <span dir="ltr">
1187
+ {sheetSize} · {labelGrid.size.widthMm} × {labelGrid.size.heightMm} mm
1188
+ </span>
1189
+ {labelOverflow && <span className="text-error-text">{labels.labelOverflow}</span>}
1190
+ </>
1191
+ ) : view === "page" ? (
1192
+ <>
1193
+ <span>{fill(labels.pageOf, { page: 1, pages })}</span>
1194
+ <span>{labels.pageSetup}</span>
1195
+ </>
1196
+ ) : (
1197
+ <span>{doc.lang === "ar" ? labels.arabic : labels.english}</span>
1198
+ )}
1199
+ <span>{labels[KIND_LABEL[doc.kind]]}</span>
1200
+ <span className="flex-1" />
1201
+ {(refusedNote || collabError) && (
1202
+ <span role="status" className="truncate text-warning-text">
1203
+ {refusedNote ? labels.sugRefused : labels.collabFailed}
1204
+ </span>
1205
+ )}
1206
+ <span>
1207
+ {preview
1208
+ ? fill(editable ? labels.previewEditingStatus : labels.previewStatus, { record: preview.label })
1209
+ : fill(labels.lastEdited, { name: actorName(doc.updatedBy), time: formatTime(doc.updatedAt) })}
1210
+ </span>
1211
+ </footer>
1212
+ {publish && (
1213
+ <PublishCheck
1214
+ open={checkOpen}
1215
+ onOpenChange={setCheckOpen}
1216
+ blockers={blockers}
1217
+ checking={checking}
1218
+ nextVersion={(publish.publishedVersion ?? 0) + 1}
1219
+ recordLabel={publish.recordLabel}
1220
+ onPublish={publish.publish}
1221
+ onFix={fixBlocker}
1222
+ labels={labels}
1223
+ fieldLabel={fieldLabel}
1224
+ />
1225
+ )}
1226
+ </div>
1227
+ )
1228
+ }
1229
+
1230
+ const MODE_ICON: Record<EditorMode, IconName> = { editing: "edit", suggesting: "suggest", viewing: "view" }
1231
+
1232
+ /** One line of the mode menu (E.10, the EditorCollab card's `.wy-modemenu`). */
1233
+ function ModeItem({
1234
+ icon,
1235
+ title,
1236
+ hint,
1237
+ on,
1238
+ disabled,
1239
+ onSelect,
1240
+ }: {
1241
+ icon: IconName
1242
+ title: string
1243
+ hint: string
1244
+ on: boolean
1245
+ disabled?: boolean
1246
+ onSelect: () => void
1247
+ }) {
1248
+ return (
1249
+ <DropdownMenuItem
1250
+ disabled={disabled}
1251
+ onSelect={onSelect}
1252
+ aria-current={on ? "true" : undefined}
1253
+ className={cn("wy-modemenu__it p-2", on && "is-on", disabled && "opacity-50")}
1254
+ >
1255
+ <Icon name={icon} />
1256
+ <span className="wy-modemenu__t">
1257
+ {title}
1258
+ <span>{hint}</span>
1259
+ </span>
1260
+ {on && <Icon name="check" />}
1261
+ </DropdownMenuItem>
1262
+ )
1263
+ }
1264
+
1265
+ /** A field in the letterhead: its chip while editing, the record's value in preview. */
1266
+ function LetterheadField({ field, preview, labels }: { field: FieldDef; preview: FieldPreview | null; labels: EditorLabels }) {
1267
+ if (!preview) return <span className="wy-mf" title={field.path}>{field.label}</span>
1268
+ const value = preview.values[field.path]
1269
+ if (value === null || value === undefined || value === "")
1270
+ return (
1271
+ <span className="wy-mf is-missing" title={labels.fieldMissing}>
1272
+ <Icon name="alert" size={12} />
1273
+ {field.label}
1274
+ </span>
1275
+ )
1276
+ return <span className="wy-mf is-preview">{value}</span>
1277
+ }
1278
+
1279
+ /** 24-hour times in Western digits (stage 5). */
1280
+ function formatTime(iso: string): string {
1281
+ const d = new Date(iso)
1282
+ if (Number.isNaN(d.getTime())) return iso
1283
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
1284
+ }
1285
+
1286
+
1287
+ export { DocEditor }