@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
@@ -1,372 +1,372 @@
1
- import { Extension } from "@tiptap/core"
2
- import type { Node as PmNode, Schema } from "@tiptap/pm/model"
3
- import { Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from "@tiptap/pm/state"
4
- import { Decoration, DecorationSet } from "@tiptap/pm/view"
5
-
6
- import type { Block, Mark as DocMark } from "./contract"
7
- import { blockFromPm, blockToPm } from "./convert"
8
- import { suggestEdit, type FormatEdit, type RenderedFormat } from "./suggestions"
9
-
10
- /**
11
- * Suggesting mode and the collaboration decorations (editor M5, E.10, E.39).
12
- *
13
- * While suggesting, every edit is let through and then rewritten by
14
- * `appendTransaction`: the top-level blocks it touched are diffed before and
15
- * after (`suggestEdit`, pure and tested), and replaced with the same change
16
- * expressed as local `insertion` / `deletion` marks and block `suggestion`
17
- * attrs. A formatting change is undone and kept as a pending format edit,
18
- * drawn with a dashed underline. An edit that can't be a suggestion yet is
19
- * undone (and counted in `refused`, so the editor can say so).
20
- *
21
- * The same plugin draws, on screen only (never in the document):
22
- * - comment highlights by matching each open thread's quote within its anchor
23
- * block (warning tint and underline, E.39, not the highlight colour);
24
- * - suggested blocks, dashed (inserted) or struck (deleted);
25
- * - format suggestions, dashed underline.
26
- */
27
-
28
- export const LOCAL_PREFIX = "local-"
29
- let localSeq = 0
30
- export const nextLocalId = () => `${LOCAL_PREFIX}${Date.now().toString(36)}${(localSeq++).toString(36)}`
31
-
32
- /** Pending format edit in document positions. */
33
- interface PmFormat {
34
- id: string
35
- from: number
36
- to: number
37
- mark: DocMark
38
- add: boolean
39
- }
40
-
41
- export interface CollabThreadAnchor {
42
- id: string
43
- blockId: string
44
- quote: string
45
- }
46
-
47
- interface SuggestingState {
48
- enabled: boolean
49
- formats: PmFormat[]
50
- /** Server format suggestions, by block offsets. */
51
- serverFormats: RenderedFormat[]
52
- threads: CollabThreadAnchor[]
53
- active: string | null
54
- /** How many edits were refused since the plugin started (the editor shows a note when it grows). */
55
- refused: number
56
- }
57
-
58
- export type SuggestingMeta =
59
- | { enabled: boolean }
60
- | { skip: true }
61
- | { addFormats: PmFormat[] }
62
- | { dropFormats: string[] }
63
- | { renameFormat: { from: string; to: string } }
64
- | { serverFormats: RenderedFormat[] }
65
- | { threads: CollabThreadAnchor[] }
66
- | { active: string | null }
67
- | { refused: true }
68
-
69
- export const suggestingKey = new PluginKey<SuggestingState>("suggesting")
70
-
71
- export interface SuggestingOptions {
72
- /** Whether an id is one of this person's pending, unsent changes. */
73
- isLocal: (id: string) => boolean
74
- /** A click on a highlight or a suggestion: the card to make active. */
75
- onActivate: (id: string | null) => void
76
- }
77
-
78
- /** The node and position of a block by id, nested blocks included. */
79
- export function findBlockNode(doc: PmNode, id: string): { node: PmNode; pos: number } | null {
80
- let found: { node: PmNode; pos: number } | null = null
81
- doc.descendants((node, pos) => {
82
- if (found) return false
83
- if (node.attrs.id === id) {
84
- found = { node, pos }
85
- return false
86
- }
87
- return true
88
- })
89
- return found
90
- }
91
-
92
- /** A textblock's text as patches and quotes count it (one character per inline atom). */
93
- export function blockTextOf(node: PmNode): string {
94
- return node.textBetween(0, node.content.size, undefined, "\uFFFC")
95
- }
96
-
97
- /** Where an open thread's quote is, in document positions. */
98
- export function threadRange(doc: PmNode, t: CollabThreadAnchor): { from: number; to: number } | null {
99
- if (!t.quote) return null
100
- const at = findBlockNode(doc, t.blockId)
101
- if (!at || !at.node.isTextblock) return null
102
- const index = blockTextOf(at.node).indexOf(t.quote)
103
- if (index < 0) return null
104
- return { from: at.pos + 1 + index, to: at.pos + 1 + index + t.quote.length }
105
- }
106
-
107
- /** Where a suggestion shows: its first marked text or suggested block. */
108
- export function suggestionPos(doc: PmNode, id: string, formats: RenderedFormat[] = []): number | null {
109
- let at: number | null = null
110
- doc.descendants((node, pos) => {
111
- if (at !== null) return false
112
- if (node.attrs.suggestion?.id === id) {
113
- at = pos
114
- return false
115
- }
116
- if (node.isText && node.marks.some((m) => (m.type.name === "insertion" || m.type.name === "deletion") && m.attrs.suggestionId === id)) {
117
- at = pos
118
- return false
119
- }
120
- return true
121
- })
122
- if (at !== null) return at
123
- const f = formats.find((x) => x.suggestionId === id)
124
- const b = f && findBlockNode(doc, f.blockId)
125
- return b ? b.pos + 1 + f!.from : null
126
- }
127
-
128
- function caretOf(state: EditorState): { blockId: string; offset: number } | null {
129
- const sel = state.selection
130
- if (!sel.empty) return null
131
- const parent = sel.$from.parent
132
- const id = parent.attrs.id as string | null
133
- return id ? { blockId: id, offset: sel.$from.parentOffset } : null
134
- }
135
-
136
- const toBlocks = (nodes: PmNode[]): Block[] => nodes.map((n) => blockFromPm(n.toJSON())).filter((b): b is Block => b !== null)
137
-
138
- /**
139
- * The Suggesting-mode rewrite of one or more transactions (exported for tests).
140
- * Returns the transaction to append, or null when there is nothing to do.
141
- */
142
- export function suggestTransaction(
143
- trs: readonly Transaction[],
144
- oldState: EditorState,
145
- newState: EditorState,
146
- isLocal: (id: string) => boolean
147
- ): Transaction | null {
148
- const st = suggestingKey.getState(newState)
149
- const edits = trs.filter((t) => t.docChanged && !t.getMeta(suggestingKey) && !t.getMeta("history$") && !t.getMeta("appendedTransaction"))
150
- if (!edits.length) return null
151
- // Editing: typed or pasted text is plain draft text, never part of a suggestion around it.
152
- if (!st?.enabled) return stripInsertedSuggestionMarks(trs, newState)
153
-
154
- const a = oldState.doc
155
- const b = newState.doc
156
- let i = 0
157
- while (i < a.childCount && i < b.childCount && a.child(i).eq(b.child(i))) i++
158
- let j = 0
159
- while (j < a.childCount - i && j < b.childCount - i && a.child(a.childCount - 1 - j).eq(b.child(b.childCount - 1 - j))) j++
160
- const oldNodes: PmNode[] = []
161
- const newNodes: PmNode[] = []
162
- for (let k = i; k < a.childCount - j; k++) oldNodes.push(a.child(k))
163
- for (let k = i; k < b.childCount - j; k++) newNodes.push(b.child(k))
164
- let start = 0
165
- for (let k = 0; k < i; k++) start += b.child(k).nodeSize
166
- const newEnd = start + newNodes.reduce((n, node) => n + node.nodeSize, 0)
167
-
168
- const result = suggestEdit(toBlocks(oldNodes), toBlocks(newNodes), {
169
- localId: nextLocalId(),
170
- isLocal,
171
- caretBefore: oldState.selection.empty ? caretOf(oldState) : selectionEnd(oldState),
172
- caretAfter: caretOf(newState),
173
- })
174
-
175
- const tr = newState.tr
176
- const schema: Schema = newState.schema
177
- if (!result) {
178
- // Not expressible as a suggestion yet: put the touched blocks back as they were.
179
- tr.replaceWith(start, newEnd, oldNodes)
180
- tr.setSelection(oldState.selection.getBookmark().resolve(tr.doc))
181
- tr.setMeta(suggestingKey, { refused: true } satisfies SuggestingMeta)
182
- return tr.setMeta("addToHistory", false)
183
- }
184
- const nodes = result.blocks.map((block) => schema.nodeFromJSON(blockToPm(block)))
185
- const same = nodes.length === newNodes.length && nodes.every((n, k) => n.eq(newNodes[k]))
186
- if (same && !result.formats.length) return null
187
- if (!same) tr.replaceWith(start, newEnd, nodes)
188
- tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
189
- if (!newState.selection.empty && tr.doc.content.size === newState.doc.content.size) {
190
- // A formatting change keeps its selection.
191
- tr.setSelection(TextSelection.create(tr.doc, newState.selection.from, newState.selection.to))
192
- } else if (result.caret) {
193
- const at = findBlockNode(tr.doc, result.caret.blockId)
194
- if (at) {
195
- const pos = Math.min(at.pos + 1 + result.caret.offset, at.pos + at.node.nodeSize - 1)
196
- tr.setSelection(TextSelection.create(tr.doc, pos))
197
- }
198
- }
199
- if (result.formats.length) {
200
- const formats = result.formats
201
- .map((f: FormatEdit) => {
202
- const at = findBlockNode(tr.doc, f.blockId)
203
- return at ? { id: f.id, from: at.pos + 1 + f.from, to: at.pos + 1 + f.to, mark: f.mark, add: f.add } : null
204
- })
205
- .filter((f): f is PmFormat => f !== null)
206
- // A second meta key can't share the plugin key: formats ride on their own.
207
- tr.setMeta(FORMATS_META, formats)
208
- }
209
- return tr
210
- }
211
-
212
- const FORMATS_META = "suggestingFormats"
213
-
214
- /**
215
- * Editing mode: text a transaction inserts must not carry another
216
- * suggestion's `insertion` or `deletion` mark. Typed inside a suggested
217
- * insertion, it would inherit the mark, and saving (which strips suggested
218
- * insertions from the draft) would silently drop it. Undo/redo, the editor's
219
- * own redraws and appended transactions keep their marks.
220
- */
221
- export function stripInsertedSuggestionMarks(trs: readonly Transaction[], state: EditorState): Transaction | null {
222
- const ranges: { from: number; to: number }[] = []
223
- trs.forEach((t, ti) => {
224
- if (!t.docChanged || t.getMeta(suggestingKey) || t.getMeta("history$") || t.getMeta("appendedTransaction")) return
225
- t.mapping.maps.forEach((map, i) => {
226
- map.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
227
- if (newEnd <= newStart) return
228
- // Into this transaction's final document, then through the transactions after it.
229
- let from = t.mapping.slice(i + 1).map(newStart, 1)
230
- let to = t.mapping.slice(i + 1).map(newEnd, -1)
231
- for (const later of trs.slice(ti + 1)) {
232
- from = later.mapping.map(from, 1)
233
- to = later.mapping.map(to, -1)
234
- }
235
- if (to > from) ranges.push({ from, to })
236
- })
237
- })
238
- })
239
- if (!ranges.length) return null
240
- const { insertion, deletion } = state.schema.marks
241
- const tr = state.tr
242
- for (const { from, to } of ranges) {
243
- let marked = false
244
- state.doc.nodesBetween(from, to, (node) => {
245
- if (node.isInline && node.marks.some((m) => m.type === insertion || m.type === deletion)) marked = true
246
- return !marked
247
- })
248
- if (!marked) continue
249
- if (insertion) tr.removeMark(from, to, insertion)
250
- if (deletion) tr.removeMark(from, to, deletion)
251
- }
252
- if (!tr.docChanged) return null
253
- return tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
254
- }
255
-
256
- function selectionEnd(state: EditorState): { blockId: string; offset: number } | null {
257
- const $to = state.selection.$to
258
- const id = $to.parent.attrs.id as string | null
259
- return id ? { blockId: id, offset: $to.parentOffset } : null
260
- }
261
-
262
- /** Pending format edits as block offsets, for the flush. */
263
- export function pendingFormats(state: EditorState): FormatEdit[] {
264
- const st = suggestingKey.getState(state)
265
- if (!st) return []
266
- const out: FormatEdit[] = []
267
- for (const f of st.formats) {
268
- const $from = state.doc.resolve(f.from)
269
- const id = $from.parent.attrs.id as string | null
270
- if (!id || f.to <= f.from) continue
271
- const start = $from.start()
272
- out.push({ id: f.id, blockId: id, from: f.from - start, to: Math.min(f.to, $from.end()) - start, mark: f.mark, add: f.add })
273
- }
274
- return out
275
- }
276
-
277
- /** Swaps a local suggestion id for the server's in marks and block attrs. */
278
- export function renameSuggestion(state: EditorState, from: string, to: string): Transaction {
279
- const tr = state.tr
280
- state.doc.descendants((node, pos) => {
281
- if (node.attrs.suggestion?.id === from) tr.setNodeMarkup(pos, undefined, { ...node.attrs, suggestion: { ...node.attrs.suggestion, id: to } })
282
- if (node.isText) {
283
- for (const m of node.marks) {
284
- if ((m.type.name === "insertion" || m.type.name === "deletion") && m.attrs.suggestionId === from) {
285
- tr.removeMark(pos, pos + node.nodeSize, m)
286
- tr.addMark(pos, pos + node.nodeSize, m.type.create({ suggestionId: to }))
287
- }
288
- }
289
- }
290
- return true
291
- })
292
- tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
293
- tr.setMeta("addToHistory", false)
294
- return tr
295
- }
296
-
297
- export const Suggesting = Extension.create<SuggestingOptions>({
298
- name: "suggesting",
299
- // After BlockIds, so a new block already has its id when the edit is rewritten.
300
- priority: 10,
301
- addOptions() {
302
- return { isLocal: (id: string) => id.startsWith(LOCAL_PREFIX), onActivate: () => {} }
303
- },
304
- addProseMirrorPlugins() {
305
- const options = this.options
306
- return [
307
- new Plugin<SuggestingState>({
308
- key: suggestingKey,
309
- state: {
310
- init: () => ({ enabled: false, formats: [], serverFormats: [], threads: [], active: null, refused: 0 }),
311
- apply(tr, prev) {
312
- let next = prev
313
- if (tr.docChanged && prev.formats.length) {
314
- next = {
315
- ...next,
316
- formats: prev.formats
317
- .map((f) => ({ ...f, from: tr.mapping.map(f.from, 1), to: tr.mapping.map(f.to, -1) }))
318
- .filter((f) => f.to > f.from),
319
- }
320
- }
321
- const added = tr.getMeta(FORMATS_META) as PmFormat[] | undefined
322
- if (added) next = { ...next, formats: [...next.formats, ...added] }
323
- const meta = tr.getMeta(suggestingKey) as SuggestingMeta | undefined
324
- if (!meta) return next
325
- if ("enabled" in meta) return { ...next, enabled: meta.enabled }
326
- if ("dropFormats" in meta) return { ...next, formats: next.formats.filter((f) => !meta.dropFormats.includes(f.id)) }
327
- if ("serverFormats" in meta) return { ...next, serverFormats: meta.serverFormats }
328
- if ("threads" in meta) return { ...next, threads: meta.threads }
329
- if ("active" in meta) return { ...next, active: meta.active }
330
- if ("refused" in meta) return { ...next, refused: next.refused + 1 }
331
- return next
332
- },
333
- },
334
- appendTransaction: (trs, oldState, newState) => suggestTransaction(trs, oldState, newState, options.isLocal),
335
- props: {
336
- decorations(state) {
337
- const st = suggestingKey.getState(state)
338
- if (!st) return null
339
- const decos: Decoration[] = []
340
- for (const t of st.threads) {
341
- const r = threadRange(state.doc, t)
342
- if (r) decos.push(Decoration.inline(r.from, r.to, { class: `wy-cmt${st.active === t.id ? " is-active" : ""}`, "data-thread": t.id }))
343
- }
344
- state.doc.descendants((node, pos) => {
345
- const s = node.attrs.suggestion as { id: string; action: string } | null | undefined
346
- if (s) {
347
- decos.push(
348
- Decoration.node(pos, pos + node.nodeSize, {
349
- class: `wy-sug-block is-${s.action}${st.active === s.id ? " is-active" : ""}`,
350
- "data-suggestion": s.id,
351
- })
352
- )
353
- }
354
- return true
355
- })
356
- for (const f of st.serverFormats) {
357
- const at = findBlockNode(state.doc, f.blockId)
358
- if (at) decos.push(Decoration.inline(at.pos + 1 + f.from, at.pos + 1 + f.to, { class: "wy-sug-fmt", "data-suggestion": f.suggestionId }))
359
- }
360
- for (const f of st.formats) decos.push(Decoration.inline(f.from, f.to, { class: "wy-sug-fmt is-pending" }))
361
- return DecorationSet.create(state.doc, decos)
362
- },
363
- handleClick(_view, _pos, event) {
364
- const el = (event.target as HTMLElement | null)?.closest?.("[data-thread],[data-suggestion]") as HTMLElement | null
365
- options.onActivate(el ? (el.dataset.thread ?? el.dataset.suggestion ?? null) : null)
366
- return false
367
- },
368
- },
369
- }),
370
- ]
371
- },
372
- })
1
+ import { Extension } from "@tiptap/core"
2
+ import type { Node as PmNode, Schema } from "@tiptap/pm/model"
3
+ import { Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from "@tiptap/pm/state"
4
+ import { Decoration, DecorationSet } from "@tiptap/pm/view"
5
+
6
+ import type { Block, Mark as DocMark } from "./contract"
7
+ import { blockFromPm, blockToPm } from "./convert"
8
+ import { suggestEdit, type FormatEdit, type RenderedFormat } from "./suggestions"
9
+
10
+ /**
11
+ * Suggesting mode and the collaboration decorations (editor M5, E.10, E.39).
12
+ *
13
+ * While suggesting, every edit is let through and then rewritten by
14
+ * `appendTransaction`: the top-level blocks it touched are diffed before and
15
+ * after (`suggestEdit`, pure and tested), and replaced with the same change
16
+ * expressed as local `insertion` / `deletion` marks and block `suggestion`
17
+ * attrs. A formatting change is undone and kept as a pending format edit,
18
+ * drawn with a dashed underline. An edit that can't be a suggestion yet is
19
+ * undone (and counted in `refused`, so the editor can say so).
20
+ *
21
+ * The same plugin draws, on screen only (never in the document):
22
+ * - comment highlights by matching each open thread's quote within its anchor
23
+ * block (warning tint and underline, E.39, not the highlight colour);
24
+ * - suggested blocks, dashed (inserted) or struck (deleted);
25
+ * - format suggestions, dashed underline.
26
+ */
27
+
28
+ export const LOCAL_PREFIX = "local-"
29
+ let localSeq = 0
30
+ export const nextLocalId = () => `${LOCAL_PREFIX}${Date.now().toString(36)}${(localSeq++).toString(36)}`
31
+
32
+ /** Pending format edit in document positions. */
33
+ interface PmFormat {
34
+ id: string
35
+ from: number
36
+ to: number
37
+ mark: DocMark
38
+ add: boolean
39
+ }
40
+
41
+ export interface CollabThreadAnchor {
42
+ id: string
43
+ blockId: string
44
+ quote: string
45
+ }
46
+
47
+ interface SuggestingState {
48
+ enabled: boolean
49
+ formats: PmFormat[]
50
+ /** Server format suggestions, by block offsets. */
51
+ serverFormats: RenderedFormat[]
52
+ threads: CollabThreadAnchor[]
53
+ active: string | null
54
+ /** How many edits were refused since the plugin started (the editor shows a note when it grows). */
55
+ refused: number
56
+ }
57
+
58
+ export type SuggestingMeta =
59
+ | { enabled: boolean }
60
+ | { skip: true }
61
+ | { addFormats: PmFormat[] }
62
+ | { dropFormats: string[] }
63
+ | { renameFormat: { from: string; to: string } }
64
+ | { serverFormats: RenderedFormat[] }
65
+ | { threads: CollabThreadAnchor[] }
66
+ | { active: string | null }
67
+ | { refused: true }
68
+
69
+ export const suggestingKey = new PluginKey<SuggestingState>("suggesting")
70
+
71
+ export interface SuggestingOptions {
72
+ /** Whether an id is one of this person's pending, unsent changes. */
73
+ isLocal: (id: string) => boolean
74
+ /** A click on a highlight or a suggestion: the card to make active. */
75
+ onActivate: (id: string | null) => void
76
+ }
77
+
78
+ /** The node and position of a block by id, nested blocks included. */
79
+ export function findBlockNode(doc: PmNode, id: string): { node: PmNode; pos: number } | null {
80
+ let found: { node: PmNode; pos: number } | null = null
81
+ doc.descendants((node, pos) => {
82
+ if (found) return false
83
+ if (node.attrs.id === id) {
84
+ found = { node, pos }
85
+ return false
86
+ }
87
+ return true
88
+ })
89
+ return found
90
+ }
91
+
92
+ /** A textblock's text as patches and quotes count it (one character per inline atom). */
93
+ export function blockTextOf(node: PmNode): string {
94
+ return node.textBetween(0, node.content.size, undefined, "\uFFFC")
95
+ }
96
+
97
+ /** Where an open thread's quote is, in document positions. */
98
+ export function threadRange(doc: PmNode, t: CollabThreadAnchor): { from: number; to: number } | null {
99
+ if (!t.quote) return null
100
+ const at = findBlockNode(doc, t.blockId)
101
+ if (!at || !at.node.isTextblock) return null
102
+ const index = blockTextOf(at.node).indexOf(t.quote)
103
+ if (index < 0) return null
104
+ return { from: at.pos + 1 + index, to: at.pos + 1 + index + t.quote.length }
105
+ }
106
+
107
+ /** Where a suggestion shows: its first marked text or suggested block. */
108
+ export function suggestionPos(doc: PmNode, id: string, formats: RenderedFormat[] = []): number | null {
109
+ let at: number | null = null
110
+ doc.descendants((node, pos) => {
111
+ if (at !== null) return false
112
+ if (node.attrs.suggestion?.id === id) {
113
+ at = pos
114
+ return false
115
+ }
116
+ if (node.isText && node.marks.some((m) => (m.type.name === "insertion" || m.type.name === "deletion") && m.attrs.suggestionId === id)) {
117
+ at = pos
118
+ return false
119
+ }
120
+ return true
121
+ })
122
+ if (at !== null) return at
123
+ const f = formats.find((x) => x.suggestionId === id)
124
+ const b = f && findBlockNode(doc, f.blockId)
125
+ return b ? b.pos + 1 + f!.from : null
126
+ }
127
+
128
+ function caretOf(state: EditorState): { blockId: string; offset: number } | null {
129
+ const sel = state.selection
130
+ if (!sel.empty) return null
131
+ const parent = sel.$from.parent
132
+ const id = parent.attrs.id as string | null
133
+ return id ? { blockId: id, offset: sel.$from.parentOffset } : null
134
+ }
135
+
136
+ const toBlocks = (nodes: PmNode[]): Block[] => nodes.map((n) => blockFromPm(n.toJSON())).filter((b): b is Block => b !== null)
137
+
138
+ /**
139
+ * The Suggesting-mode rewrite of one or more transactions (exported for tests).
140
+ * Returns the transaction to append, or null when there is nothing to do.
141
+ */
142
+ export function suggestTransaction(
143
+ trs: readonly Transaction[],
144
+ oldState: EditorState,
145
+ newState: EditorState,
146
+ isLocal: (id: string) => boolean
147
+ ): Transaction | null {
148
+ const st = suggestingKey.getState(newState)
149
+ const edits = trs.filter((t) => t.docChanged && !t.getMeta(suggestingKey) && !t.getMeta("history$") && !t.getMeta("appendedTransaction"))
150
+ if (!edits.length) return null
151
+ // Editing: typed or pasted text is plain draft text, never part of a suggestion around it.
152
+ if (!st?.enabled) return stripInsertedSuggestionMarks(trs, newState)
153
+
154
+ const a = oldState.doc
155
+ const b = newState.doc
156
+ let i = 0
157
+ while (i < a.childCount && i < b.childCount && a.child(i).eq(b.child(i))) i++
158
+ let j = 0
159
+ while (j < a.childCount - i && j < b.childCount - i && a.child(a.childCount - 1 - j).eq(b.child(b.childCount - 1 - j))) j++
160
+ const oldNodes: PmNode[] = []
161
+ const newNodes: PmNode[] = []
162
+ for (let k = i; k < a.childCount - j; k++) oldNodes.push(a.child(k))
163
+ for (let k = i; k < b.childCount - j; k++) newNodes.push(b.child(k))
164
+ let start = 0
165
+ for (let k = 0; k < i; k++) start += b.child(k).nodeSize
166
+ const newEnd = start + newNodes.reduce((n, node) => n + node.nodeSize, 0)
167
+
168
+ const result = suggestEdit(toBlocks(oldNodes), toBlocks(newNodes), {
169
+ localId: nextLocalId(),
170
+ isLocal,
171
+ caretBefore: oldState.selection.empty ? caretOf(oldState) : selectionEnd(oldState),
172
+ caretAfter: caretOf(newState),
173
+ })
174
+
175
+ const tr = newState.tr
176
+ const schema: Schema = newState.schema
177
+ if (!result) {
178
+ // Not expressible as a suggestion yet: put the touched blocks back as they were.
179
+ tr.replaceWith(start, newEnd, oldNodes)
180
+ tr.setSelection(oldState.selection.getBookmark().resolve(tr.doc))
181
+ tr.setMeta(suggestingKey, { refused: true } satisfies SuggestingMeta)
182
+ return tr.setMeta("addToHistory", false)
183
+ }
184
+ const nodes = result.blocks.map((block) => schema.nodeFromJSON(blockToPm(block)))
185
+ const same = nodes.length === newNodes.length && nodes.every((n, k) => n.eq(newNodes[k]))
186
+ if (same && !result.formats.length) return null
187
+ if (!same) tr.replaceWith(start, newEnd, nodes)
188
+ tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
189
+ if (!newState.selection.empty && tr.doc.content.size === newState.doc.content.size) {
190
+ // A formatting change keeps its selection.
191
+ tr.setSelection(TextSelection.create(tr.doc, newState.selection.from, newState.selection.to))
192
+ } else if (result.caret) {
193
+ const at = findBlockNode(tr.doc, result.caret.blockId)
194
+ if (at) {
195
+ const pos = Math.min(at.pos + 1 + result.caret.offset, at.pos + at.node.nodeSize - 1)
196
+ tr.setSelection(TextSelection.create(tr.doc, pos))
197
+ }
198
+ }
199
+ if (result.formats.length) {
200
+ const formats = result.formats
201
+ .map((f: FormatEdit) => {
202
+ const at = findBlockNode(tr.doc, f.blockId)
203
+ return at ? { id: f.id, from: at.pos + 1 + f.from, to: at.pos + 1 + f.to, mark: f.mark, add: f.add } : null
204
+ })
205
+ .filter((f): f is PmFormat => f !== null)
206
+ // A second meta key can't share the plugin key: formats ride on their own.
207
+ tr.setMeta(FORMATS_META, formats)
208
+ }
209
+ return tr
210
+ }
211
+
212
+ const FORMATS_META = "suggestingFormats"
213
+
214
+ /**
215
+ * Editing mode: text a transaction inserts must not carry another
216
+ * suggestion's `insertion` or `deletion` mark. Typed inside a suggested
217
+ * insertion, it would inherit the mark, and saving (which strips suggested
218
+ * insertions from the draft) would silently drop it. Undo/redo, the editor's
219
+ * own redraws and appended transactions keep their marks.
220
+ */
221
+ export function stripInsertedSuggestionMarks(trs: readonly Transaction[], state: EditorState): Transaction | null {
222
+ const ranges: { from: number; to: number }[] = []
223
+ trs.forEach((t, ti) => {
224
+ if (!t.docChanged || t.getMeta(suggestingKey) || t.getMeta("history$") || t.getMeta("appendedTransaction")) return
225
+ t.mapping.maps.forEach((map, i) => {
226
+ map.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
227
+ if (newEnd <= newStart) return
228
+ // Into this transaction's final document, then through the transactions after it.
229
+ let from = t.mapping.slice(i + 1).map(newStart, 1)
230
+ let to = t.mapping.slice(i + 1).map(newEnd, -1)
231
+ for (const later of trs.slice(ti + 1)) {
232
+ from = later.mapping.map(from, 1)
233
+ to = later.mapping.map(to, -1)
234
+ }
235
+ if (to > from) ranges.push({ from, to })
236
+ })
237
+ })
238
+ })
239
+ if (!ranges.length) return null
240
+ const { insertion, deletion } = state.schema.marks
241
+ const tr = state.tr
242
+ for (const { from, to } of ranges) {
243
+ let marked = false
244
+ state.doc.nodesBetween(from, to, (node) => {
245
+ if (node.isInline && node.marks.some((m) => m.type === insertion || m.type === deletion)) marked = true
246
+ return !marked
247
+ })
248
+ if (!marked) continue
249
+ if (insertion) tr.removeMark(from, to, insertion)
250
+ if (deletion) tr.removeMark(from, to, deletion)
251
+ }
252
+ if (!tr.docChanged) return null
253
+ return tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
254
+ }
255
+
256
+ function selectionEnd(state: EditorState): { blockId: string; offset: number } | null {
257
+ const $to = state.selection.$to
258
+ const id = $to.parent.attrs.id as string | null
259
+ return id ? { blockId: id, offset: $to.parentOffset } : null
260
+ }
261
+
262
+ /** Pending format edits as block offsets, for the flush. */
263
+ export function pendingFormats(state: EditorState): FormatEdit[] {
264
+ const st = suggestingKey.getState(state)
265
+ if (!st) return []
266
+ const out: FormatEdit[] = []
267
+ for (const f of st.formats) {
268
+ const $from = state.doc.resolve(f.from)
269
+ const id = $from.parent.attrs.id as string | null
270
+ if (!id || f.to <= f.from) continue
271
+ const start = $from.start()
272
+ out.push({ id: f.id, blockId: id, from: f.from - start, to: Math.min(f.to, $from.end()) - start, mark: f.mark, add: f.add })
273
+ }
274
+ return out
275
+ }
276
+
277
+ /** Swaps a local suggestion id for the server's in marks and block attrs. */
278
+ export function renameSuggestion(state: EditorState, from: string, to: string): Transaction {
279
+ const tr = state.tr
280
+ state.doc.descendants((node, pos) => {
281
+ if (node.attrs.suggestion?.id === from) tr.setNodeMarkup(pos, undefined, { ...node.attrs, suggestion: { ...node.attrs.suggestion, id: to } })
282
+ if (node.isText) {
283
+ for (const m of node.marks) {
284
+ if ((m.type.name === "insertion" || m.type.name === "deletion") && m.attrs.suggestionId === from) {
285
+ tr.removeMark(pos, pos + node.nodeSize, m)
286
+ tr.addMark(pos, pos + node.nodeSize, m.type.create({ suggestionId: to }))
287
+ }
288
+ }
289
+ }
290
+ return true
291
+ })
292
+ tr.setMeta(suggestingKey, { skip: true } satisfies SuggestingMeta)
293
+ tr.setMeta("addToHistory", false)
294
+ return tr
295
+ }
296
+
297
+ export const Suggesting = Extension.create<SuggestingOptions>({
298
+ name: "suggesting",
299
+ // After BlockIds, so a new block already has its id when the edit is rewritten.
300
+ priority: 10,
301
+ addOptions() {
302
+ return { isLocal: (id: string) => id.startsWith(LOCAL_PREFIX), onActivate: () => {} }
303
+ },
304
+ addProseMirrorPlugins() {
305
+ const options = this.options
306
+ return [
307
+ new Plugin<SuggestingState>({
308
+ key: suggestingKey,
309
+ state: {
310
+ init: () => ({ enabled: false, formats: [], serverFormats: [], threads: [], active: null, refused: 0 }),
311
+ apply(tr, prev) {
312
+ let next = prev
313
+ if (tr.docChanged && prev.formats.length) {
314
+ next = {
315
+ ...next,
316
+ formats: prev.formats
317
+ .map((f) => ({ ...f, from: tr.mapping.map(f.from, 1), to: tr.mapping.map(f.to, -1) }))
318
+ .filter((f) => f.to > f.from),
319
+ }
320
+ }
321
+ const added = tr.getMeta(FORMATS_META) as PmFormat[] | undefined
322
+ if (added) next = { ...next, formats: [...next.formats, ...added] }
323
+ const meta = tr.getMeta(suggestingKey) as SuggestingMeta | undefined
324
+ if (!meta) return next
325
+ if ("enabled" in meta) return { ...next, enabled: meta.enabled }
326
+ if ("dropFormats" in meta) return { ...next, formats: next.formats.filter((f) => !meta.dropFormats.includes(f.id)) }
327
+ if ("serverFormats" in meta) return { ...next, serverFormats: meta.serverFormats }
328
+ if ("threads" in meta) return { ...next, threads: meta.threads }
329
+ if ("active" in meta) return { ...next, active: meta.active }
330
+ if ("refused" in meta) return { ...next, refused: next.refused + 1 }
331
+ return next
332
+ },
333
+ },
334
+ appendTransaction: (trs, oldState, newState) => suggestTransaction(trs, oldState, newState, options.isLocal),
335
+ props: {
336
+ decorations(state) {
337
+ const st = suggestingKey.getState(state)
338
+ if (!st) return null
339
+ const decos: Decoration[] = []
340
+ for (const t of st.threads) {
341
+ const r = threadRange(state.doc, t)
342
+ if (r) decos.push(Decoration.inline(r.from, r.to, { class: `wy-cmt${st.active === t.id ? " is-active" : ""}`, "data-thread": t.id }))
343
+ }
344
+ state.doc.descendants((node, pos) => {
345
+ const s = node.attrs.suggestion as { id: string; action: string } | null | undefined
346
+ if (s) {
347
+ decos.push(
348
+ Decoration.node(pos, pos + node.nodeSize, {
349
+ class: `wy-sug-block is-${s.action}${st.active === s.id ? " is-active" : ""}`,
350
+ "data-suggestion": s.id,
351
+ })
352
+ )
353
+ }
354
+ return true
355
+ })
356
+ for (const f of st.serverFormats) {
357
+ const at = findBlockNode(state.doc, f.blockId)
358
+ if (at) decos.push(Decoration.inline(at.pos + 1 + f.from, at.pos + 1 + f.to, { class: "wy-sug-fmt", "data-suggestion": f.suggestionId }))
359
+ }
360
+ for (const f of st.formats) decos.push(Decoration.inline(f.from, f.to, { class: "wy-sug-fmt is-pending" }))
361
+ return DecorationSet.create(state.doc, decos)
362
+ },
363
+ handleClick(_view, _pos, event) {
364
+ const el = (event.target as HTMLElement | null)?.closest?.("[data-thread],[data-suggestion]") as HTMLElement | null
365
+ options.onActivate(el ? (el.dataset.thread ?? el.dataset.suggestion ?? null) : null)
366
+ return false
367
+ },
368
+ },
369
+ }),
370
+ ]
371
+ },
372
+ })