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