@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,141 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import type { Editor } from "@tiptap/core"
5
+ import { getMarkRange } from "@tiptap/core"
6
+
7
+ import { Button } from "../button"
8
+ import { Icon } from "../icon"
9
+ import { IconButton } from "../icon-button"
10
+ import type { EditorLabels } from "./labels"
11
+
12
+ /** A bare domain gets https:// (EditorInline). Mail and site-relative links stay as typed. */
13
+ export function normaliseHref(input: string): string {
14
+ const href = input.trim()
15
+ if (!href) return ""
16
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(href)) return href
17
+ if (looksLikeEmail(href)) return `mailto:${href}`
18
+ return `https://${href}`
19
+ }
20
+
21
+ /**
22
+ * name@domain.tld: one @, a non-empty name, and a dot inside the domain, with
23
+ * no spaces. Checked by splitting rather than one regular expression, which
24
+ * backtracks badly on long hostile input (CodeQL js/polynomial-redos).
25
+ */
26
+ function looksLikeEmail(text: string): boolean {
27
+ if (/\s/.test(text)) return false
28
+ const at = text.indexOf("@")
29
+ if (at <= 0 || at !== text.lastIndexOf("@")) return false
30
+ const domain = text.slice(at + 1)
31
+ const dot = domain.indexOf(".")
32
+ return dot > 0 && dot < domain.length - 1
33
+ }
34
+
35
+ /** Only web, mail and in-app links: never javascript: or data: (the href lands in an <a>). */
36
+ export function isSafeHref(href: string): boolean {
37
+ return /^(?:https?:|mailto:|tel:|\/|#)/i.test(href)
38
+ }
39
+
40
+ const FLOAT = "absolute z-30 flex items-center gap-1.5 rounded-lg border border-border bg-popover shadow-float"
41
+
42
+ /** The address field at the selection (⌘K with text selected, or the bubble's link). */
43
+ function LinkPopover({
44
+ editor,
45
+ labels,
46
+ position,
47
+ onClose,
48
+ }: {
49
+ editor: Editor
50
+ labels: EditorLabels
51
+ position: { top: number; left: number }
52
+ onClose: () => void
53
+ }) {
54
+ const [value, setValue] = React.useState(() => String(editor.getAttributes("link").href ?? ""))
55
+ const input = React.useRef<HTMLInputElement>(null)
56
+ React.useEffect(() => input.current?.focus(), [])
57
+
58
+ const apply = () => {
59
+ const href = normaliseHref(value)
60
+ const chain = editor.chain().focus().extendMarkRange("link")
61
+ if (!href) chain.unsetMark("link").run()
62
+ else if (isSafeHref(href)) chain.setMark("link", { href }).run()
63
+ onClose()
64
+ }
65
+
66
+ return (
67
+ <div data-slot="link-popover" className={`${FLOAT} w-[360px] p-1.5`} style={position}>
68
+ <Icon name="link" className="ms-1 text-muted-foreground" />
69
+ <input
70
+ ref={input}
71
+ aria-label={labels.linkAddress}
72
+ value={value}
73
+ dir="ltr"
74
+ onChange={(e) => setValue(e.target.value)}
75
+ onKeyDown={(e) => {
76
+ if (e.key === "Enter") {
77
+ e.preventDefault()
78
+ apply()
79
+ } else if (e.key === "Escape") {
80
+ e.preventDefault()
81
+ onClose()
82
+ editor.commands.focus()
83
+ }
84
+ }}
85
+ className="h-7 min-w-0 flex-1 rounded-control-sm border border-input bg-card px-2 text-[0.8125rem] outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
86
+ />
87
+ <Button size="sm" variant="outline" onMouseDown={(e) => e.preventDefault()} onClick={apply}>
88
+ {labels.linkApply}
89
+ </Button>
90
+ </div>
91
+ )
92
+ }
93
+
94
+ /** Hovering a link shows its address with copy, edit and remove. */
95
+ function LinkCard({
96
+ editor,
97
+ labels,
98
+ href,
99
+ pos,
100
+ position,
101
+ onEdit,
102
+ onClose,
103
+ onPointerEnter,
104
+ onPointerLeave,
105
+ }: {
106
+ editor: Editor
107
+ labels: EditorLabels
108
+ href: string
109
+ /** A document position inside the link. */
110
+ pos: number
111
+ position: { top: number; left: number }
112
+ onEdit: (pos: number) => void
113
+ onClose: () => void
114
+ onPointerEnter: () => void
115
+ onPointerLeave: () => void
116
+ }) {
117
+ const remove = () => {
118
+ const range = getMarkRange(editor.state.doc.resolve(pos), editor.schema.marks.link)
119
+ if (range) editor.chain().focus().setTextSelection(range).unsetMark("link").run()
120
+ onClose()
121
+ }
122
+ return (
123
+ <div
124
+ data-slot="link-card"
125
+ className={`${FLOAT} max-w-[360px] py-1 ps-2.5 pe-1 text-[0.8125rem]`}
126
+ style={position}
127
+ onPointerEnter={onPointerEnter}
128
+ onPointerLeave={onPointerLeave}
129
+ >
130
+ <Icon name="external" size={14} className="text-muted-foreground" />
131
+ <a href={href} target="_blank" rel="noopener noreferrer" dir="ltr" className="truncate text-primary" aria-label={labels.linkOpen}>
132
+ {href}
133
+ </a>
134
+ <IconButton icon="copy" label={labels.linkCopy} size="sm" onClick={() => void navigator.clipboard?.writeText(href)} />
135
+ <IconButton icon="edit" label={labels.linkEdit} size="sm" onClick={() => onEdit(pos)} />
136
+ {editor.isEditable && <IconButton icon="close" label={labels.linkRemove} size="sm" onClick={remove} />}
137
+ </div>
138
+ )
139
+ }
140
+
141
+ export { LinkCard, LinkPopover }
@@ -0,0 +1,450 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { NodeViewContent, NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from "@tiptap/react"
5
+
6
+ import { Badge } from "../badge"
7
+ import { Chart } from "../chart"
8
+ import { BarcodeSvg } from "../documents/barcode-svg"
9
+ import { Icon } from "../icon"
10
+ import { MathText } from "../math-text"
11
+ import { cn } from "../utils"
12
+ import type { Inline } from "./contract"
13
+ import { fill } from "./labels"
14
+ import {
15
+ BarcodeBlock,
16
+ Callout,
17
+ ChartBlock,
18
+ FileBlock,
19
+ Image,
20
+ MathBlock,
21
+ PageBreak,
22
+ QrBlock,
23
+ RecordBlock,
24
+ SignatureBlock,
25
+ Table,
26
+ Toggle,
27
+ } from "./schema-rich"
28
+ import { Field, MathInline } from "./schema"
29
+ import { formatSize, inlineText, useEditorServices, type ChartData, type RecordView } from "./services"
30
+
31
+ /**
32
+ * How the rich blocks look in the editor (EditorBlocks, bundle.css
33
+ * `.wy-blk--*`). Atoms are read-only here; their block toolbar edits them
34
+ * (block-toolbar.tsx). Containers (callout, toggle) keep their text editable.
35
+ */
36
+
37
+ const blockAttrs = (props: ReactNodeViewProps, type: string) => ({
38
+ "data-type": type,
39
+ "data-block-id": props.node.attrs.id ?? undefined,
40
+ className: cn("wy-rich", props.selected && "is-selected"),
41
+ })
42
+
43
+ function CalloutView(props: ReactNodeViewProps) {
44
+ const important = props.node.attrs.kind === "important"
45
+ return (
46
+ <NodeViewWrapper {...blockAttrs(props, "callout")} data-kind={important ? "important" : "note"}>
47
+ <span contentEditable={false} className="wy-callout-icon">
48
+ <Icon name={important ? "alert" : "info"} />
49
+ </span>
50
+ <NodeViewContent as="div" className="wy-callout-text" />
51
+ </NodeViewWrapper>
52
+ )
53
+ }
54
+
55
+ function ToggleView(props: ReactNodeViewProps) {
56
+ const { labels } = useEditorServices()
57
+ const open = Boolean(props.node.attrs.open)
58
+ return (
59
+ <NodeViewWrapper {...blockAttrs(props, "toggle")} data-open={open ? "true" : "false"}>
60
+ <button
61
+ type="button"
62
+ contentEditable={false}
63
+ className="wy-toggle-button"
64
+ aria-expanded={open}
65
+ aria-label={open ? labels.toggleClose : labels.toggleOpen}
66
+ onMouseDown={(e) => e.preventDefault()}
67
+ onClick={() => props.updateAttributes({ open: !open })}
68
+ >
69
+ <Icon name="chevron-right" />
70
+ </button>
71
+ <NodeViewContent as="div" className="wy-toggle-content" />
72
+ </NodeViewWrapper>
73
+ )
74
+ }
75
+
76
+ function PageBreakView(props: ReactNodeViewProps) {
77
+ const { labels } = useEditorServices()
78
+ return (
79
+ <NodeViewWrapper {...blockAttrs(props, "pageBreak")}>
80
+ <div className="wy-pagebreak">{labels.blockPageBreak}</div>
81
+ </NodeViewWrapper>
82
+ )
83
+ }
84
+
85
+ function ImageView(props: ReactNodeViewProps) {
86
+ const { labels } = useEditorServices()
87
+ const { src, alt, width, caption } = props.node.attrs as { src: string; alt: string; width: string; caption: Inline[] | null }
88
+ return (
89
+ <NodeViewWrapper {...blockAttrs(props, "image")} data-width={width}>
90
+ <figure className="wy-figure">
91
+ {src ? <img src={src} alt={alt} draggable={false} /> : <div className="wy-placeholder">{labels.imageEmpty}</div>}
92
+ {caption && caption.length > 0 && <figcaption dir="auto">{inlineText(caption)}</figcaption>}
93
+ </figure>
94
+ </NodeViewWrapper>
95
+ )
96
+ }
97
+
98
+ function FileView(props: ReactNodeViewProps) {
99
+ const { services, labels } = useEditorServices()
100
+ const { fileId, name, size, mime } = props.node.attrs as { fileId: string; name: string; size: number; mime: string }
101
+ const kind = (mime.split("/")[1] ?? "").toUpperCase()
102
+ const href = fileId && services.fileUrl ? services.fileUrl(fileId) : undefined
103
+ return (
104
+ <NodeViewWrapper {...blockAttrs(props, "file")}>
105
+ <div className="wy-file">
106
+ <span className="wy-tile" aria-hidden="true">
107
+ <Icon name="document" />
108
+ </span>
109
+ <span className="wy-file-meta">
110
+ <span className="font-medium" dir="auto">
111
+ {name || labels.fileEmpty}
112
+ </span>
113
+ {fileId && <span className="text-xs text-muted-foreground">{[formatSize(size), kind].filter(Boolean).join(" · ")}</span>}
114
+ </span>
115
+ {href && (
116
+ <a href={href} download={name} className="wy-file-download" aria-label={fill(labels.fileDownload, { name })} contentEditable={false}>
117
+ <Icon name="download" />
118
+ </a>
119
+ )}
120
+ </div>
121
+ </NodeViewWrapper>
122
+ )
123
+ }
124
+
125
+ /** Loads live data for a block, again whenever the block's source changes. */
126
+ function useLive<T>(key: string, load: (() => Promise<T | null>) | null): { state: "loading" | "ready" | "hidden" | "error" | "none"; data: T | null } {
127
+ const [result, setResult] = React.useState<{ key: string; state: "loading" | "ready" | "hidden" | "error" | "none"; data: T | null }>({ key: "", state: "loading", data: null })
128
+ React.useEffect(() => {
129
+ if (!load) {
130
+ setResult({ key, state: "none", data: null })
131
+ return
132
+ }
133
+ let live = true
134
+ setResult({ key, state: "loading", data: null })
135
+ load()
136
+ .then((data) => live && setResult({ key, state: data === null ? "hidden" : "ready", data }))
137
+ .catch(() => live && setResult({ key, state: "error", data: null }))
138
+ return () => {
139
+ live = false
140
+ }
141
+ // `load` is rebuilt every render; the key says when the source really changed.
142
+ // eslint-disable-next-line react-hooks/exhaustive-deps
143
+ }, [key])
144
+ return result.key === key ? result : { state: "loading", data: null }
145
+ }
146
+
147
+ function RecordView_(props: ReactNodeViewProps) {
148
+ const { services, labels } = useEditorServices()
149
+ const ref = props.node.attrs.ref as { type: string; id: string } | null
150
+ const key = ref ? `${ref.type}:${ref.id}` : ""
151
+ const { state, data } = useLive<RecordView>(key, ref && services.resolveRecord ? () => services.resolveRecord!(ref) : null)
152
+ const summary = props.node.attrs.view === "summary"
153
+ return (
154
+ <NodeViewWrapper {...blockAttrs(props, "record")}>
155
+ <div className="wy-embed">
156
+ <div className="wy-embed-head">
157
+ <Icon name="invoice" size={14} />
158
+ {data?.typeLabel ?? labels.blockRecord}
159
+ <span className="flex-1" />
160
+ {state === "ready" && (
161
+ <>
162
+ <Icon name="sync" size={12} />
163
+ {labels.live}
164
+ </>
165
+ )}
166
+ </div>
167
+ {!ref ? (
168
+ <div className="wy-placeholder">{labels.recordEmpty}</div>
169
+ ) : state === "loading" ? (
170
+ <div className="wy-skeleton" aria-busy="true" />
171
+ ) : state === "hidden" || state === "none" ? (
172
+ <div className="wy-placeholder">{state === "hidden" ? labels.recordHidden : labels.recordUnavailable}</div>
173
+ ) : state === "error" ? (
174
+ <div className="wy-placeholder">{labels.recordFailed}</div>
175
+ ) : data ? (
176
+ <div className="wy-embed-row">
177
+ {!summary && (
178
+ <span className="wy-tile is-tint" aria-hidden="true">
179
+ <Icon name="invoice" />
180
+ </span>
181
+ )}
182
+ <span className="wy-embed-main">
183
+ <span className="font-semibold" dir="auto">
184
+ {data.title}
185
+ </span>
186
+ {data.subtitle && <span className="text-[0.8125rem] text-muted-foreground">{data.subtitle}</span>}
187
+ </span>
188
+ {data.amount && <span className="text-base font-semibold tabular-nums" dir="ltr">{data.amount}</span>}
189
+ {data.status && <Badge variant={data.status.tone}>{data.status.label}</Badge>}
190
+ </div>
191
+ ) : null}
192
+ </div>
193
+ </NodeViewWrapper>
194
+ )
195
+ }
196
+
197
+ /** 4860 → "4.9K": the one labelled bar (BarChart card). Western digits in every language. */
198
+ function compact(value: number): string {
199
+ if (Math.abs(value) >= 1_000_000) return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`
200
+ if (Math.abs(value) >= 1_000) return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}K`
201
+ return String(value)
202
+ }
203
+
204
+ function ChartView(props: ReactNodeViewProps) {
205
+ const { services, labels } = useEditorServices()
206
+ const source = props.node.attrs.source as { query: string; params?: Record<string, string> } | null
207
+ const chart = (props.node.attrs.chart ?? "bar") as "bar" | "line" | "donut"
208
+ const title = props.node.attrs.title as string | null
209
+ const key = source ? JSON.stringify(source) : ""
210
+ const { state, data } = useLive<ChartData>(key, source && services.loadChart ? () => services.loadChart!(source) : null)
211
+ const [asTable, setAsTable] = React.useState(false)
212
+ const rows = (data?.points ?? []).map((p) => ({ label: p.label, value: p.value }))
213
+ const valueLabel = data?.valueLabel ?? title ?? labels.blockChart
214
+ const highest = rows.reduce((best, r, i) => (r.value > (rows[best]?.value ?? -Infinity) ? i : best), 0)
215
+ const ready = state === "ready" && rows.length > 0
216
+ return (
217
+ <NodeViewWrapper {...blockAttrs(props, "chart")}>
218
+ <div className="wy-embed">
219
+ {/* The BarChart card's header: the title, what it covers and that it is live, and a table view. */}
220
+ <div className="wy-chart-head">
221
+ <div className="grid min-w-0">
222
+ <span className="wy-chart-title" dir="auto">
223
+ {title || (source ? services.chartSources?.find((s) => s.key === source.query)?.label : null) || labels.blockChart}
224
+ </span>
225
+ {state === "ready" && (
226
+ <span className="wy-chart-sub" dir="auto">
227
+ {data?.subtitle ? fill(labels.chartLiveRange, { range: data.subtitle }) : labels.live}
228
+ </span>
229
+ )}
230
+ </div>
231
+ {ready && (
232
+ <button
233
+ type="button"
234
+ className="wy-chart-toggle"
235
+ contentEditable={false}
236
+ aria-pressed={asTable}
237
+ onMouseDown={(e) => e.preventDefault()}
238
+ onClick={() => setAsTable((v) => !v)}
239
+ >
240
+ <Icon name={asTable ? "chart" : "table"} size={14} />
241
+ {asTable ? labels.chartShowChart : labels.chartShowTable}
242
+ </button>
243
+ )}
244
+ </div>
245
+ {!source ? (
246
+ <div className="wy-placeholder">{labels.chartEmpty}</div>
247
+ ) : state === "loading" ? (
248
+ <div className="wy-skeleton is-tall" aria-busy="true" />
249
+ ) : ready && asTable ? (
250
+ <table className="wy-chart-table">
251
+ <thead>
252
+ <tr>
253
+ <th scope="col">{labels.chartCategory}</th>
254
+ <th scope="col">{valueLabel}</th>
255
+ </tr>
256
+ </thead>
257
+ <tbody>
258
+ {rows.map((r) => (
259
+ <tr key={r.label}>
260
+ <td dir="auto">{r.label}</td>
261
+ <td dir="ltr">{r.value.toLocaleString("en")}</td>
262
+ </tr>
263
+ ))}
264
+ </tbody>
265
+ </table>
266
+ ) : ready ? (
267
+ <Chart
268
+ type={chart === "donut" ? "pie" : chart}
269
+ data={rows}
270
+ xKey="label"
271
+ series={[{ key: "value", label: valueLabel, color: 1 }]}
272
+ height={170}
273
+ // One series needs no legend; a ring needs one to name its slices.
274
+ legend={chart === "donut"}
275
+ highlight={chart === "bar" ? highest : undefined}
276
+ formatValue={compact}
277
+ donut={chart === "donut"}
278
+ />
279
+ ) : (
280
+ <div className="wy-placeholder">
281
+ {state === "hidden" ? labels.chartHidden : state === "error" ? labels.chartFailed : state === "none" ? labels.chartUnavailable : labels.chartNoData}
282
+ </div>
283
+ )}
284
+ </div>
285
+ </NodeViewWrapper>
286
+ )
287
+ }
288
+
289
+ function SignatureView(props: ReactNodeViewProps) {
290
+ const { labels } = useEditorServices()
291
+ const signers = (props.node.attrs.signers ?? []) as { name: Inline[]; role: Inline[] }[]
292
+ const date = (props.node.attrs.date ?? []) as Inline[]
293
+ return (
294
+ <NodeViewWrapper {...blockAttrs(props, "signature")}>
295
+ <div className="wy-sign">
296
+ {signers.map((s, i) => (
297
+ <div key={i} className="wy-sign-line">
298
+ <b dir="auto">{inlineText(s.name) || labels.signatureName}</b>
299
+ <span dir="auto">{inlineText(s.role)}</span>
300
+ </div>
301
+ ))}
302
+ <div className="wy-sign-line">
303
+ {/* @date-display-ignore: the signature date is text the author typed or a merge field (Inline[]), not a record timestamp; this is its label. */}
304
+ <b>{labels.signatureDate}</b>
305
+ <span dir="auto">{inlineText(date)}</span>
306
+ </div>
307
+ {props.node.attrs.stamp && <div className="wy-sign-stamp">{labels.signatureStamp}</div>}
308
+ </div>
309
+ </NodeViewWrapper>
310
+ )
311
+ }
312
+
313
+ /** A barcode or QR code; a merge field can't be drawn until there's a value, so it shows what fills it. */
314
+ function CodeView(props: ReactNodeViewProps & { qr: boolean }) {
315
+ const { labels } = useEditorServices()
316
+ const value = (props.node.attrs.value ?? []) as Inline[]
317
+ const hasField = value.some((r) => r.type === "field")
318
+ const text = inlineText(value)
319
+ const symbology = props.qr ? "qrcode" : String(props.node.attrs.symbology ?? "code128")
320
+ const caption = props.qr ? inlineText(props.node.attrs.caption as Inline[] | null) : ""
321
+ return (
322
+ <NodeViewWrapper {...blockAttrs(props, props.qr ? "qr" : "barcode")}>
323
+ <figure className={cn("wy-code", props.qr ? "is-qr" : "is-bar")}>
324
+ {!text ? (
325
+ <div className="wy-placeholder">{props.qr ? labels.qrEmpty : labels.barcodeEmpty}</div>
326
+ ) : hasField ? (
327
+ <div className="wy-placeholder is-field" dir="auto">
328
+ {fill(labels.codeFromField, { value: text })}
329
+ </div>
330
+ ) : (
331
+ <div className="wy-code-art" dir="ltr">
332
+ <BarcodeSvg symbology={symbology} value={text} showText={!props.qr && Boolean(props.node.attrs.showText)} />
333
+ </div>
334
+ )}
335
+ {caption && <figcaption dir="auto">{caption}</figcaption>}
336
+ </figure>
337
+ </NodeViewWrapper>
338
+ )
339
+ }
340
+
341
+ function MathView(props: ReactNodeViewProps) {
342
+ const { labels } = useEditorServices()
343
+ const tex = String(props.node.attrs.tex ?? "")
344
+ return (
345
+ <NodeViewWrapper {...blockAttrs(props, "math")}>
346
+ <div className="wy-math-block" dir="ltr">
347
+ {tex ? <MathText expression={tex} block /> : <div className="wy-placeholder">{labels.mathEmpty}</div>}
348
+ </div>
349
+ </NodeViewWrapper>
350
+ )
351
+ }
352
+
353
+ /** An inline formula (E.42), rendered with KaTeX; its source is the tooltip. */
354
+ function MathInlineView(props: ReactNodeViewProps) {
355
+ const tex = String(props.node.attrs.tex ?? "")
356
+ return (
357
+ <NodeViewWrapper as="span" data-math="" dir="ltr" title={tex} className={cn("wy-math", props.selected && "is-selected")}>
358
+ {tex ? <MathText expression={tex} /> : "…"}
359
+ </NodeViewWrapper>
360
+ )
361
+ }
362
+
363
+ /**
364
+ * E.26: a merge field is a chip with its plain name, its path on hover. While
365
+ * previewing with a record it shows the value with a dotted underline, or the
366
+ * name on the error tint when the record has none (E.27).
367
+ */
368
+ function FieldView(props: ReactNodeViewProps) {
369
+ const { labels, preview } = useEditorServices()
370
+ const path = String(props.node.attrs.path ?? "")
371
+ const label = String(props.node.attrs.label || path)
372
+ if (preview) {
373
+ const value = preview.values[path]
374
+ if (value === null || value === undefined || value === "") {
375
+ return (
376
+ <NodeViewWrapper as="span" data-field={path} title={labels.fieldMissing} className="wy-mf is-missing">
377
+ <Icon name="alert" size={12} />
378
+ {label}
379
+ </NodeViewWrapper>
380
+ )
381
+ }
382
+ return (
383
+ <NodeViewWrapper as="span" data-field={path} title={label} className="wy-mf is-preview">
384
+ {value}
385
+ </NodeViewWrapper>
386
+ )
387
+ }
388
+ return (
389
+ <NodeViewWrapper as="span" data-field={path} title={path} className={cn("wy-mf", props.selected && "is-selected")}>
390
+ {label}
391
+ </NodeViewWrapper>
392
+ )
393
+ }
394
+
395
+ /** Table cells take their column's alignment (E.15: end-aligned numbers). */
396
+ const TableWithAlign = Table.extend({
397
+ addNodeView() {
398
+ return ({ node: initial }) => {
399
+ let node = initial
400
+ const dom = document.createElement("table")
401
+ const contentDOM = document.createElement("tbody")
402
+ dom.append(contentDOM)
403
+ const paint = () => {
404
+ dom.dataset.type = "table"
405
+ dom.dataset.headerRow = node.attrs.headerRow ? "true" : "false"
406
+ if (node.attrs.id) dom.dataset.blockId = node.attrs.id
407
+ const columns = (node.attrs.columns ?? []) as { align?: string }[]
408
+ dom.style.setProperty("--wy-columns", String(columns.length))
409
+ requestAnimationFrame(() => {
410
+ contentDOM.querySelectorAll("tr").forEach((tr) =>
411
+ Array.from(tr.children).forEach((cell, i) => {
412
+ ;(cell as HTMLElement).dataset.align = columns[i]?.align === "end" ? "end" : "start"
413
+ })
414
+ )
415
+ })
416
+ }
417
+ paint()
418
+ return {
419
+ dom,
420
+ contentDOM,
421
+ update(next) {
422
+ if (next.type !== node.type) return false
423
+ node = next
424
+ paint()
425
+ return true
426
+ },
427
+ }
428
+ }
429
+ },
430
+ })
431
+
432
+ const react = (component: React.ComponentType<ReactNodeViewProps>) => () => ReactNodeViewRenderer(component)
433
+
434
+ /** The M3 node types with their editor views. */
435
+ export const richNodeViews = [
436
+ Callout.extend({ addNodeView: react(CalloutView) }),
437
+ Toggle.extend({ addNodeView: react(ToggleView) }),
438
+ TableWithAlign,
439
+ PageBreak.extend({ addNodeView: react(PageBreakView) }),
440
+ Image.extend({ addNodeView: react(ImageView) }),
441
+ FileBlock.extend({ addNodeView: react(FileView) }),
442
+ RecordBlock.extend({ addNodeView: react(RecordView_) }),
443
+ ChartBlock.extend({ addNodeView: react(ChartView) }),
444
+ SignatureBlock.extend({ addNodeView: react(SignatureView) }),
445
+ BarcodeBlock.extend({ addNodeView: react((p) => <CodeView {...p} qr={false} />) }),
446
+ QrBlock.extend({ addNodeView: react((p) => <CodeView {...p} qr />) }),
447
+ MathBlock.extend({ addNodeView: react(MathView) }),
448
+ MathInline.extend({ addNodeView: react(MathInlineView) }),
449
+ Field.extend({ addNodeView: react(FieldView) }),
450
+ ]