@whity/ui 0.5.0 → 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 +107 -107
  2. package/package.json +221 -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 +123 -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 +398 -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 +1686 -1106
  54. package/src/date-picker.stories.tsx +61 -61
  55. package/src/date-picker.tsx +456 -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 +50 -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 +90 -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-tab-bar.tsx +152 -0
  151. package/src/plugin-card.stories.tsx +208 -180
  152. package/src/plugin-card.tsx +931 -848
  153. package/src/popover.stories.tsx +48 -48
  154. package/src/popover.tsx +55 -55
  155. package/src/radio-group.stories.tsx +26 -26
  156. package/src/radio-group.tsx +44 -44
  157. package/src/route-flow/editor.tsx +1087 -1014
  158. package/src/route-flow/model.ts +771 -716
  159. package/src/save-bar.tsx +94 -0
  160. package/src/scope-grant.tsx +139 -139
  161. package/src/screen-too-small.stories.tsx +61 -61
  162. package/src/screen-too-small.tsx +104 -104
  163. package/src/search-field.tsx +65 -0
  164. package/src/select.stories.tsx +44 -44
  165. package/src/select.tsx +197 -197
  166. package/src/separator.stories.tsx +34 -34
  167. package/src/separator.tsx +34 -34
  168. package/src/sheet.stories.tsx +49 -49
  169. package/src/sheet.tsx +168 -168
  170. package/src/skeleton.stories.tsx +28 -28
  171. package/src/skeleton.tsx +19 -19
  172. package/src/slider.stories.tsx +78 -78
  173. package/src/slider.tsx +300 -300
  174. package/src/spinner.stories.tsx +33 -33
  175. package/src/spinner.tsx +55 -55
  176. package/src/stepper.tsx +85 -0
  177. package/src/switch.stories.tsx +42 -42
  178. package/src/switch.tsx +41 -41
  179. package/src/switcher.stories.tsx +111 -111
  180. package/src/switcher.tsx +131 -131
  181. package/src/system-state.tsx +55 -0
  182. package/src/table.stories.tsx +48 -48
  183. package/src/table.tsx +121 -121
  184. package/src/tabs.stories.tsx +74 -74
  185. package/src/tabs.tsx +90 -90
  186. package/src/tag-input.stories.tsx +67 -67
  187. package/src/tag-input.tsx +117 -117
  188. package/src/tenant-logo.tsx +63 -63
  189. package/src/tenant-switcher.stories.tsx +38 -38
  190. package/src/tenant-switcher.tsx +164 -164
  191. package/src/textarea.stories.tsx +27 -27
  192. package/src/textarea.tsx +18 -18
  193. package/src/theme-mode.ts +52 -52
  194. package/src/time-grid.tsx +163 -0
  195. package/src/time-picker.stories.tsx +62 -62
  196. package/src/time-picker.tsx +615 -615
  197. package/src/toggle-group.tsx +138 -138
  198. package/src/tooltip.stories.tsx +43 -43
  199. package/src/tooltip.tsx +73 -73
  200. package/src/top-nav.stories.tsx +58 -58
  201. package/src/top-nav.tsx +324 -324
  202. package/src/undo-bar.tsx +107 -107
  203. package/src/utils.ts +45 -45
  204. package/src/view-toggle.stories.tsx +84 -84
  205. package/src/view-toggle.tsx +110 -110
@@ -0,0 +1,205 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { NodeViewWrapper, type ReactNodeViewProps } from "@tiptap/react"
5
+
6
+ import { Icon } from "../icon"
7
+ import { cn } from "../utils"
8
+ import type { Block, Inline } from "./contract"
9
+ import { freshEditorBlocks } from "./convert"
10
+ import { applyOverrides, lookupPart, partText, segments, type Segment } from "./saved-parts"
11
+ import { fill, type EditorLabels } from "./labels"
12
+ import { inlineText, useEditorServices } from "./services"
13
+
14
+ /**
15
+ * A synced saved block in a document (EditorCustomBlocks; E.21, E.38): drawn
16
+ * from the library, so editing the original reaches every document that uses
17
+ * it. It shows a light outline in the main colour and, when selected or
18
+ * hovered, its source label: the name, "Synced · used in 12 documents" and
19
+ * Detach, which turns it into ordinary blocks changed here only.
20
+ */
21
+ export function SavedBlockView(props: ReactNodeViewProps) {
22
+ const { services, labels } = useEditorServices()
23
+ const id = String(props.node.attrs.savedBlockId ?? "")
24
+ const saved = services.savedBlocks?.find((b) => b.id === id) ?? null
25
+ const editable = props.editor.isEditable
26
+ const overrides = (props.node.attrs.overrides ?? {}) as Partial<Record<string, Inline[]>>
27
+
28
+ const detach = () => {
29
+ const pos = props.getPos()
30
+ if (!saved || typeof pos !== "number") return
31
+ // What this document filled in stays; the rest is the library's as it is now.
32
+ props.editor
33
+ .chain()
34
+ .focus()
35
+ .insertContentAt({ from: pos, to: pos + props.node.nodeSize }, freshEditorBlocks(applyOverrides(saved.blocks, overrides)))
36
+ .run()
37
+ }
38
+
39
+ /** E.23a: this document's own text for one part, by its key; empty goes back to the original's. */
40
+ const fillPart = (segment: Extract<Segment, { part: string }>, text: string) => {
41
+ const next = { ...overrides }
42
+ delete next[segment.legacy] // a value under the pre-3.4 name moves to the key
43
+ if (text) next[segment.part] = [{ type: "text", text }]
44
+ else delete next[segment.part]
45
+ props.updateAttributes({ overrides: next })
46
+ }
47
+
48
+ const line = (blockId: string, content: Inline[]) =>
49
+ segments(blockId, content).map((s, i) =>
50
+ s.part === null ? (
51
+ <React.Fragment key={i}>{inlineText(s.runs)}</React.Fragment>
52
+ ) : (
53
+ <PartField key={s.part} original={partText(s.runs)} value={inlineText(lookupPart(overrides, s) ?? [])} editable={editable} labels={labels} onChange={(text) => fillPart(s, text)} />
54
+ )
55
+ )
56
+
57
+ const usedIn = saved?.usedIn ?? 0
58
+ return (
59
+ <NodeViewWrapper
60
+ data-type="savedBlock"
61
+ data-block-id={props.node.attrs.id ?? undefined}
62
+ className={cn("wy-rich wy-saved", props.selected && "is-selected")}
63
+ role="group"
64
+ aria-label={fill(labels.savedBlockLabel, { name: saved?.name ?? "" })}
65
+ >
66
+ {saved && (
67
+ <div className="wy-saved-src" contentEditable={false}>
68
+ <Icon name="sync" size={12} />
69
+ <b dir="auto">{saved.name}</b>
70
+ <span>
71
+ {labels.savedBlockSynced} · {usedIn === 1 ? labels.savedBlockUsedInOne : fill(labels.savedBlockUsedIn, { n: usedIn })}
72
+ </span>
73
+ {editable && (
74
+ <>
75
+ <span className="wy-saved-sep" aria-hidden="true" />
76
+ <button
77
+ type="button"
78
+ className="wy-saved-action"
79
+ title={labels.savedBlockDetachHint}
80
+ onMouseDown={(e) => e.preventDefault()}
81
+ onClick={detach}
82
+ >
83
+ {labels.savedBlockDetach}
84
+ </button>
85
+ </>
86
+ )}
87
+ </div>
88
+ )}
89
+ <div className="wy-saved-body" contentEditable={false}>
90
+ {saved ? <SavedBlocksPreview blocks={saved.blocks} labels={labels} line={line} /> : <div className="wy-placeholder">{labels.savedBlockMissing}</div>}
91
+ </div>
92
+ </NodeViewWrapper>
93
+ )
94
+ }
95
+
96
+ /** A block type's name for what the preview can't draw as text. */
97
+ const TYPE_NAMES: Partial<Record<Block["type"], keyof EditorLabels>> = {
98
+ table: "blockTable",
99
+ image: "blockImage",
100
+ file: "blockFile",
101
+ record: "blockRecord",
102
+ chart: "blockChart",
103
+ signature: "blockSignature",
104
+ barcode: "blockBarcode",
105
+ qr: "blockQr",
106
+ math: "blockMath",
107
+ pageBreak: "blockPageBreak",
108
+ columns: "blockColumns",
109
+ }
110
+
111
+ /**
112
+ * The library's blocks, read-only, with the sheet's own type: text as text,
113
+ * other blocks named. The saved block is edited in the original, not here.
114
+ */
115
+ function SavedBlocksPreview({ blocks, labels, line }: { blocks: Block[]; labels: EditorLabels; line: (blockId: string, content: Inline[]) => React.ReactNode }) {
116
+ return (
117
+ <>
118
+ {blocks.map((block) => {
119
+ switch (block.type) {
120
+ case "heading": {
121
+ const H = `h${block.level + 1}` as "h2" | "h3" | "h4"
122
+ return <H key={block.id}>{line(block.id, block.content)}</H>
123
+ }
124
+ case "paragraph":
125
+ return <p key={block.id}>{line(block.id, block.content)}</p>
126
+ case "quote":
127
+ return <blockquote key={block.id}>{line(block.id, block.content)}</blockquote>
128
+ case "callout":
129
+ return (
130
+ <div key={block.id} className="wy-saved-callout" data-kind={block.kind}>
131
+ <Icon name={block.kind === "important" ? "alert" : "info"} className="wy-callout-icon" />
132
+ <p>{line(block.id, block.content)}</p>
133
+ </div>
134
+ )
135
+ case "bullet":
136
+ case "number":
137
+ case "checklist":
138
+ return (
139
+ <p key={block.id} style={{ paddingInlineStart: `${(block.level + 1) * 1.25}em` }}>
140
+ {block.type === "checklist" ? (block.checked ? "☑ " : "☐ ") : block.type === "bullet" ? "• " : ""}
141
+ {line(block.id, block.content)}
142
+ </p>
143
+ )
144
+ case "code":
145
+ return <pre key={block.id}>{block.text}</pre>
146
+ case "divider":
147
+ return <hr key={block.id} />
148
+ case "toggle":
149
+ return (
150
+ <React.Fragment key={block.id}>
151
+ <p>{inlineText(block.summary)}</p>
152
+ <SavedBlocksPreview blocks={block.children} labels={labels} line={line} />
153
+ </React.Fragment>
154
+ )
155
+ default: {
156
+ const name = TYPE_NAMES[block.type]
157
+ return (
158
+ <div key={block.id} className="wy-placeholder">
159
+ {name ? labels[name] : block.type}
160
+ </div>
161
+ )
162
+ }
163
+ }
164
+ })}
165
+ </>
166
+ )
167
+ }
168
+
169
+ /**
170
+ * One per-document part (E.23): a field this document fills, showing the
171
+ * original's text until it does. Read-only, it shows what will print.
172
+ */
173
+ function PartField({
174
+ original,
175
+ value,
176
+ editable,
177
+ labels,
178
+ onChange,
179
+ }: {
180
+ original: string
181
+ value: string
182
+ editable: boolean
183
+ labels: EditorLabels
184
+ onChange: (text: string) => void
185
+ }) {
186
+ const [draft, setDraft] = React.useState(value)
187
+ React.useEffect(() => setDraft(value), [value])
188
+ if (!editable) return <span className="wy-part">{value || original}</span>
189
+ return (
190
+ <input
191
+ className="wy-part"
192
+ dir="auto"
193
+ value={draft}
194
+ placeholder={original}
195
+ size={Math.max(4, (draft || original).length)}
196
+ aria-label={fill(labels.perDocumentFill, { text: original })}
197
+ onChange={(e) => setDraft(e.target.value)}
198
+ onBlur={() => draft !== value && onChange(draft.trim())}
199
+ onKeyDown={(e) => {
200
+ if (e.key === "Enter") (e.target as HTMLInputElement).blur()
201
+ if (e.key === "Escape") setDraft(value)
202
+ }}
203
+ />
204
+ )
205
+ }
@@ -0,0 +1,105 @@
1
+ import type { Meta, StoryObj } from "@storybook/react-vite"
2
+ import * as React from "react"
3
+
4
+ import type { SavedBlock, WhityDocument } from "./contract"
5
+ import { DocEditor } from "./doc-editor"
6
+ import { EDITOR_LABELS } from "./labels"
7
+ import { SAMPLE_DOCUMENT } from "./sample"
8
+ import { SaveBlockDialog } from "./save-block-dialog"
9
+ import type { EditorServices } from "./services"
10
+
11
+ /**
12
+ * Editor M7, the saved blocks half of the EditorCustomBlocks card: a synced
13
+ * block in a document with its label ("Bank details · Synced · used in 12
14
+ * documents", Detach), the / menu's Saved blocks group, and Save as block.
15
+ */
16
+ const meta = {
17
+ title: "Editor/Saved blocks",
18
+ parameters: { layout: "fullscreen", fullBleed: true },
19
+ } satisfies Meta
20
+
21
+ export default meta
22
+ type Story = StoryObj<typeof meta>
23
+
24
+ const t = (text: string) => ({ type: "text" as const, text })
25
+
26
+ const BANK: SavedBlock = {
27
+ id: "5",
28
+ name: "Bank details",
29
+ mode: "synced",
30
+ sharing: "workspace",
31
+ owner: { kind: "person", id: "1", name: "Amro Saleh" },
32
+ blocks: [
33
+ { id: "s1", type: "heading", level: 3, content: [t("Bank details")] },
34
+ { id: "s2", type: "callout", kind: "note", content: [t("Example Bank, Mecca Street branch · IBAN JO71 EXBK 0000 0000 0000 1234 5678 90 · SWIFT EXBKJOAM")] },
35
+ ],
36
+ perDocumentParts: [],
37
+ version: 3,
38
+ usedIn: 12,
39
+ }
40
+ const TERMS: SavedBlock = {
41
+ ...BANK,
42
+ id: "6",
43
+ name: "Payment terms",
44
+ mode: "copy",
45
+ sharing: "me",
46
+ blocks: [{ id: "c1", type: "paragraph", content: [t("Please pay within 30 days of the invoice date.")] }],
47
+ usedIn: 0,
48
+ }
49
+
50
+ const SIGN: SavedBlock = {
51
+ ...BANK,
52
+ id: "7",
53
+ name: "Signature line",
54
+ blocks: [
55
+ {
56
+ id: "g1",
57
+ type: "paragraph",
58
+ content: [t("Signed by "), { type: "text", text: "Amro Saleh", marks: [{ type: "perDocument", key: "pd_signer01" }] }, t(" on "), { type: "text", text: "12 November 2026", marks: [{ type: "perDocument", key: "pd_signdate" }] }],
59
+ },
60
+ ],
61
+ perDocumentParts: [
62
+ { key: "pd_signer01", label: { en: "Signer's name", ar: "اسم الموقّع" }, kind: "text" },
63
+ { key: "pd_signdate", label: { en: "Date", ar: "التاريخ" }, kind: "text" },
64
+ ],
65
+ usedIn: 4,
66
+ }
67
+
68
+ const SERVICES: EditorServices = {
69
+ savedBlocks: [BANK, TERMS, SIGN],
70
+ saveBlock: async (b) => ({ ...b, id: "9", owner: BANK.owner, version: 1, usedIn: 0 }),
71
+ canShareSavedBlocks: true,
72
+ }
73
+
74
+ const DOC: WhityDocument = {
75
+ ...SAMPLE_DOCUMENT,
76
+ title: "Invoice letter",
77
+ blocks: [
78
+ { id: "p1", type: "paragraph", content: [t("Thank you for your order from Example Bakery. Please transfer the amount due to:")] },
79
+ { id: "r1", type: "savedBlock", savedBlockId: "5", version: 3, overrides: {} },
80
+ { id: "p2", type: "paragraph", content: [t("Questions? Reply to this letter or call us.")] },
81
+ { id: "r2", type: "savedBlock", savedBlockId: "7", version: 1, overrides: { "g1#0": [t("Awss Haddad")] } },
82
+ ],
83
+ }
84
+
85
+ function Editor({ lang }: { lang?: "ar" }) {
86
+ const [doc, setDoc] = React.useState<WhityDocument>(
87
+ lang === "ar"
88
+ ? { ...DOC, lang: "ar", title: "رسالة الفاتورة", blocks: [{ id: "p1", type: "paragraph", content: [t("شكرًا لطلبك من Example Bakery. يرجى تحويل المبلغ المستحق إلى:")] }, DOC.blocks[1]] }
89
+ : DOC
90
+ )
91
+ return (
92
+ <div dir={lang === "ar" ? "rtl" : undefined} lang={lang} className="h-screen">
93
+ <DocEditor document={doc} onChange={setDoc} canEdit services={SERVICES} />
94
+ </div>
95
+ )
96
+ }
97
+
98
+ /** Hover or select the synced block to see its label and Detach; type / to see the Saved blocks group. */
99
+ export const SyncedInADocument: Story = { render: () => <Editor /> }
100
+
101
+ export const Arabic: Story = { render: () => <Editor lang="ar" /> }
102
+
103
+ export const SaveAsBlock: Story = {
104
+ render: () => <SaveBlockDialog open onOpenChange={() => undefined} blockCount={2} canShare onSave={async () => undefined} labels={EDITOR_LABELS} />,
105
+ }
@@ -0,0 +1,192 @@
1
+ import type { Block, Inline, PerDocumentKey, PerDocumentPart } from "./contract"
2
+
3
+ /**
4
+ * Per-document parts of a synced saved block (E.23, E.23a). In the original,
5
+ * text carries the `perDocument` mark and a merge field sets `perDocument`.
6
+ * Since design 3.4 each part has a stable key, `pd_` + 8 characters, minted
7
+ * once when the creator marks it and kept through edits, moves and
8
+ * translation; adjacent runs with the same key are one part, and a
9
+ * document's `overrides` fill parts by key.
10
+ *
11
+ * Rows from before 3.4 carry no key: each run of consecutive marked text and
12
+ * fields in a block's line is one part, named by where it sits,
13
+ * `<block id>#<n>`. That name (`legacy`) is still worked out for every part,
14
+ * so a value stored under it keeps filling the same part. Migration 270
15
+ * gave stored rows their keys; Whity's printer (SavedBlockExpander,
16
+ * PerDocumentParts) finds parts the same way.
17
+ */
18
+
19
+ export type Segment = { part: null; runs: Inline[] } | { part: PerDocumentKey; legacy: string; runs: Inline[] }
20
+
21
+ /** The blocks whose `content` holds a line of text (and so can hold a part). */
22
+ const TEXT_TYPES = new Set(["paragraph", "heading", "quote", "bullet", "number", "checklist", "callout"])
23
+
24
+ const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
25
+
26
+ /** A fresh part key: `pd_` + 8 characters of a nanoid alphabet (E.23a). */
27
+ export function mintPartKey(): PerDocumentKey {
28
+ const bytes = new Uint8Array(8)
29
+ crypto.getRandomValues(bytes)
30
+ return "pd_" + Array.from(bytes, (b) => ALPHABET[b & 63]).join("")
31
+ }
32
+
33
+ /** The part a run belongs to: null when it isn't one, "" for a part with no key yet, else its key. */
34
+ export function partKeyOf(run: Inline): string | null {
35
+ // Rows from before 3.4 have the mark without a key.
36
+ const mark = (run.type === "text" || run.type === "field" ? run.marks?.find((m) => m.type === "perDocument") : undefined) as { key?: unknown } | undefined
37
+ const markKey = mark ? (typeof mark.key === "string" && mark.key ? mark.key : "") : null
38
+ if (run.type === "text") return markKey
39
+ if (run.type === "field") {
40
+ const own = run.perDocument as unknown
41
+ if (typeof own === "string" && own) return own
42
+ if (own === true) return markKey ?? ""
43
+ return markKey
44
+ }
45
+ return null
46
+ }
47
+
48
+ export function isPerDocument(run: Inline): boolean {
49
+ return partKeyOf(run) !== null
50
+ }
51
+
52
+ /** A block's line split into plain runs and parts, in order. */
53
+ export function segments(blockId: string, content: Inline[]): Segment[] {
54
+ const out: Segment[] = []
55
+ let n = 0
56
+ let current: string | null = null
57
+ for (const run of content) {
58
+ const key = partKeyOf(run)
59
+ const last = out[out.length - 1]
60
+ if (last && key === current && (key !== null || last.part === null)) {
61
+ last.runs.push(run)
62
+ } else if (key === null) {
63
+ out.push({ part: null, runs: [run] })
64
+ } else {
65
+ const legacy = `${blockId}#${n++}`
66
+ out.push({ part: key || legacy, legacy, runs: [run] })
67
+ }
68
+ current = key
69
+ }
70
+ return out
71
+ }
72
+
73
+ /** What a document holds for a part: by its key, then by its pre-3.4 name. Undefined when nothing. */
74
+ export function lookupPart(overrides: Partial<Record<string, Inline[]>>, segment: Segment): Inline[] | undefined {
75
+ if (segment.part === null) return undefined
76
+ for (const name of [segment.part, segment.legacy]) {
77
+ const value = overrides[name]
78
+ if (value && value.length) return value
79
+ }
80
+ return undefined
81
+ }
82
+
83
+ function textContent(block: Block): Inline[] | null {
84
+ return TEXT_TYPES.has(block.type) && "content" in block && Array.isArray(block.content) ? (block.content as Inline[]) : null
85
+ }
86
+
87
+ function collect(blocks: Block[], found: Map<string, Inline[]>): void {
88
+ for (const block of blocks) {
89
+ const content = textContent(block)
90
+ if (content) for (const s of segments(block.id, content)) if (s.part !== null) found.set(s.part, [...(found.get(s.part) ?? []), ...s.runs])
91
+ if (block.type === "toggle") collect(block.children, found)
92
+ if (block.type === "columns") {
93
+ collect(block.columns[0], found)
94
+ collect(block.columns[1], found)
95
+ }
96
+ }
97
+ }
98
+
99
+ /** Every part's key in a saved block's blocks, in reading order, nested toggles and columns included. */
100
+ export function perDocumentKeys(blocks: Block[]): PerDocumentKey[] {
101
+ const found = new Map<string, Inline[]>()
102
+ collect(blocks, found)
103
+ return [...found.keys()]
104
+ }
105
+
106
+ /**
107
+ * The parts in reading order, each once, keeping what `previous` gave each key
108
+ * (label, required, placeholder). A new part is labelled with its own text.
109
+ */
110
+ export function perDocumentParts(blocks: Block[], previous: PerDocumentPart[] = []): PerDocumentPart[] {
111
+ const found = new Map<string, Inline[]>()
112
+ collect(blocks, found)
113
+ const before = new Map(previous.map((p) => [p.key, p]))
114
+ return [...found].map(([key, runs]) => {
115
+ const kind: PerDocumentPart["kind"] = runs.every((r) => r.type === "field") ? "field" : "text"
116
+ const old = before.get(key)
117
+ const text = partText(runs).replace(/\s+/g, " ").trim().slice(0, 120)
118
+ return { ...old, key, kind, label: old?.label?.en ? old.label : { en: text || key } }
119
+ })
120
+ }
121
+
122
+ /** The run with its part's key written on its mark (and on a field's `perDocument`). */
123
+ function withKey(run: Inline, key: PerDocumentKey): Inline {
124
+ if (run.type !== "text" && run.type !== "field") return run
125
+ const out = { ...run } as typeof run
126
+ if (run.marks) out.marks = run.marks.map((m) => (m.type === "perDocument" ? { type: "perDocument", key } : m)) as typeof run.marks
127
+ if (out.type === "field" && out.perDocument !== undefined) out.perDocument = key
128
+ return out
129
+ }
130
+
131
+ /**
132
+ * Gives every part that has no key one (E.23a). `map` takes each part's
133
+ * pre-3.4 name to its key, reused when present and filled in for every part.
134
+ */
135
+ export function assignPartKeys(blocks: Block[], map: Map<string, PerDocumentKey> = new Map()): Block[] {
136
+ return blocks.map((block) => {
137
+ const content = textContent(block)
138
+ let next: Block = block
139
+ if (content) {
140
+ const runs = segments(block.id, content).flatMap((s) => {
141
+ if (s.part === null) return s.runs
142
+ if (s.part !== s.legacy) {
143
+ if (!map.has(s.legacy)) map.set(s.legacy, s.part)
144
+ return s.runs
145
+ }
146
+ const key = map.get(s.legacy) ?? mintPartKey()
147
+ map.set(s.legacy, key)
148
+ return s.runs.map((r) => withKey(r, key))
149
+ })
150
+ next = { ...block, content: runs } as Block
151
+ }
152
+ if (next.type === "toggle") next = { ...next, children: assignPartKeys(next.children, map) }
153
+ if (next.type === "columns") next = { ...next, columns: [assignPartKeys(next.columns[0], map), assignPartKeys(next.columns[1], map)] }
154
+ return next
155
+ })
156
+ }
157
+
158
+ /**
159
+ * The blocks with each filled part replaced by the document's own text (and
160
+ * the per-document mark dropped): what Detach leaves in the document.
161
+ */
162
+ export function applyOverrides(blocks: Block[], overrides: Partial<Record<string, Inline[]>>): Block[] {
163
+ return blocks.map((block) => {
164
+ const content = textContent(block)
165
+ let next: Block = block
166
+ if (content) {
167
+ const runs = segments(block.id, content).flatMap((s) => {
168
+ if (s.part === null) return s.runs
169
+ const own = lookupPart(overrides, s) ?? s.runs
170
+ return own.map((r) => (r.type === "text" || r.type === "field" ? unmark(r) : r))
171
+ })
172
+ next = { ...block, content: runs } as Block
173
+ }
174
+ if (next.type === "toggle") next = { ...next, children: applyOverrides(next.children, overrides) }
175
+ if (next.type === "columns") next = { ...next, columns: [applyOverrides(next.columns[0], overrides), applyOverrides(next.columns[1], overrides)] }
176
+ return next
177
+ })
178
+ }
179
+
180
+ function unmark<T extends Inline & { marks?: { type: string }[] }>(run: T): T {
181
+ const marks = run.marks?.filter((m) => m.type !== "perDocument")
182
+ const out = { ...run } as T & { perDocument?: unknown }
183
+ if (marks && marks.length) out.marks = marks as T["marks"]
184
+ else delete out.marks
185
+ if (out.type === "field") delete out.perDocument
186
+ return out
187
+ }
188
+
189
+ /** The plain text a part shows when the document hasn't filled it: the original's. */
190
+ export function partText(runs: Inline[]): string {
191
+ return runs.map((r) => (r.type === "text" ? r.text : r.type === "field" ? r.label || r.path : r.type === "math" ? r.tex : "\n")).join("")
192
+ }