@whity/ui 0.5.0 → 1.0.1

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 (208) hide show
  1. package/README.md +107 -107
  2. package/package.json +223 -192
  3. package/src/access-denied.stories.tsx +179 -179
  4. package/src/access-denied.tsx +305 -305
  5. package/src/action-proposal.tsx +338 -302
  6. package/src/actor-chip.tsx +71 -71
  7. package/src/agent-activity.tsx +163 -163
  8. package/src/agent-collaboration.stories.tsx +156 -156
  9. package/src/agent-run-status.tsx +196 -196
  10. package/src/alert-dialog.stories.tsx +45 -45
  11. package/src/alert-dialog.tsx +147 -147
  12. package/src/alert.stories.tsx +91 -91
  13. package/src/alert.tsx +89 -89
  14. package/src/app-sidebar.stories.tsx +195 -195
  15. package/src/app-sidebar.tsx +604 -500
  16. package/src/approval-queue.tsx +109 -108
  17. package/src/audience-group-picker.stories.tsx +198 -198
  18. package/src/audience-group-picker.tsx +362 -362
  19. package/src/audience-people-picker.stories.tsx +102 -102
  20. package/src/audience-people-picker.tsx +279 -279
  21. package/src/avatar-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -83
  23. package/src/badge.stories.tsx +105 -105
  24. package/src/badge.tsx +68 -68
  25. package/src/beta-warning.stories.tsx +79 -79
  26. package/src/beta-warning.tsx +189 -189
  27. package/src/bilingual-input.stories.tsx +82 -82
  28. package/src/bilingual-input.tsx +188 -183
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -51
  31. package/src/breadcrumb.tsx +90 -90
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -87
  34. package/src/button.tsx +125 -118
  35. package/src/card.stories.tsx +423 -423
  36. package/src/card.tsx +180 -180
  37. package/src/chart.stories.tsx +66 -66
  38. package/src/chart.tsx +228 -228
  39. package/src/checkbox.stories.tsx +62 -62
  40. package/src/checkbox.tsx +54 -54
  41. package/src/collapsible.stories.tsx +48 -48
  42. package/src/collapsible.tsx +34 -34
  43. package/src/color-card.stories.tsx +61 -61
  44. package/src/color-card.tsx +270 -270
  45. package/src/color-picker.stories.tsx +65 -65
  46. package/src/color-picker.tsx +425 -425
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +399 -306
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -38
  51. package/src/copy-block.tsx +85 -85
  52. package/src/data-table.stories.tsx +200 -200
  53. package/src/data-table.tsx +1687 -1106
  54. package/src/date-picker.stories.tsx +61 -61
  55. package/src/date-picker.tsx +457 -422
  56. package/src/design-cards.stories.tsx +551 -458
  57. package/src/dialog.stories.tsx +48 -48
  58. package/src/dialog.tsx +179 -166
  59. package/src/display-preferences.tsx +59 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -72
  61. package/src/documents/barcode-svg.tsx +79 -79
  62. package/src/dropdown-menu.stories.tsx +77 -77
  63. package/src/dropdown-menu.tsx +271 -271
  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 -279
  68. package/src/editor/block-ids.ts +44 -44
  69. package/src/editor/block-list.tsx +104 -101
  70. package/src/editor/block-toolbar.tsx +490 -477
  71. package/src/editor/bubble.tsx +119 -93
  72. package/src/editor/catalogue.ts +169 -103
  73. package/src/editor/collab-rail.tsx +746 -746
  74. package/src/editor/collab.stories.tsx +207 -207
  75. package/src/editor/collab.ts +87 -87
  76. package/src/editor/contract.ts +476 -408
  77. package/src/editor/convert.ts +414 -362
  78. package/src/editor/doc-editor.stories.tsx +98 -98
  79. package/src/editor/doc-editor.tsx +1492 -1287
  80. package/src/editor/editor.css +636 -536
  81. package/src/editor/extensions.ts +86 -86
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -107
  84. package/src/editor/fields.ts +100 -100
  85. package/src/editor/gutter.tsx +443 -367
  86. package/src/editor/index.ts +23 -22
  87. package/src/editor/label-sheet.tsx +289 -289
  88. package/src/editor/labels.ts +394 -310
  89. package/src/editor/link-tools.tsx +141 -141
  90. package/src/editor/node-views.tsx +461 -450
  91. package/src/editor/page-view.tsx +372 -353
  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 -182
  97. package/src/editor/rich-blocks.stories.tsx +146 -146
  98. package/src/editor/sample.ts +40 -40
  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 -150
  104. package/src/editor/schema.ts +368 -315
  105. package/src/editor/services.tsx +205 -127
  106. package/src/editor/slash.ts +64 -64
  107. package/src/editor/suggesting.ts +372 -372
  108. package/src/editor/suggestions.ts +763 -763
  109. package/src/editor/table-keys.ts +66 -66
  110. package/src/editor/templates.stories.tsx +324 -324
  111. package/src/editor/toolbar.tsx +364 -358
  112. package/src/empty-state.stories.tsx +51 -51
  113. package/src/empty-state.tsx +126 -100
  114. package/src/empty-state.usage-notes.md +30 -30
  115. package/src/form.stories.tsx +112 -112
  116. package/src/form.tsx +176 -176
  117. package/src/globals.css +20 -20
  118. package/src/icon-button.tsx +85 -85
  119. package/src/icon-map.ts +335 -244
  120. package/src/icon.tsx +41 -41
  121. package/src/index.ts +92 -67
  122. package/src/input.stories.tsx +157 -157
  123. package/src/input.tsx +768 -759
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -29
  127. package/src/locked-screen.tsx +75 -61
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -62
  131. package/src/math-text.stories.tsx +33 -33
  132. package/src/math-text.tsx +43 -43
  133. package/src/menu-bar.stories.tsx +198 -198
  134. package/src/menu-bar.tsx +373 -373
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -230
  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 -95
  142. package/src/page-header.tsx +122 -122
  143. package/src/page-shell.stories.tsx +42 -42
  144. package/src/page-shell.tsx +32 -32
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -45
  147. package/src/pagination.tsx +98 -98
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-input.tsx +252 -0
  151. package/src/phone-tab-bar.tsx +152 -0
  152. package/src/plugin-card.stories.tsx +208 -180
  153. package/src/plugin-card.tsx +931 -848
  154. package/src/popover.stories.tsx +48 -48
  155. package/src/popover.tsx +55 -55
  156. package/src/radio-group.stories.tsx +26 -26
  157. package/src/radio-group.tsx +44 -44
  158. package/src/role-summary.stories.tsx +143 -0
  159. package/src/role-summary.tsx +120 -0
  160. package/src/route-flow/editor.tsx +1087 -1014
  161. package/src/route-flow/model.ts +771 -716
  162. package/src/save-bar.tsx +94 -0
  163. package/src/scope-grant.tsx +139 -139
  164. package/src/screen-too-small.stories.tsx +61 -61
  165. package/src/screen-too-small.tsx +104 -104
  166. package/src/search-field.tsx +65 -0
  167. package/src/select.stories.tsx +44 -44
  168. package/src/select.tsx +197 -197
  169. package/src/separator.stories.tsx +34 -34
  170. package/src/separator.tsx +34 -34
  171. package/src/sheet.stories.tsx +49 -49
  172. package/src/sheet.tsx +168 -168
  173. package/src/skeleton.stories.tsx +28 -28
  174. package/src/skeleton.tsx +19 -19
  175. package/src/slider.stories.tsx +78 -78
  176. package/src/slider.tsx +300 -300
  177. package/src/spinner.stories.tsx +33 -33
  178. package/src/spinner.tsx +55 -55
  179. package/src/stepper.tsx +85 -0
  180. package/src/switch.stories.tsx +42 -42
  181. package/src/switch.tsx +41 -41
  182. package/src/switcher.stories.tsx +111 -111
  183. package/src/switcher.tsx +131 -131
  184. package/src/system-state.tsx +55 -0
  185. package/src/table.stories.tsx +48 -48
  186. package/src/table.tsx +121 -121
  187. package/src/tabs.stories.tsx +74 -74
  188. package/src/tabs.tsx +90 -90
  189. package/src/tag-input.stories.tsx +67 -67
  190. package/src/tag-input.tsx +117 -117
  191. package/src/tenant-logo.tsx +63 -63
  192. package/src/tenant-switcher.stories.tsx +38 -38
  193. package/src/tenant-switcher.tsx +185 -164
  194. package/src/textarea.stories.tsx +27 -27
  195. package/src/textarea.tsx +18 -18
  196. package/src/theme-mode.ts +74 -52
  197. package/src/time-grid.tsx +163 -0
  198. package/src/time-picker.stories.tsx +62 -62
  199. package/src/time-picker.tsx +616 -615
  200. package/src/toggle-group.tsx +139 -138
  201. package/src/tooltip.stories.tsx +43 -43
  202. package/src/tooltip.tsx +73 -73
  203. package/src/top-nav.stories.tsx +58 -58
  204. package/src/top-nav.tsx +324 -324
  205. package/src/undo-bar.tsx +107 -107
  206. package/src/utils.ts +45 -45
  207. package/src/view-toggle.stories.tsx +84 -84
  208. package/src/view-toggle.tsx +111 -110
@@ -1,353 +1,372 @@
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 }
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 type options a resolved theme carries beside the contract's tokens
79
+ * (E.46, E.47). The server sends them; the contract file follows the design
80
+ * handoff, which doesn't list them yet.
81
+ */
82
+ export type ThemeTypeOptions = { titleFace?: "readex" | "noto"; largePrint?: boolean }
83
+
84
+ /**
85
+ * The theme's colours as the `--doc-*` variables the page view and sheet read
86
+ * (E.11): `--doc-accent` on paper, `--doc-accent-on-dark` for the continuous
87
+ * sheet's title in dark mode, and `--doc-title-font` when the theme sets the
88
+ * title in the body face (E.46).
89
+ */
90
+ export function themeStyle(theme: ResolvedThemeTokens | null | undefined): React.CSSProperties | undefined {
91
+ if (!theme) return undefined
92
+ const options = theme as ResolvedThemeTokens & ThemeTypeOptions
93
+ return {
94
+ "--doc-accent": theme.accent,
95
+ "--doc-accent-on-dark": theme.accentOnDark,
96
+ ...(options.titleFace === "noto" ? { "--doc-title-font": "var(--font-sans)" } : {}),
97
+ } as React.CSSProperties
98
+ }
99
+
100
+ /** E.47: whether the theme prints large (the page view scales its print sizes to match). */
101
+ export function largePrint(theme: ResolvedThemeTokens | null | undefined): boolean {
102
+ return (theme as (ResolvedThemeTokens & ThemeTypeOptions) | null | undefined)?.largePrint === true
103
+ }
104
+
105
+ /** The letterhead's mark at `size`, as the theme's logo shape asks. */
106
+ function LetterheadMark({ letterhead, size, showName }: { letterhead: Letterhead; size: number; showName?: boolean }) {
107
+ if (letterhead.logoShape === "none") return showName ? <span className="text-sm font-semibold text-foreground">{letterhead.name}</span> : <span />
108
+ return (
109
+ <TenantLogo
110
+ name={letterhead.name}
111
+ src={letterhead.logo}
112
+ size={size}
113
+ showName={showName}
114
+ shape={letterhead.logoShape === "wide" ? "wide" : "square"}
115
+ />
116
+ )
117
+ }
118
+
119
+ /* ------------------------------------------------------- Page breaks */
120
+
121
+ interface Spacer {
122
+ /** The document position the gap goes before. */
123
+ pos: number
124
+ height: number
125
+ }
126
+
127
+ const paginationKey = new PluginKey<DecorationSet>("pagePagination")
128
+
129
+ function spacerWidget(height: number) {
130
+ return () => {
131
+ const el = document.createElement("div")
132
+ el.className = "wy-pv__gap"
133
+ el.setAttribute("aria-hidden", "true")
134
+ el.contentEditable = "false"
135
+ el.style.height = `${height}px`
136
+ return el
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Pushes a block that would cross the bottom of a page to the top of the next
142
+ * one, and starts a page after every Page break block. Whity Render paginates
143
+ * the PDF itself (it measures rows); these breaks are a close preview (E.7).
144
+ */
145
+ export const PagePagination = Extension.create({
146
+ name: "pagePagination",
147
+ addProseMirrorPlugins() {
148
+ return [
149
+ new Plugin<DecorationSet>({
150
+ key: paginationKey,
151
+ state: {
152
+ init: () => DecorationSet.empty,
153
+ apply(tr, set) {
154
+ const next = tr.getMeta(paginationKey) as Spacer[] | undefined
155
+ if (next) {
156
+ return DecorationSet.create(
157
+ tr.doc,
158
+ next.map((s) => Decoration.widget(s.pos, spacerWidget(s.height), { side: -1, key: `gap-${s.pos}-${s.height}` }))
159
+ )
160
+ }
161
+ return set.map(tr.mapping, tr.doc)
162
+ },
163
+ },
164
+ props: { decorations: (state) => paginationKey.getState(state) },
165
+ }),
166
+ ]
167
+ },
168
+ })
169
+
170
+ function sameSpacers(a: Spacer[], b: Spacer[]): boolean {
171
+ return a.length === b.length && a.every((s, i) => s.pos === b[i].pos && Math.abs(s.height - b[i].height) < 2)
172
+ }
173
+
174
+ /**
175
+ * Lays the top-level blocks out on pages. `column` is the content column,
176
+ * `firstTop` where the editor's content starts on page 1 (below the
177
+ * letterhead), both in unzoomed px. Returns the number of pages.
178
+ */
179
+ function usePagination(editor: Editor | null, column: React.RefObject<HTMLDivElement | null>, enabled: boolean): number {
180
+ const [pages, setPages] = React.useState(1)
181
+ const applied = React.useRef<Spacer[]>([])
182
+
183
+ const layout = React.useCallback(() => {
184
+ if (!editor || editor.isDestroyed || !column.current) return
185
+ const view = editor.view
186
+ const box = column.current.getBoundingClientRect()
187
+ // CSS zoom scales what getBoundingClientRect reports; offsetWidth isn't.
188
+ const scale = column.current.offsetWidth ? box.width / column.current.offsetWidth : 1
189
+ const pageStart = (k: number) => k * (PAGE.height + PAGE.gap) + (k === 0 ? 0 : PAGE.margin + RUN_HEADER)
190
+ const pageEnd = (k: number) => k * (PAGE.height + PAGE.gap) + PAGE.height - PAGE.margin
191
+
192
+ const spacers: Spacer[] = []
193
+ let shiftBefore = 0 // the gaps applied last time above this block, to recover its natural place
194
+ let shift = 0 // the gaps this pass adds above it
195
+ let page = 0
196
+ let breakNext = false
197
+ const old = new Map(applied.current.map((s) => [s.pos, s.height]))
198
+
199
+ view.state.doc.forEach((node, offset) => {
200
+ const dom = view.nodeDOM(offset)
201
+ if (!(dom instanceof HTMLElement)) return
202
+ shiftBefore += old.get(offset) ?? 0
203
+ const r = dom.getBoundingClientRect()
204
+ const naturalTop = (r.top - box.top) / scale - shiftBefore
205
+ const height = r.height / scale
206
+ let top = naturalTop + shift
207
+ if (breakNext || (top + height > pageEnd(page) && top > pageStart(page) + 1)) {
208
+ const target = pageStart(page + 1)
209
+ const gap = Math.max(0, target - top)
210
+ if (gap > 0) spacers.push({ pos: offset, height: Math.round(gap) })
211
+ shift += gap
212
+ top += gap
213
+ page += 1
214
+ }
215
+ breakNext = node.type.name === "pageBreak"
216
+ // A block taller than a page runs over the next ones.
217
+ while (top + height > pageEnd(page) + 1) page += 1
218
+ })
219
+
220
+ setPages(page + 1)
221
+ if (!sameSpacers(spacers, applied.current)) {
222
+ applied.current = spacers
223
+ view.dispatch(view.state.tr.setMeta(paginationKey, spacers).setMeta("addToHistory", false))
224
+ }
225
+ }, [editor, column])
226
+
227
+ React.useEffect(() => {
228
+ if (!editor) return
229
+ if (!enabled) {
230
+ if (applied.current.length) {
231
+ applied.current = []
232
+ editor.view.dispatch(editor.state.tr.setMeta(paginationKey, []).setMeta("addToHistory", false))
233
+ }
234
+ setPages(1)
235
+ return
236
+ }
237
+ let frame = 0
238
+ const schedule = () => {
239
+ cancelAnimationFrame(frame)
240
+ frame = requestAnimationFrame(layout)
241
+ }
242
+ schedule()
243
+ const onUpdate = ({ transaction }: { transaction: { docChanged: boolean } }) => {
244
+ if (transaction.docChanged) schedule()
245
+ }
246
+ editor.on("update", onUpdate)
247
+ const ro = new ResizeObserver(schedule)
248
+ if (column.current) ro.observe(column.current)
249
+ // Images and charts change height when they load.
250
+ const dom = editor.view.dom
251
+ dom.addEventListener("load", schedule, true)
252
+ return () => {
253
+ cancelAnimationFrame(frame)
254
+ editor.off("update", onUpdate)
255
+ ro.disconnect()
256
+ dom.removeEventListener("load", schedule, true)
257
+ }
258
+ }, [editor, enabled, layout, column])
259
+
260
+ return pages
261
+ }
262
+
263
+ /* -------------------------------------------------------- Page view */
264
+
265
+ /**
266
+ * The page view (E.7, EditorPageView): white A4 pages in both themes (E.11),
267
+ * the letterhead on page 1, a running header after it, and "Page x of y" with
268
+ * the reference in each footer. The title is the tenant's print colour.
269
+ */
270
+ function PageView({
271
+ editor,
272
+ title,
273
+ letterhead,
274
+ reference,
275
+ date,
276
+ footerRef,
277
+ theme,
278
+ zoom,
279
+ showMargins = false,
280
+ labels,
281
+ onPages,
282
+ children,
283
+ }: {
284
+ editor: Editor | null
285
+ title: string
286
+ letterhead?: Letterhead | null
287
+ /** The end side of the letterhead: the reference ("Ref INV-1042") and the date. */
288
+ reference?: React.ReactNode
289
+ date?: React.ReactNode
290
+ /** Beside "Page x of y" in the footer: the document's reference. */
291
+ footerRef?: string
292
+ /** The document's resolved theme: the print colour and where it's used (E.44, E.45). */
293
+ theme?: ResolvedThemeTokens | null
294
+ /** 0.5 to 1.25. */
295
+ zoom: number
296
+ showMargins?: boolean
297
+ labels: EditorLabels
298
+ onPages?: (pages: number) => void
299
+ children: React.ReactNode
300
+ }) {
301
+ const column = React.useRef<HTMLDivElement>(null)
302
+ const pages = usePagination(editor, column, true)
303
+ React.useEffect(() => onPages?.(pages), [pages, onPages])
304
+
305
+ return (
306
+ <div className="wy-pv" style={{ zoom } as React.CSSProperties}>
307
+ <div
308
+ className="wy-pv__stack light"
309
+ data-accent-use={theme?.accentUse}
310
+ data-large-print={largePrint(theme) || undefined}
311
+ style={{ ...themeStyle(theme), height: pages * PAGE.height + (pages - 1) * PAGE.gap }}
312
+ >
313
+ {Array.from({ length: pages }, (_, i) => (
314
+ <div
315
+ key={i}
316
+ className={cn("wy-pv__page", showMargins && "show-margins")}
317
+ style={{ top: i * (PAGE.height + PAGE.gap) }}
318
+ aria-hidden="true"
319
+ >
320
+ <div className="wy-pv__margin" />
321
+ {i > 0 && (
322
+ <div className="wy-pv__run">
323
+ {letterhead ? <LetterheadMark letterhead={letterhead} size={20} showName={false} /> : <span />}
324
+ <span>{fill(labels.pageContinued, { title: title || labels.untitled })}</span>
325
+ </div>
326
+ )}
327
+ <div className="wy-pv__foot">
328
+ <span>
329
+ {fill(labels.pageOf, { page: i + 1, pages })}
330
+ {footerRef ? ` · ${footerRef}` : ""}
331
+ </span>
332
+ <span>{letterhead?.name}</span>
333
+ </div>
334
+ </div>
335
+ ))}
336
+ <div ref={column} className="wy-pv__column">
337
+ {letterhead !== null && (
338
+ <div className="wy-pv__lh">
339
+ {letterhead ? (
340
+ <div className="grid content-start gap-1.5">
341
+ <LetterheadMark letterhead={letterhead} size={32} showName />
342
+ {letterhead.lines.map((line, i) => (
343
+ <span key={i} dir="auto">
344
+ {line}
345
+ </span>
346
+ ))}
347
+ </div>
348
+ ) : (
349
+ <span />
350
+ )}
351
+ <div className="wy-pv__lhend">
352
+ <h1 className="wy-pv__title" dir="auto">
353
+ {title || labels.untitled}
354
+ </h1>
355
+ {reference && <b>{reference}</b>}
356
+ {date && <span>{date}</span>}
357
+ </div>
358
+ </div>
359
+ )}
360
+ {children}
361
+ </div>
362
+ </div>
363
+ </div>
364
+ )
365
+ }
366
+
367
+ /** The zoom that fits a page to `width` px of canvas, no larger than 100%. */
368
+ export function fitZoom(width: number): number {
369
+ return Math.max(0.3, Math.min(1, (width - 48) / PAGE.width))
370
+ }
371
+
372
+ export { PageView }