@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,353 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { Extension, type Editor } from "@tiptap/core"
5
+ import { Plugin, PluginKey } from "@tiptap/pm/state"
6
+ import { Decoration, DecorationSet } from "@tiptap/pm/view"
7
+
8
+ import { TenantLogo } from "../tenant-logo"
9
+ import { cn } from "../utils"
10
+ import type { LetterheadLine, ResolvedThemeTokens } from "./contract"
11
+ import { fill, type EditorLabels } from "./labels"
12
+
13
+ /**
14
+ * A4 at 96 dpi (EditorPageView): 794 × 1123px, 16mm margins (stage 6), 24px
15
+ * between pages on screen. The running header on the pages after the first
16
+ * takes RUN_HEADER px of the content box.
17
+ */
18
+ export const PAGE = { width: 794, height: 1123, margin: 60, gap: 24 } as const
19
+ const RUN_HEADER = 44
20
+
21
+ export interface Letterhead {
22
+ /** The tenant's logo, framed; without one, its initials on the print colour. */
23
+ logo?: string | null
24
+ /**
25
+ * E.44: how the logo shows. `square` (the default) frames it, `wide` shows a
26
+ * wordmark unframed, `none` prints the name without a mark.
27
+ */
28
+ logoShape?: "square" | "wide" | "none"
29
+ name: string
30
+ /** Address, tax number, phone and email lines at the start side. */
31
+ lines: string[]
32
+ }
33
+
34
+ /** Every workspace line a theme can put in the letterhead, by its theme name; null when not set. */
35
+ export type LetterheadParts = Record<LetterheadLine, string | null>
36
+
37
+ /** The workspace's uploaded logos (branding); null when one isn't uploaded. */
38
+ export interface BrandLogos {
39
+ wide: string | null
40
+ square: string | null
41
+ }
42
+
43
+ /**
44
+ * The letterhead a theme asks for (E.44, stage 6.2): the lines its
45
+ * `letterhead.lines` names, in that order, from `parts`; and the logo its
46
+ * `letterhead.logo` chooses, falling back to the other shape when that one
47
+ * isn't uploaded (and to the initials when neither is). Without a theme, or
48
+ * without the parts, the letterhead stays as `base` has it.
49
+ */
50
+ export function themedLetterhead(
51
+ base: Letterhead,
52
+ theme: Pick<ResolvedThemeTokens, "letterhead"> | null | undefined,
53
+ parts?: LetterheadParts | null,
54
+ logos?: BrandLogos | null
55
+ ): Letterhead {
56
+ if (!theme) return base
57
+ const { logo, lines } = theme.letterhead
58
+ const picked =
59
+ logo === "none"
60
+ ? { logo: null, logoShape: "none" as const }
61
+ : logo === "wide"
62
+ ? logos?.wide
63
+ ? { logo: logos.wide, logoShape: "wide" as const }
64
+ : { logo: logos?.square ?? null, logoShape: "square" as const }
65
+ : logos?.square
66
+ ? { logo: logos.square, logoShape: "square" as const }
67
+ : logos?.wide
68
+ ? { logo: logos.wide, logoShape: "wide" as const }
69
+ : { logo: null, logoShape: "square" as const }
70
+ return {
71
+ ...base,
72
+ ...(logos || logo === "none" ? picked : {}),
73
+ lines: parts ? lines.map((key) => parts[key]).filter((line): line is string => !!line && line.trim() !== "") : base.lines,
74
+ }
75
+ }
76
+
77
+ /**
78
+ * The theme's colours as the `--doc-*` variables the page view and sheet read
79
+ * (E.11): `--doc-accent` on paper, `--doc-accent-on-dark` for the continuous
80
+ * sheet's title in dark mode.
81
+ */
82
+ export function themeStyle(theme: ResolvedThemeTokens | null | undefined): React.CSSProperties | undefined {
83
+ if (!theme) return undefined
84
+ return { "--doc-accent": theme.accent, "--doc-accent-on-dark": theme.accentOnDark } as React.CSSProperties
85
+ }
86
+
87
+ /** The letterhead's mark at `size`, as the theme's logo shape asks. */
88
+ function LetterheadMark({ letterhead, size, showName }: { letterhead: Letterhead; size: number; showName?: boolean }) {
89
+ if (letterhead.logoShape === "none") return showName ? <span className="text-sm font-semibold text-foreground">{letterhead.name}</span> : <span />
90
+ return (
91
+ <TenantLogo
92
+ name={letterhead.name}
93
+ src={letterhead.logo}
94
+ size={size}
95
+ showName={showName}
96
+ shape={letterhead.logoShape === "wide" ? "wide" : "square"}
97
+ />
98
+ )
99
+ }
100
+
101
+ /* ------------------------------------------------------- Page breaks */
102
+
103
+ interface Spacer {
104
+ /** The document position the gap goes before. */
105
+ pos: number
106
+ height: number
107
+ }
108
+
109
+ const paginationKey = new PluginKey<DecorationSet>("pagePagination")
110
+
111
+ function spacerWidget(height: number) {
112
+ return () => {
113
+ const el = document.createElement("div")
114
+ el.className = "wy-pv__gap"
115
+ el.setAttribute("aria-hidden", "true")
116
+ el.contentEditable = "false"
117
+ el.style.height = `${height}px`
118
+ return el
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Pushes a block that would cross the bottom of a page to the top of the next
124
+ * one, and starts a page after every Page break block. Whity Render paginates
125
+ * the PDF itself (it measures rows); these breaks are a close preview (E.7).
126
+ */
127
+ export const PagePagination = Extension.create({
128
+ name: "pagePagination",
129
+ addProseMirrorPlugins() {
130
+ return [
131
+ new Plugin<DecorationSet>({
132
+ key: paginationKey,
133
+ state: {
134
+ init: () => DecorationSet.empty,
135
+ apply(tr, set) {
136
+ const next = tr.getMeta(paginationKey) as Spacer[] | undefined
137
+ if (next) {
138
+ return DecorationSet.create(
139
+ tr.doc,
140
+ next.map((s) => Decoration.widget(s.pos, spacerWidget(s.height), { side: -1, key: `gap-${s.pos}-${s.height}` }))
141
+ )
142
+ }
143
+ return set.map(tr.mapping, tr.doc)
144
+ },
145
+ },
146
+ props: { decorations: (state) => paginationKey.getState(state) },
147
+ }),
148
+ ]
149
+ },
150
+ })
151
+
152
+ function sameSpacers(a: Spacer[], b: Spacer[]): boolean {
153
+ return a.length === b.length && a.every((s, i) => s.pos === b[i].pos && Math.abs(s.height - b[i].height) < 2)
154
+ }
155
+
156
+ /**
157
+ * Lays the top-level blocks out on pages. `column` is the content column,
158
+ * `firstTop` where the editor's content starts on page 1 (below the
159
+ * letterhead), both in unzoomed px. Returns the number of pages.
160
+ */
161
+ function usePagination(editor: Editor | null, column: React.RefObject<HTMLDivElement | null>, enabled: boolean): number {
162
+ const [pages, setPages] = React.useState(1)
163
+ const applied = React.useRef<Spacer[]>([])
164
+
165
+ const layout = React.useCallback(() => {
166
+ if (!editor || editor.isDestroyed || !column.current) return
167
+ const view = editor.view
168
+ const box = column.current.getBoundingClientRect()
169
+ // CSS zoom scales what getBoundingClientRect reports; offsetWidth isn't.
170
+ const scale = column.current.offsetWidth ? box.width / column.current.offsetWidth : 1
171
+ const pageStart = (k: number) => k * (PAGE.height + PAGE.gap) + (k === 0 ? 0 : PAGE.margin + RUN_HEADER)
172
+ const pageEnd = (k: number) => k * (PAGE.height + PAGE.gap) + PAGE.height - PAGE.margin
173
+
174
+ const spacers: Spacer[] = []
175
+ let shiftBefore = 0 // the gaps applied last time above this block, to recover its natural place
176
+ let shift = 0 // the gaps this pass adds above it
177
+ let page = 0
178
+ let breakNext = false
179
+ const old = new Map(applied.current.map((s) => [s.pos, s.height]))
180
+
181
+ view.state.doc.forEach((node, offset) => {
182
+ const dom = view.nodeDOM(offset)
183
+ if (!(dom instanceof HTMLElement)) return
184
+ shiftBefore += old.get(offset) ?? 0
185
+ const r = dom.getBoundingClientRect()
186
+ const naturalTop = (r.top - box.top) / scale - shiftBefore
187
+ const height = r.height / scale
188
+ let top = naturalTop + shift
189
+ if (breakNext || (top + height > pageEnd(page) && top > pageStart(page) + 1)) {
190
+ const target = pageStart(page + 1)
191
+ const gap = Math.max(0, target - top)
192
+ if (gap > 0) spacers.push({ pos: offset, height: Math.round(gap) })
193
+ shift += gap
194
+ top += gap
195
+ page += 1
196
+ }
197
+ breakNext = node.type.name === "pageBreak"
198
+ // A block taller than a page runs over the next ones.
199
+ while (top + height > pageEnd(page) + 1) page += 1
200
+ })
201
+
202
+ setPages(page + 1)
203
+ if (!sameSpacers(spacers, applied.current)) {
204
+ applied.current = spacers
205
+ view.dispatch(view.state.tr.setMeta(paginationKey, spacers).setMeta("addToHistory", false))
206
+ }
207
+ }, [editor, column])
208
+
209
+ React.useEffect(() => {
210
+ if (!editor) return
211
+ if (!enabled) {
212
+ if (applied.current.length) {
213
+ applied.current = []
214
+ editor.view.dispatch(editor.state.tr.setMeta(paginationKey, []).setMeta("addToHistory", false))
215
+ }
216
+ setPages(1)
217
+ return
218
+ }
219
+ let frame = 0
220
+ const schedule = () => {
221
+ cancelAnimationFrame(frame)
222
+ frame = requestAnimationFrame(layout)
223
+ }
224
+ schedule()
225
+ const onUpdate = ({ transaction }: { transaction: { docChanged: boolean } }) => {
226
+ if (transaction.docChanged) schedule()
227
+ }
228
+ editor.on("update", onUpdate)
229
+ const ro = new ResizeObserver(schedule)
230
+ if (column.current) ro.observe(column.current)
231
+ // Images and charts change height when they load.
232
+ const dom = editor.view.dom
233
+ dom.addEventListener("load", schedule, true)
234
+ return () => {
235
+ cancelAnimationFrame(frame)
236
+ editor.off("update", onUpdate)
237
+ ro.disconnect()
238
+ dom.removeEventListener("load", schedule, true)
239
+ }
240
+ }, [editor, enabled, layout, column])
241
+
242
+ return pages
243
+ }
244
+
245
+ /* -------------------------------------------------------- Page view */
246
+
247
+ /**
248
+ * The page view (E.7, EditorPageView): white A4 pages in both themes (E.11),
249
+ * the letterhead on page 1, a running header after it, and "Page x of y" with
250
+ * the reference in each footer. The title is the tenant's print colour.
251
+ */
252
+ function PageView({
253
+ editor,
254
+ title,
255
+ letterhead,
256
+ reference,
257
+ date,
258
+ footerRef,
259
+ theme,
260
+ zoom,
261
+ showMargins = false,
262
+ labels,
263
+ onPages,
264
+ children,
265
+ }: {
266
+ editor: Editor | null
267
+ title: string
268
+ letterhead?: Letterhead | null
269
+ /** The end side of the letterhead: the reference ("Ref INV-1042") and the date. */
270
+ reference?: React.ReactNode
271
+ date?: React.ReactNode
272
+ /** Beside "Page x of y" in the footer: the document's reference. */
273
+ footerRef?: string
274
+ /** The document's resolved theme: the print colour and where it's used (E.44, E.45). */
275
+ theme?: ResolvedThemeTokens | null
276
+ /** 0.5 to 1.25. */
277
+ zoom: number
278
+ showMargins?: boolean
279
+ labels: EditorLabels
280
+ onPages?: (pages: number) => void
281
+ children: React.ReactNode
282
+ }) {
283
+ const column = React.useRef<HTMLDivElement>(null)
284
+ const pages = usePagination(editor, column, true)
285
+ React.useEffect(() => onPages?.(pages), [pages, onPages])
286
+
287
+ return (
288
+ <div className="wy-pv" style={{ zoom } as React.CSSProperties}>
289
+ <div
290
+ className="wy-pv__stack light"
291
+ data-accent-use={theme?.accentUse}
292
+ style={{ ...themeStyle(theme), height: pages * PAGE.height + (pages - 1) * PAGE.gap }}
293
+ >
294
+ {Array.from({ length: pages }, (_, i) => (
295
+ <div
296
+ key={i}
297
+ className={cn("wy-pv__page", showMargins && "show-margins")}
298
+ style={{ top: i * (PAGE.height + PAGE.gap) }}
299
+ aria-hidden="true"
300
+ >
301
+ <div className="wy-pv__margin" />
302
+ {i > 0 && (
303
+ <div className="wy-pv__run">
304
+ {letterhead ? <LetterheadMark letterhead={letterhead} size={20} showName={false} /> : <span />}
305
+ <span>{fill(labels.pageContinued, { title: title || labels.untitled })}</span>
306
+ </div>
307
+ )}
308
+ <div className="wy-pv__foot">
309
+ <span>
310
+ {fill(labels.pageOf, { page: i + 1, pages })}
311
+ {footerRef ? ` · ${footerRef}` : ""}
312
+ </span>
313
+ <span>{letterhead?.name}</span>
314
+ </div>
315
+ </div>
316
+ ))}
317
+ <div ref={column} className="wy-pv__column">
318
+ {letterhead !== null && (
319
+ <div className="wy-pv__lh">
320
+ {letterhead ? (
321
+ <div className="grid content-start gap-1.5">
322
+ <LetterheadMark letterhead={letterhead} size={32} showName />
323
+ {letterhead.lines.map((line, i) => (
324
+ <span key={i} dir="auto">
325
+ {line}
326
+ </span>
327
+ ))}
328
+ </div>
329
+ ) : (
330
+ <span />
331
+ )}
332
+ <div className="wy-pv__lhend">
333
+ <h1 className="wy-pv__title" dir="auto">
334
+ {title || labels.untitled}
335
+ </h1>
336
+ {reference && <b>{reference}</b>}
337
+ {date && <span>{date}</span>}
338
+ </div>
339
+ </div>
340
+ )}
341
+ {children}
342
+ </div>
343
+ </div>
344
+ </div>
345
+ )
346
+ }
347
+
348
+ /** The zoom that fits a page to `width` px of canvas, no larger than 100%. */
349
+ export function fitZoom(width: number): number {
350
+ return Math.max(0.3, Math.min(1, (width - 48) / PAGE.width))
351
+ }
352
+
353
+ export { PageView }
@@ -0,0 +1,182 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import type { Node as PMNode } from "@tiptap/pm/model"
5
+
6
+ import { Button } from "../button"
7
+ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../dialog"
8
+ import { Icon, type IconName } from "../icon"
9
+ import type { PublishBlocker } from "./contract"
10
+ import { fill, type EditorLabels } from "./labels"
11
+
12
+ /**
13
+ * The fields a document uses that its record type doesn't offer (E.37). The
14
+ * server runs the same check again before it publishes.
15
+ */
16
+ export function unknownFields(doc: PMNode, known: Set<string>): string[] {
17
+ const missing = new Set<string>()
18
+ doc.descendants((node) => {
19
+ if (node.type.name === "field" && !known.has(String(node.attrs.path))) missing.add(String(node.attrs.path))
20
+ })
21
+ return [...missing]
22
+ }
23
+
24
+ const ICON: Record<PublishBlocker["kind"], IconName> = {
25
+ "open-suggestions": "suggest",
26
+ "missing-plugin": "plugin",
27
+ "block-without-print-view": "plugin",
28
+ "unknown-field": "field",
29
+ "theme-unavailable": "branding",
30
+ }
31
+
32
+ /**
33
+ * `fill` for text that holds a value from elsewhere: each `{key}` becomes the
34
+ * node given, so a theme ref can sit in a `<bdi>` inside an Arabic sentence.
35
+ */
36
+ function fillNodes(template: string, values: Record<string, React.ReactNode>): React.ReactNode {
37
+ return template.split(/(\{\w+\})/).map((part, i) => {
38
+ const m = /^\{(\w+)\}$/.exec(part)
39
+ return m && m[1] in values ? <React.Fragment key={i}>{values[m[1]]}</React.Fragment> : part
40
+ })
41
+ }
42
+
43
+ function blockerText(
44
+ b: PublishBlocker,
45
+ labels: EditorLabels,
46
+ names: { plugin?: (id: string) => string; field?: (path: string) => string }
47
+ ): { title: React.ReactNode; hint: string; action?: string } {
48
+ switch (b.kind) {
49
+ case "open-suggestions":
50
+ return {
51
+ title: b.count === 1 ? labels.blockerSuggestion : fill(labels.blockerSuggestions, { n: b.count }),
52
+ hint: labels.blockerSuggestionsHint,
53
+ action: labels.review,
54
+ }
55
+ case "missing-plugin":
56
+ return { title: fill(labels.blockerPlugin, { plugin: names.plugin?.(b.plugin) ?? b.plugin }), hint: labels.blockerPluginHint, action: labels.show }
57
+ case "block-without-print-view":
58
+ return { title: labels.blockerNoPrint, hint: labels.blockerNoPrintHint, action: labels.show }
59
+ case "unknown-field":
60
+ return { title: fill(labels.blockerField, { field: names.field?.(b.path) ?? b.path }), hint: labels.blockerFieldHint, action: labels.show }
61
+ case "theme-unavailable":
62
+ // No way to fix it here until the theme picker (WHIT-736): the hint says what to do.
63
+ return { title: fillNodes(labels.blockerTheme, { ref: <bdi dir="ltr">{b.ref}</bdi> }), hint: labels.blockerThemeHint }
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Publish (E.9) opens this check first (TplDocDesigner): what blocks
69
+ * publishing, each with a way to fix it, and Publish stays disabled until the
70
+ * list is empty (E.37). Publishing makes the draft the version Whity Render
71
+ * and agents use.
72
+ */
73
+ function PublishCheck({
74
+ open,
75
+ onOpenChange,
76
+ blockers,
77
+ checking = false,
78
+ nextVersion,
79
+ recordLabel,
80
+ onPublish,
81
+ onFix,
82
+ labels,
83
+ pluginName,
84
+ fieldLabel,
85
+ }: {
86
+ open: boolean
87
+ onOpenChange: (open: boolean) => void
88
+ blockers: PublishBlocker[]
89
+ /** While the server's check is running. */
90
+ checking?: boolean
91
+ nextVersion: number
92
+ /** What the template prints, plural: "payment reminders". */
93
+ recordLabel?: string
94
+ onPublish: () => Promise<void> | void
95
+ onFix: (blocker: PublishBlocker) => void
96
+ labels: EditorLabels
97
+ pluginName?: (id: string) => string
98
+ fieldLabel?: (path: string) => string
99
+ }) {
100
+ const [busy, setBusy] = React.useState(false)
101
+ const [error, setError] = React.useState(false)
102
+ React.useEffect(() => {
103
+ if (open) setError(false)
104
+ }, [open])
105
+ const publish = async () => {
106
+ setBusy(true)
107
+ setError(false)
108
+ try {
109
+ await onPublish()
110
+ onOpenChange(false)
111
+ } catch {
112
+ setError(true)
113
+ } finally {
114
+ setBusy(false)
115
+ }
116
+ }
117
+ const clear = !checking && blockers.length === 0
118
+ return (
119
+ <Dialog open={open} onOpenChange={onOpenChange}>
120
+ <DialogContent className="max-w-[440px]" closeLabel={labels.keepEditing}>
121
+ <DialogHeader>
122
+ <DialogTitle>{labels.publishTitle}</DialogTitle>
123
+ <DialogDescription>
124
+ {recordLabel ? fill(labels.publishExplainFor, { records: recordLabel }) : labels.publishExplain}
125
+ </DialogDescription>
126
+ </DialogHeader>
127
+ {checking ? (
128
+ <p role="status" className="text-sm text-muted-foreground">
129
+ {labels.publishChecking}
130
+ </p>
131
+ ) : blockers.length > 0 ? (
132
+ <ul className="m-0 grid list-none gap-2 p-0" aria-label={labels.publishBlockers}>
133
+ {blockers.map((b, i) => {
134
+ const t = blockerText(b, labels, { plugin: pluginName, field: fieldLabel })
135
+ return (
136
+ <li key={i} className="flex items-start gap-2.5 rounded-control-lg border border-border px-3 py-2.5 text-sm">
137
+ <Icon name={ICON[b.kind]} className="mt-0.5 shrink-0 text-warning-text" />
138
+ <div className="grid flex-1 gap-0.5">
139
+ <span className="font-medium">{t.title}</span>
140
+ <span className="text-[0.8125rem] text-muted-foreground">{t.hint}</span>
141
+ </div>
142
+ {t.action && (
143
+ <Button
144
+ variant="outline"
145
+ size="sm"
146
+ onClick={() => {
147
+ onOpenChange(false)
148
+ onFix(b)
149
+ }}
150
+ >
151
+ {t.action}
152
+ </Button>
153
+ )}
154
+ </li>
155
+ )
156
+ })}
157
+ </ul>
158
+ ) : (
159
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
160
+ <Icon name="check" className="text-success-text" />
161
+ {labels.publishClear}
162
+ </p>
163
+ )}
164
+ {error && (
165
+ <p role="alert" className="text-sm text-error-text">
166
+ {labels.publishFailed}
167
+ </p>
168
+ )}
169
+ <DialogFooter>
170
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
171
+ {labels.keepEditing}
172
+ </Button>
173
+ <Button icon="check" disabled={!clear || busy} onClick={publish}>
174
+ {fill(labels.publishVersion, { n: nextVersion })}
175
+ </Button>
176
+ </DialogFooter>
177
+ </DialogContent>
178
+ </Dialog>
179
+ )
180
+ }
181
+
182
+ export { PublishCheck }
@@ -0,0 +1,146 @@
1
+ import type { Meta, StoryObj } from "@storybook/react-vite"
2
+ import * as React from "react"
3
+
4
+ import type { Block, EditorMode, WhityDocument } from "./contract"
5
+ import { DocEditor } from "./doc-editor"
6
+ import { SAMPLE_DOCUMENT } from "./sample"
7
+ import type { EditorServices } from "./services"
8
+
9
+ const meta = {
10
+ title: "Editor/Rich blocks",
11
+ parameters: { layout: "fullscreen", fullBleed: true },
12
+ } satisfies Meta
13
+
14
+ export default meta
15
+ type Story = StoryObj<typeof meta>
16
+
17
+ const t = (text: string) => ({ type: "text" as const, text })
18
+ const wait = <T,>(value: T, ms = 400) => new Promise<T>((done) => setTimeout(() => done(value), ms))
19
+
20
+ /** Stand-ins for the server: Example Bakery's invoices and a monthly chart. */
21
+ const SERVICES: EditorServices = {
22
+ recordTypes: [
23
+ { key: "invoice", label: "Invoice" },
24
+ { key: "document", label: "Issued document" },
25
+ ],
26
+ chartSources: [
27
+ { key: "documents-by-month", label: "Documents issued per month" },
28
+ { key: "revenue-by-month", label: "Revenue per month" },
29
+ ],
30
+ resolveRecord: (ref) =>
31
+ wait(
32
+ ref.id === "INV-1042"
33
+ ? { typeLabel: "Invoice", title: "INV-1042 · Example Clinic", subtitle: "Due 14 Oct 2026", amount: "JOD 301.600", status: { label: "Overdue", tone: "warning" as const } }
34
+ : ref.id === "INV-0001"
35
+ ? null
36
+ : { typeLabel: "Invoice", title: `${ref.id} · Example Bakery`, amount: "JOD 96.000", status: { label: "Paid", tone: "success" as const } }
37
+ ),
38
+ loadChart: (source) =>
39
+ wait(
40
+ source.query === "empty"
41
+ ? { points: [] }
42
+ : {
43
+ valueLabel: source.query === "revenue-by-month" ? "JOD" : "Documents",
44
+ subtitle: "Last 6 months",
45
+ points: [
46
+ { label: "May", value: 18 },
47
+ { label: "Jun", value: 24 },
48
+ { label: "Jul", value: 21 },
49
+ { label: "Aug", value: 30 },
50
+ { label: "Sep", value: 27 },
51
+ { label: "Oct", value: 35 },
52
+ ],
53
+ }
54
+ ),
55
+ uploadFile: (file) => wait({ fileId: String(Date.now()), url: URL.createObjectURL(file), name: file.name, size: file.size, mime: file.type }, 700),
56
+ fileUrl: () => "#",
57
+ }
58
+
59
+ const BLOCKS: Block[] = [
60
+ { id: "r1", type: "paragraph", content: [t("Every M3 block, with stand-in data. Click a block to see its toolbar.")] },
61
+ { id: "r2", type: "callout", kind: "note", content: [t("Payment is due within 30 days of the invoice date.")] },
62
+ { id: "r3", type: "callout", kind: "important", content: [t("Late payments add 2% a month.")] },
63
+ {
64
+ id: "r4",
65
+ type: "toggle",
66
+ open: true,
67
+ summary: [t("How do I pay by card?")],
68
+ children: [{ id: "r4a", type: "paragraph", content: [t("Open the link in the invoice email and follow the steps.")] }],
69
+ },
70
+ {
71
+ id: "r5",
72
+ type: "columns",
73
+ columns: [
74
+ [{ id: "r5a", type: "paragraph", content: [t("Example Bakery, 12 Rainbow Street, Amman")] }],
75
+ [{ id: "r5b", type: "paragraph", content: [t("Example Clinic, 4 Garden Road, Irbid")] }],
76
+ ],
77
+ },
78
+ {
79
+ id: "r6",
80
+ type: "table",
81
+ headerRow: true,
82
+ columns: [{ align: "start" }, { align: "start" }, { align: "end" }],
83
+ rows: [
84
+ [[t("Invoice")], [t("Customer")], [t("Amount")]],
85
+ [[t("INV-1042")], [t("Example Clinic")], [t("JOD 301.600")]],
86
+ [[t("INV-1051")], [t("Example Café")], [t("JOD 96.000")]],
87
+ ],
88
+ },
89
+ { id: "r7", type: "image", src: "", alt: "", width: "wide" },
90
+ { id: "r8", type: "file", fileId: "f1", name: "price-list-2026.pdf", size: 248_320, mime: "application/pdf" },
91
+ { id: "r9", type: "record", ref: { type: "invoice", id: "INV-1042" }, view: "card" },
92
+ { id: "r10", type: "record", ref: { type: "invoice", id: "INV-1051" }, view: "summary" },
93
+ { id: "r11", type: "record", ref: { type: "invoice", id: "INV-0001" }, view: "card" },
94
+ { id: "r12", type: "chart", chart: "bar", source: { query: "documents-by-month" }, title: "Documents issued per month" },
95
+ { id: "r13", type: "chart", chart: "line", source: { query: "revenue-by-month" }, title: "Revenue per month" },
96
+ { id: "r13b", type: "chart", chart: "donut", source: { query: "documents-by-month" }, title: "Documents by month" },
97
+ {
98
+ id: "r14",
99
+ type: "signature",
100
+ signers: [
101
+ { name: [t("Lina Haddad")], role: [t("Finance manager")] },
102
+ { name: [t("Omar Saleh")], role: [t("Owner")] },
103
+ ],
104
+ date: [t("29 Oct 2026")],
105
+ stamp: true,
106
+ },
107
+ { id: "r15", type: "barcode", symbology: "code128", value: [t("INV-1042")], showText: true },
108
+ { id: "r16", type: "qr", value: [t("https://example.com/pay/INV-1042")], caption: [t("Scan to pay")] },
109
+ { id: "r17", type: "math", tex: "\\text{Total} = \\sum_{i=1}^{n} q_i \\times p_i" },
110
+ { id: "r18", type: "pageBreak" },
111
+ { id: "r19", type: "paragraph", content: [t("After the page break.")] },
112
+ ]
113
+
114
+ function Live({ initial, canEdit = true, services = SERVICES }: { initial: WhityDocument; canEdit?: boolean; services?: EditorServices }) {
115
+ const [doc, setDoc] = React.useState(initial)
116
+ const [mode, setMode] = React.useState<EditorMode>("editing")
117
+ return (
118
+ <div style={{ height: "100vh" }}>
119
+ <DocEditor
120
+ document={doc}
121
+ onChange={setDoc}
122
+ canEdit={canEdit}
123
+ mode={mode}
124
+ onModeChange={setMode}
125
+ back={{ label: "Back to notes", onClick: () => {} }}
126
+ path="Notes · Billing"
127
+ save={{ state: "saved", at: "14:02" }}
128
+ services={services}
129
+ />
130
+ </div>
131
+ )
132
+ }
133
+
134
+ const DOC: WhityDocument = { ...SAMPLE_DOCUMENT, title: "Rich blocks", blocks: BLOCKS }
135
+
136
+ export const AllBlocks: Story = { render: () => <Live initial={DOC} /> }
137
+
138
+ export const ReadOnly: Story = { render: () => <Live initial={DOC} canEdit={false} /> }
139
+
140
+ /** No services: records and charts say what is missing instead of loading. */
141
+ export const NoServices: Story = { render: () => <Live initial={DOC} services={{}} /> }
142
+
143
+ export const Arabic: Story = {
144
+ globals: { direction: "rtl" },
145
+ render: () => <Live initial={{ ...DOC, lang: "ar", title: "الكتل الغنية" }} />,
146
+ }