@whity/ui 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/README.md +106 -2
  2. package/package.json +219 -4
  3. package/src/access-denied.stories.tsx +179 -0
  4. package/src/access-denied.tsx +305 -0
  5. package/src/action-proposal.tsx +338 -0
  6. package/src/actor-chip.tsx +71 -0
  7. package/src/agent-activity.tsx +163 -0
  8. package/src/agent-collaboration.stories.tsx +156 -0
  9. package/src/agent-run-status.tsx +196 -0
  10. package/src/alert-dialog.stories.tsx +45 -0
  11. package/src/alert-dialog.tsx +147 -0
  12. package/src/alert.stories.tsx +91 -0
  13. package/src/alert.tsx +89 -0
  14. package/src/app-sidebar.stories.tsx +195 -0
  15. package/src/app-sidebar.tsx +604 -0
  16. package/src/approval-queue.tsx +109 -0
  17. package/src/audience-group-picker.stories.tsx +198 -0
  18. package/src/audience-group-picker.tsx +362 -0
  19. package/src/audience-people-picker.stories.tsx +102 -0
  20. package/src/audience-people-picker.tsx +279 -0
  21. package/src/avatar-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -0
  23. package/src/badge.stories.tsx +105 -0
  24. package/src/badge.tsx +68 -0
  25. package/src/beta-warning.stories.tsx +79 -0
  26. package/src/beta-warning.tsx +189 -0
  27. package/src/bilingual-input.stories.tsx +82 -0
  28. package/src/bilingual-input.tsx +188 -0
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -0
  31. package/src/breadcrumb.tsx +90 -0
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -0
  34. package/src/button.tsx +123 -0
  35. package/src/card.stories.tsx +423 -0
  36. package/src/card.tsx +180 -0
  37. package/src/chart.stories.tsx +66 -0
  38. package/src/chart.tsx +228 -0
  39. package/src/checkbox.stories.tsx +62 -0
  40. package/src/checkbox.tsx +54 -0
  41. package/src/collapsible.stories.tsx +48 -0
  42. package/src/collapsible.tsx +34 -0
  43. package/src/color-card.stories.tsx +61 -0
  44. package/src/color-card.tsx +270 -0
  45. package/src/color-picker.stories.tsx +65 -0
  46. package/src/color-picker.tsx +425 -0
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +398 -0
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -0
  51. package/src/copy-block.tsx +85 -0
  52. package/src/data-table.stories.tsx +200 -0
  53. package/src/data-table.tsx +1686 -0
  54. package/src/date-picker.stories.tsx +61 -0
  55. package/src/date-picker.tsx +456 -0
  56. package/src/design-cards.stories.tsx +551 -0
  57. package/src/dialog.stories.tsx +48 -0
  58. package/src/dialog.tsx +179 -0
  59. package/src/display-preferences.tsx +50 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -0
  61. package/src/documents/barcode-svg.tsx +79 -0
  62. package/src/dropdown-menu.stories.tsx +77 -0
  63. package/src/dropdown-menu.tsx +271 -0
  64. package/src/editor/agent-panel.tsx +222 -0
  65. package/src/editor/agents.stories.tsx +81 -0
  66. package/src/editor/agents.ts +55 -0
  67. package/src/editor/behaviour.ts +279 -0
  68. package/src/editor/block-ids.ts +44 -0
  69. package/src/editor/block-list.tsx +104 -0
  70. package/src/editor/block-toolbar.tsx +490 -0
  71. package/src/editor/bubble.tsx +119 -0
  72. package/src/editor/catalogue.ts +169 -0
  73. package/src/editor/collab-rail.tsx +746 -0
  74. package/src/editor/collab.stories.tsx +207 -0
  75. package/src/editor/collab.ts +87 -0
  76. package/src/editor/contract.ts +476 -0
  77. package/src/editor/convert.ts +414 -0
  78. package/src/editor/doc-editor.stories.tsx +98 -0
  79. package/src/editor/doc-editor.tsx +1492 -0
  80. package/src/editor/editor.css +636 -0
  81. package/src/editor/extensions.ts +86 -0
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -0
  84. package/src/editor/fields.ts +100 -0
  85. package/src/editor/gutter.tsx +443 -0
  86. package/src/editor/index.ts +23 -0
  87. package/src/editor/label-sheet.tsx +289 -0
  88. package/src/editor/labels.ts +394 -0
  89. package/src/editor/link-tools.tsx +141 -0
  90. package/src/editor/node-views.tsx +461 -0
  91. package/src/editor/page-view.tsx +372 -0
  92. package/src/editor/phone.tsx +310 -0
  93. package/src/editor/plugin-block-view.tsx +230 -0
  94. package/src/editor/plugin-blocks.stories.tsx +96 -0
  95. package/src/editor/plugin-blocks.ts +52 -0
  96. package/src/editor/publish-check.tsx +201 -0
  97. package/src/editor/rich-blocks.stories.tsx +146 -0
  98. package/src/editor/sample.ts +40 -0
  99. package/src/editor/save-block-dialog.tsx +141 -0
  100. package/src/editor/saved-block-view.tsx +205 -0
  101. package/src/editor/saved-blocks.stories.tsx +105 -0
  102. package/src/editor/saved-parts.ts +192 -0
  103. package/src/editor/schema-rich.ts +156 -0
  104. package/src/editor/schema.ts +368 -0
  105. package/src/editor/services.tsx +205 -0
  106. package/src/editor/slash.ts +64 -0
  107. package/src/editor/suggesting.ts +372 -0
  108. package/src/editor/suggestions.ts +763 -0
  109. package/src/editor/table-keys.ts +66 -0
  110. package/src/editor/templates.stories.tsx +324 -0
  111. package/src/editor/toolbar.tsx +364 -0
  112. package/src/empty-state.stories.tsx +51 -0
  113. package/src/empty-state.tsx +126 -0
  114. package/src/empty-state.usage-notes.md +30 -0
  115. package/src/form.stories.tsx +112 -0
  116. package/src/form.tsx +176 -0
  117. package/src/globals.css +20 -0
  118. package/src/icon-button.tsx +85 -0
  119. package/src/icon-map.ts +335 -0
  120. package/src/icon.tsx +41 -0
  121. package/src/index.ts +90 -0
  122. package/src/input.stories.tsx +157 -0
  123. package/src/input.tsx +768 -0
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -0
  127. package/src/locked-screen.tsx +75 -0
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -0
  131. package/src/math-text.stories.tsx +33 -0
  132. package/src/math-text.tsx +43 -0
  133. package/src/menu-bar.stories.tsx +198 -0
  134. package/src/menu-bar.tsx +373 -0
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -0
  137. package/src/money/money-input.tsx +131 -0
  138. package/src/money/money.tsx +33 -0
  139. package/src/open-on-computer.tsx +150 -0
  140. package/src/otp-input.tsx +161 -0
  141. package/src/page-header.stories.tsx +95 -0
  142. package/src/page-header.tsx +122 -0
  143. package/src/page-shell.stories.tsx +42 -0
  144. package/src/page-shell.tsx +32 -0
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -0
  147. package/src/pagination.tsx +98 -0
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-tab-bar.tsx +152 -0
  151. package/src/plugin-card.stories.tsx +208 -0
  152. package/src/plugin-card.tsx +931 -0
  153. package/src/popover.stories.tsx +48 -0
  154. package/src/popover.tsx +55 -0
  155. package/src/radio-group.stories.tsx +26 -0
  156. package/src/radio-group.tsx +44 -0
  157. package/src/route-flow/editor.tsx +1087 -0
  158. package/src/route-flow/model.ts +771 -0
  159. package/src/save-bar.tsx +94 -0
  160. package/src/scope-grant.tsx +139 -0
  161. package/src/screen-too-small.stories.tsx +61 -0
  162. package/src/screen-too-small.tsx +104 -0
  163. package/src/search-field.tsx +65 -0
  164. package/src/select.stories.tsx +44 -0
  165. package/src/select.tsx +197 -0
  166. package/src/separator.stories.tsx +34 -0
  167. package/src/separator.tsx +34 -0
  168. package/src/sheet.stories.tsx +49 -0
  169. package/src/sheet.tsx +168 -0
  170. package/src/skeleton.stories.tsx +28 -0
  171. package/src/skeleton.tsx +19 -0
  172. package/src/slider.stories.tsx +78 -0
  173. package/src/slider.tsx +300 -0
  174. package/src/spinner.stories.tsx +33 -0
  175. package/src/spinner.tsx +55 -0
  176. package/src/stepper.tsx +85 -0
  177. package/src/switch.stories.tsx +42 -0
  178. package/src/switch.tsx +41 -0
  179. package/src/switcher.stories.tsx +111 -0
  180. package/src/switcher.tsx +131 -0
  181. package/src/system-state.tsx +55 -0
  182. package/src/table.stories.tsx +48 -0
  183. package/src/table.tsx +121 -0
  184. package/src/tabs.stories.tsx +74 -0
  185. package/src/tabs.tsx +90 -0
  186. package/src/tag-input.stories.tsx +67 -0
  187. package/src/tag-input.tsx +117 -0
  188. package/src/tenant-logo.tsx +63 -0
  189. package/src/tenant-switcher.stories.tsx +38 -0
  190. package/src/tenant-switcher.tsx +164 -0
  191. package/src/textarea.stories.tsx +27 -0
  192. package/src/textarea.tsx +18 -0
  193. package/src/theme-mode.ts +52 -0
  194. package/src/time-grid.tsx +163 -0
  195. package/src/time-picker.stories.tsx +62 -0
  196. package/src/time-picker.tsx +615 -0
  197. package/src/toggle-group.tsx +138 -0
  198. package/src/tooltip.stories.tsx +43 -0
  199. package/src/tooltip.tsx +73 -0
  200. package/src/top-nav.stories.tsx +58 -0
  201. package/src/top-nav.tsx +324 -0
  202. package/src/undo-bar.tsx +107 -0
  203. package/src/utils.ts +45 -0
  204. package/src/view-toggle.stories.tsx +84 -0
  205. package/src/view-toggle.tsx +110 -0
@@ -0,0 +1,230 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { NodeViewWrapper, type ReactNodeViewProps } from "@tiptap/react"
5
+
6
+ import { Button } from "../button"
7
+ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../dialog"
8
+ import { Icon } from "../icon"
9
+ import { Input } from "../input"
10
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../select"
11
+ import { Textarea } from "../textarea"
12
+ import { cn } from "../utils"
13
+ import { fill, type EditorLabels } from "./labels"
14
+ import { fieldValues, fillView, findPluginBlock } from "./plugin-blocks"
15
+ import { useEditorServices, type PluginBlockDefinition } from "./services"
16
+ import { localizedText } from "../localized-text"
17
+
18
+ /**
19
+ * A plugin's block in a document (EditorCustomBlocks; E.17–E.20). Whity's
20
+ * renderer draws its declared view with Whity's components; nothing the
21
+ * plugin ships runs here. Selected or hovered, its source label shows the
22
+ * plugin, Verified or Not verified (Whity's mark only), and Prints or Notes
23
+ * only, with Edit opening a form built from its fields.
24
+ *
25
+ * When its plugin is off or gone, a placeholder says which plugin it needs,
26
+ * with Enable for people who may switch workspace plugins on; the block's
27
+ * data stays in the document (E.19).
28
+ */
29
+ export function PluginBlockView(props: ReactNodeViewProps) {
30
+ const { services, labels } = useEditorServices()
31
+ const lang = services.language ?? "en"
32
+ const plugin = String(props.node.attrs.plugin ?? "")
33
+ const blockType = String(props.node.attrs.blockType ?? "")
34
+ const data = (props.node.attrs.data ?? {}) as Record<string, unknown>
35
+ const found = findPluginBlock(services.pluginBlocks, plugin, blockType)
36
+ const editable = props.editor.isEditable
37
+ const [editing, setEditing] = React.useState(false)
38
+
39
+ if (!found) {
40
+ return (
41
+ <NodeViewWrapper data-type="plugin" data-block-id={props.node.attrs.id ?? undefined} className={cn("wy-rich", props.selected && "is-selected")}>
42
+ <PluginOff plugin={plugin} />
43
+ </NodeViewWrapper>
44
+ )
45
+ }
46
+
47
+ const { source, definition } = found
48
+ const name = localizedText(definition.label, lang)
49
+ const view = fillView(definition.view, fieldValues(definition, data, lang), lang)
50
+ return (
51
+ <NodeViewWrapper
52
+ data-type="plugin"
53
+ data-block-id={props.node.attrs.id ?? undefined}
54
+ className={cn("wy-rich wy-plugin", props.selected && "is-selected")}
55
+ role="group"
56
+ aria-label={fill(labels.pluginBlockLabel, { name, plugin: localizedText(source.label, lang) })}
57
+ >
58
+ <div className="wy-saved-src" contentEditable={false}>
59
+ <span className="wy-plugin-tile" aria-hidden="true">
60
+ {localizedText(source.label, lang).slice(0, 1).toUpperCase()}
61
+ </span>
62
+ <b dir="auto">{localizedText(source.label, lang)}</b>
63
+ {source.verified ? (
64
+ <span className="wy-plugin-mark">
65
+ <Icon name="check" size={12} /> {labels.pluginVerified}
66
+ </span>
67
+ ) : (
68
+ <span>{labels.pluginNotVerified}</span>
69
+ )}
70
+ <span className="wy-saved-sep" aria-hidden="true" />
71
+ <span>{definition.print ? labels.pluginPrints : labels.pluginNotesOnly}</span>
72
+ {editable && definition.fields.length > 0 && (
73
+ <>
74
+ <span className="wy-saved-sep" aria-hidden="true" />
75
+ <button type="button" className="wy-saved-action" onMouseDown={(e) => e.preventDefault()} onClick={() => setEditing(true)}>
76
+ {labels.pluginEdit}
77
+ </button>
78
+ </>
79
+ )}
80
+ </div>
81
+ <div className="wy-plugin-body" contentEditable={false}>
82
+ {services.renderPluginView ? services.renderPluginView(view) : <div className="wy-placeholder">{name}</div>}
83
+ </div>
84
+ {editing && (
85
+ <PluginBlockForm
86
+ definition={definition}
87
+ data={data}
88
+ lang={lang}
89
+ labels={labels}
90
+ onClose={() => setEditing(false)}
91
+ onSave={(next) => {
92
+ props.updateAttributes({ data: next })
93
+ setEditing(false)
94
+ }}
95
+ />
96
+ )}
97
+ </NodeViewWrapper>
98
+ )
99
+ }
100
+
101
+ /** E.19: the block's plugin is off or gone. The data stays; Enable for those who may. */
102
+ function PluginOff({ plugin }: { plugin: string }) {
103
+ const { services, labels } = useEditorServices()
104
+ const lang = services.language ?? "en"
105
+ const off = services.pluginBlocks?.off.find((p) => p.plugin === plugin)
106
+ const name = off ? localizedText(off.label, lang) : plugin
107
+ const canEnable = !!off && !!services.pluginBlocks?.canEnable && !!services.enablePlugin
108
+ const [busy, setBusy] = React.useState(false)
109
+ const [failed, setFailed] = React.useState(false)
110
+ return (
111
+ <div className="wy-plugin-off" contentEditable={false}>
112
+ <span className="wy-tile" aria-hidden="true">
113
+ <Icon name="plugin" />
114
+ </span>
115
+ <span className="grid min-w-0 flex-1 gap-0.5">
116
+ <span className="font-medium" dir="auto">
117
+ {fill(labels.pluginNeeds, { plugin: name })}
118
+ </span>
119
+ <span className="text-sm text-muted-foreground">{failed ? labels.pluginEnableFailed : labels.pluginNeedsHint}</span>
120
+ </span>
121
+ {canEnable && (
122
+ <Button
123
+ variant="outline"
124
+ size="sm"
125
+ loading={busy}
126
+ onMouseDown={(e) => e.preventDefault()}
127
+ onClick={async () => {
128
+ setBusy(true)
129
+ setFailed(false)
130
+ try {
131
+ await services.enablePlugin!(plugin)
132
+ } catch {
133
+ setFailed(true)
134
+ } finally {
135
+ setBusy(false)
136
+ }
137
+ }}
138
+ >
139
+ {labels.pluginEnable}
140
+ </Button>
141
+ )}
142
+ </div>
143
+ )
144
+ }
145
+
146
+ /** The block's Edit form, built from its declared fields. */
147
+ function PluginBlockForm({
148
+ definition,
149
+ data,
150
+ lang,
151
+ labels,
152
+ onClose,
153
+ onSave,
154
+ }: {
155
+ definition: PluginBlockDefinition
156
+ data: Record<string, unknown>
157
+ lang: "en" | "ar"
158
+ labels: EditorLabels
159
+ onClose: () => void
160
+ onSave: (data: Record<string, unknown>) => void
161
+ }) {
162
+ const [values, setValues] = React.useState<Record<string, string>>(() =>
163
+ Object.fromEntries(definition.fields.map((f) => [f.key, data[f.key] === null || data[f.key] === undefined ? "" : String(data[f.key])]))
164
+ )
165
+ const id = React.useId()
166
+ const missing = definition.fields.some((f) => f.required && !values[f.key]?.trim())
167
+ const set = (key: string, value: string) => setValues((v) => ({ ...v, [key]: value }))
168
+ return (
169
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
170
+ <DialogContent className="max-w-[440px]" closeLabel={labels.pluginCancel}>
171
+ <form
172
+ className="grid gap-4"
173
+ onSubmit={(e) => {
174
+ e.preventDefault()
175
+ if (missing) return
176
+ onSave(Object.fromEntries(definition.fields.map((f) => [f.key, f.type === "number" && values[f.key] !== "" ? Number(values[f.key]) : values[f.key]])))
177
+ }}
178
+ >
179
+ <DialogHeader>
180
+ <DialogTitle>{fill(labels.pluginEditTitle, { name: localizedText(definition.label, lang) })}</DialogTitle>
181
+ </DialogHeader>
182
+ {definition.fields.map((field) => {
183
+ const fieldId = `${id}-${field.key}`
184
+ const label = localizedText(field.label, lang)
185
+ return (
186
+ <div key={field.key} className="grid gap-1.5">
187
+ <label htmlFor={fieldId} className="text-sm font-medium">
188
+ {label}
189
+ </label>
190
+ {field.type === "longText" ? (
191
+ <Textarea id={fieldId} dir="auto" value={values[field.key]} onChange={(e) => set(field.key, e.target.value)} />
192
+ ) : field.type === "select" ? (
193
+ <Select value={values[field.key] || undefined} onValueChange={(v) => set(field.key, v)}>
194
+ <SelectTrigger id={fieldId}>
195
+ <SelectValue placeholder={labels.pluginChoose} />
196
+ </SelectTrigger>
197
+ <SelectContent>
198
+ {(field.options ?? []).map((o) => (
199
+ <SelectItem key={o.value} value={o.value}>
200
+ {localizedText(o.label, lang)}
201
+ </SelectItem>
202
+ ))}
203
+ </SelectContent>
204
+ </Select>
205
+ ) : (
206
+ <Input
207
+ id={fieldId}
208
+ dir={field.type === "text" ? "auto" : "ltr"}
209
+ type={field.type === "number" ? "number" : field.type === "date" ? "date" : "text"}
210
+ required={field.required}
211
+ value={values[field.key]}
212
+ onChange={(e) => set(field.key, e.target.value)}
213
+ />
214
+ )}
215
+ </div>
216
+ )
217
+ })}
218
+ <DialogFooter>
219
+ <Button type="button" variant="outline" onClick={onClose}>
220
+ {labels.pluginCancel}
221
+ </Button>
222
+ <Button type="submit" disabled={missing}>
223
+ {labels.pluginSave}
224
+ </Button>
225
+ </DialogFooter>
226
+ </form>
227
+ </DialogContent>
228
+ </Dialog>
229
+ )
230
+ }
@@ -0,0 +1,96 @@
1
+ import type { Meta, StoryObj } from "@storybook/react-vite"
2
+ import * as React from "react"
3
+
4
+ import type { WhityDocument } from "./contract"
5
+ import { DocEditor } from "./doc-editor"
6
+ import { SAMPLE_DOCUMENT } from "./sample"
7
+ import type { EditorServices, PluginBlocks } from "./services"
8
+
9
+ /**
10
+ * Editor M7, the plugin half of the EditorCustomBlocks card: a Verified
11
+ * plugin's block drawn by Whity (hover or select it for its source label and
12
+ * Edit), and a block whose plugin is off (E.19). In the app, the view is
13
+ * drawn by Whity's screen renderer; here a stand-in draws its key/value rows.
14
+ */
15
+ const meta = {
16
+ title: "Editor/Plugin blocks",
17
+ parameters: { layout: "fullscreen", fullBleed: true },
18
+ } satisfies Meta
19
+
20
+ export default meta
21
+ type Story = StoryObj<typeof meta>
22
+
23
+ const L = (en: string, ar = en) => ({ en, ar })
24
+
25
+ const BLOCKS: PluginBlocks = {
26
+ plugins: [
27
+ {
28
+ plugin: "DeliveryTracker",
29
+ label: L("Delivery Tracker", "متتبع التوصيل"),
30
+ verified: true,
31
+ firstParty: false,
32
+ blocks: [
33
+ {
34
+ name: "DeliveryTracker/delivery_status",
35
+ blockType: "delivery_status",
36
+ label: L("Delivery status", "حالة التوصيل"),
37
+ description: L("Where an order is", "أين الطلب"),
38
+ icon: "package",
39
+ keywords: [],
40
+ fields: [
41
+ { key: "order", label: L("Order", "الطلب"), type: "text", required: true },
42
+ { key: "customer", label: L("Customer", "العميل"), type: "text" },
43
+ { key: "stage", label: L("Stage", "المرحلة"), type: "select", options: [{ value: "packed", label: L("Packed", "مُعبأ") }, { value: "out", label: L("Out for delivery", "في الطريق") }] },
44
+ ],
45
+ view: [{ type: "keyValue", items: [{ label: "Order", value: "{{data.order}}" }, { label: "Customer", value: "{{data.customer}}" }, { label: "Stage", value: "{{data.stage}}" }] }],
46
+ print: [{ type: "keyValue", items: [{ label: "Order", value: "{{data.order}}" }] }],
47
+ allowedIn: ["note", "wiki", "template"],
48
+ },
49
+ ],
50
+ },
51
+ ],
52
+ off: [{ plugin: "RouteMaps", label: L("Route Maps", "خرائط المسار") }],
53
+ canEnable: true,
54
+ }
55
+
56
+ /** A stand-in for Whity's screen renderer: key/value rows. */
57
+ function KeyValues({ view }: { view: unknown[] }) {
58
+ const items = (view as { items?: { label: string; value: string }[] }[]).flatMap((n) => n.items ?? [])
59
+ return (
60
+ <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-1 rounded-card border border-border bg-card px-4 py-3 text-sm">
61
+ {items.map((i) => (
62
+ <React.Fragment key={i.label}>
63
+ <dt className="text-muted-foreground">{i.label}</dt>
64
+ <dd className="font-medium">{i.value}</dd>
65
+ </React.Fragment>
66
+ ))}
67
+ </dl>
68
+ )
69
+ }
70
+
71
+ const SERVICES: EditorServices = {
72
+ pluginBlocks: BLOCKS,
73
+ renderPluginView: (view) => <KeyValues view={view} />,
74
+ enablePlugin: async () => undefined,
75
+ }
76
+
77
+ const DOC: WhityDocument = {
78
+ ...SAMPLE_DOCUMENT,
79
+ title: "Order handover",
80
+ blocks: [
81
+ { id: "p1", type: "paragraph", content: [{ type: "text", text: "Where Example Clinic's order is:" }] },
82
+ { id: "d1", type: "plugin", plugin: "DeliveryTracker", blockType: "delivery_status", schemaVersion: 1, data: { order: "SO-2207", customer: "Example Clinic", stage: "out" } },
83
+ { id: "r1", type: "plugin", plugin: "RouteMaps", blockType: "route", schemaVersion: 1, data: {} },
84
+ ],
85
+ }
86
+
87
+ function Editor() {
88
+ const [doc, setDoc] = React.useState(DOC)
89
+ return (
90
+ <div className="h-screen">
91
+ <DocEditor document={doc} onChange={setDoc} canEdit services={SERVICES} />
92
+ </div>
93
+ )
94
+ }
95
+
96
+ export const InADocument: Story = { render: () => <Editor /> }
@@ -0,0 +1,52 @@
1
+ import type { Localized, PluginBlockDefinition, PluginBlocks, PluginBlockSource } from "./services"
2
+ import { localizedText } from "../localized-text"
3
+
4
+ /**
5
+ * Plugin blocks in the editor (editor M7, E.17–E.20). A block's view is a
6
+ * declaration; this fills it with the block's data the way Whity's printer
7
+ * does (PluginBlockPrinter): `{{data.key}}` becomes the field's value, a
8
+ * select's value its option's label, and `{en, ar}` text the reader's
9
+ * language. Nothing a plugin declares is run.
10
+ */
11
+
12
+ /** Each field's shown text; a select shows its option's label. */
13
+ export function fieldValues(definition: PluginBlockDefinition, data: Record<string, unknown>, lang: "en" | "ar"): Record<string, string> {
14
+ const out: Record<string, string> = {}
15
+ for (const field of definition.fields) {
16
+ const raw = data[field.key]
17
+ let text = raw === null || raw === undefined ? "" : String(raw)
18
+ if (field.type === "select") {
19
+ const option = field.options?.find((o) => o.value === text)
20
+ if (option) text = localizedText(option.label, lang)
21
+ }
22
+ out[field.key] = text
23
+ }
24
+ return out
25
+ }
26
+
27
+ const isLocalized = (v: unknown): v is Localized =>
28
+ !!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => k === "en" || k === "ar")
29
+
30
+ /** The view with `{{data.key}}` filled and `{en, ar}` text in the reader's language. */
31
+ export function fillView(view: unknown[], values: Record<string, string>, lang: "en" | "ar"): unknown[] {
32
+ const fill = (value: unknown): unknown => {
33
+ if (typeof value === "string") return value.replace(/\{\{\s*data\.([a-z][a-z0-9_]{0,39})\s*\}\}/g, (_, key: string) => values[key] ?? "")
34
+ if (isLocalized(value)) return fill(localizedText(value, lang))
35
+ if (Array.isArray(value)) return value.map(fill)
36
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fill(v)]))
37
+ return value
38
+ }
39
+ return view.map(fill)
40
+ }
41
+
42
+ /** A block's declaration and its plugin, or null when the plugin is off, gone or no longer declares it. */
43
+ export function findPluginBlock(blocks: PluginBlocks | undefined, plugin: string, blockType: string): { source: PluginBlockSource; definition: PluginBlockDefinition } | null {
44
+ const source = blocks?.plugins.find((p) => p.plugin === plugin)
45
+ const definition = source?.blocks.find((b) => b.blockType === blockType)
46
+ return source && definition ? { source, definition } : null
47
+ }
48
+
49
+ /** A new block's data: empty text, a select's first option. */
50
+ export function defaultData(definition: PluginBlockDefinition): Record<string, unknown> {
51
+ return Object.fromEntries(definition.fields.map((f) => [f.key, f.type === "select" ? (f.options?.[0]?.value ?? "") : ""]))
52
+ }
@@ -0,0 +1,201 @@
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
+ "too-large": "image",
31
+ }
32
+
33
+ /** A size in megabytes with one decimal, Western digits in either language. */
34
+ /** A size in MB, or in KB below 1 MB so a small limit never reads "0.0 MB" (WHIT-916). */
35
+ function megabytes(bytes: number): string {
36
+ const mb = 1024 * 1024
37
+ if (bytes < mb) {
38
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`
39
+ }
40
+ return `${(bytes / mb).toFixed(1)} MB`
41
+ }
42
+
43
+ /**
44
+ * `fill` for text that holds a value from elsewhere: each `{key}` becomes the
45
+ * node given, so a theme ref can sit in a `<bdi>` inside an Arabic sentence.
46
+ */
47
+ function fillNodes(template: string, values: Record<string, React.ReactNode>): React.ReactNode {
48
+ return template.split(/(\{\w+\})/).map((part, i) => {
49
+ const m = /^\{(\w+)\}$/.exec(part)
50
+ return m && m[1] in values ? <React.Fragment key={i}>{values[m[1]]}</React.Fragment> : part
51
+ })
52
+ }
53
+
54
+ function blockerText(
55
+ b: PublishBlocker,
56
+ labels: EditorLabels,
57
+ names: { plugin?: (id: string) => string; field?: (path: string) => string }
58
+ ): { title: React.ReactNode; hint: string; action?: string } {
59
+ switch (b.kind) {
60
+ case "open-suggestions":
61
+ return {
62
+ title: b.count === 1 ? labels.blockerSuggestion : fill(labels.blockerSuggestions, { n: b.count }),
63
+ hint: labels.blockerSuggestionsHint,
64
+ action: labels.review,
65
+ }
66
+ case "missing-plugin":
67
+ return { title: fill(labels.blockerPlugin, { plugin: names.plugin?.(b.plugin) ?? b.plugin }), hint: labels.blockerPluginHint, action: labels.show }
68
+ case "block-without-print-view":
69
+ return { title: labels.blockerNoPrint, hint: labels.blockerNoPrintHint, action: labels.show }
70
+ case "unknown-field":
71
+ return { title: fill(labels.blockerField, { field: names.field?.(b.path) ?? b.path }), hint: labels.blockerFieldHint, action: labels.show }
72
+ case "theme-unavailable":
73
+ // No way to fix it here until the theme picker (WHIT-736): the hint says what to do.
74
+ return { title: fillNodes(labels.blockerTheme, { ref: <bdi dir="ltr">{b.ref}</bdi> }), hint: labels.blockerThemeHint }
75
+ case "too-large":
76
+ return {
77
+ title: fillNodes(labels.blockerTooLarge, {
78
+ size: <bdi dir="ltr">{megabytes(b.bytes)}</bdi>,
79
+ max: <bdi dir="ltr">{megabytes(b.max)}</bdi>,
80
+ }),
81
+ hint: labels.blockerTooLargeHint,
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Publish (E.9) opens this check first (TplDocDesigner): what blocks
88
+ * publishing, each with a way to fix it, and Publish stays disabled until the
89
+ * list is empty (E.37). Publishing makes the draft the version Whity Render
90
+ * and agents use.
91
+ */
92
+ function PublishCheck({
93
+ open,
94
+ onOpenChange,
95
+ blockers,
96
+ checking = false,
97
+ nextVersion,
98
+ recordLabel,
99
+ onPublish,
100
+ onFix,
101
+ labels,
102
+ pluginName,
103
+ fieldLabel,
104
+ }: {
105
+ open: boolean
106
+ onOpenChange: (open: boolean) => void
107
+ blockers: PublishBlocker[]
108
+ /** While the server's check is running. */
109
+ checking?: boolean
110
+ nextVersion: number
111
+ /** What the template prints, plural: "payment reminders". */
112
+ recordLabel?: string
113
+ onPublish: () => Promise<void> | void
114
+ onFix: (blocker: PublishBlocker) => void
115
+ labels: EditorLabels
116
+ pluginName?: (id: string) => string
117
+ fieldLabel?: (path: string) => string
118
+ }) {
119
+ const [busy, setBusy] = React.useState(false)
120
+ const [error, setError] = React.useState(false)
121
+ React.useEffect(() => {
122
+ if (open) setError(false)
123
+ }, [open])
124
+ const publish = async () => {
125
+ setBusy(true)
126
+ setError(false)
127
+ try {
128
+ await onPublish()
129
+ onOpenChange(false)
130
+ } catch {
131
+ setError(true)
132
+ } finally {
133
+ setBusy(false)
134
+ }
135
+ }
136
+ const clear = !checking && blockers.length === 0
137
+ return (
138
+ <Dialog open={open} onOpenChange={onOpenChange}>
139
+ <DialogContent className="max-w-[440px]" closeLabel={labels.keepEditing}>
140
+ <DialogHeader>
141
+ <DialogTitle>{labels.publishTitle}</DialogTitle>
142
+ <DialogDescription>
143
+ {recordLabel ? fill(labels.publishExplainFor, { records: recordLabel }) : labels.publishExplain}
144
+ </DialogDescription>
145
+ </DialogHeader>
146
+ {checking ? (
147
+ <p role="status" className="text-sm text-muted-foreground">
148
+ {labels.publishChecking}
149
+ </p>
150
+ ) : blockers.length > 0 ? (
151
+ <ul className="m-0 grid list-none gap-2 p-0" aria-label={labels.publishBlockers}>
152
+ {blockers.map((b, i) => {
153
+ const t = blockerText(b, labels, { plugin: pluginName, field: fieldLabel })
154
+ return (
155
+ <li key={i} className="flex items-start gap-2.5 rounded-control-lg border border-border px-3 py-2.5 text-sm">
156
+ <Icon name={ICON[b.kind]} className="mt-0.5 shrink-0 text-warning-text" />
157
+ <div className="grid flex-1 gap-0.5">
158
+ <span className="font-medium">{t.title}</span>
159
+ <span className="text-[0.8125rem] text-muted-foreground">{t.hint}</span>
160
+ </div>
161
+ {t.action && (
162
+ <Button
163
+ variant="outline"
164
+ size="sm"
165
+ onClick={() => {
166
+ onOpenChange(false)
167
+ onFix(b)
168
+ }}
169
+ >
170
+ {t.action}
171
+ </Button>
172
+ )}
173
+ </li>
174
+ )
175
+ })}
176
+ </ul>
177
+ ) : (
178
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
179
+ <Icon name="check" className="text-success-text" />
180
+ {labels.publishClear}
181
+ </p>
182
+ )}
183
+ {error && (
184
+ <p role="alert" className="text-sm text-error-text">
185
+ {labels.publishFailed}
186
+ </p>
187
+ )}
188
+ <DialogFooter>
189
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
190
+ {labels.keepEditing}
191
+ </Button>
192
+ <Button icon="check" disabled={!clear || busy} onClick={publish}>
193
+ {fill(labels.publishVersion, { n: nextVersion })}
194
+ </Button>
195
+ </DialogFooter>
196
+ </DialogContent>
197
+ </Dialog>
198
+ )
199
+ }
200
+
201
+ export { PublishCheck }