@whity/ui 0.5.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -107
- package/package.json +223 -192
- package/src/access-denied.stories.tsx +179 -179
- package/src/access-denied.tsx +305 -305
- package/src/action-proposal.tsx +338 -302
- package/src/actor-chip.tsx +71 -71
- package/src/agent-activity.tsx +163 -163
- package/src/agent-collaboration.stories.tsx +156 -156
- package/src/agent-run-status.tsx +196 -196
- package/src/alert-dialog.stories.tsx +45 -45
- package/src/alert-dialog.tsx +147 -147
- package/src/alert.stories.tsx +91 -91
- package/src/alert.tsx +89 -89
- package/src/app-sidebar.stories.tsx +195 -195
- package/src/app-sidebar.tsx +604 -500
- package/src/approval-queue.tsx +109 -108
- package/src/audience-group-picker.stories.tsx +198 -198
- package/src/audience-group-picker.tsx +362 -362
- package/src/audience-people-picker.stories.tsx +102 -102
- package/src/audience-people-picker.tsx +279 -279
- package/src/avatar-pattern.ts +138 -0
- package/src/avatar.tsx +125 -83
- package/src/badge.stories.tsx +105 -105
- package/src/badge.tsx +68 -68
- package/src/beta-warning.stories.tsx +79 -79
- package/src/beta-warning.tsx +189 -189
- package/src/bilingual-input.stories.tsx +82 -82
- package/src/bilingual-input.tsx +188 -183
- package/src/board.tsx +216 -0
- package/src/breadcrumb.stories.tsx +51 -51
- package/src/breadcrumb.tsx +90 -90
- package/src/built-on-whity.tsx +52 -0
- package/src/button.stories.tsx +87 -87
- package/src/button.tsx +125 -118
- package/src/card.stories.tsx +423 -423
- package/src/card.tsx +180 -180
- package/src/chart.stories.tsx +66 -66
- package/src/chart.tsx +228 -228
- package/src/checkbox.stories.tsx +62 -62
- package/src/checkbox.tsx +54 -54
- package/src/collapsible.stories.tsx +48 -48
- package/src/collapsible.tsx +34 -34
- package/src/color-card.stories.tsx +61 -61
- package/src/color-card.tsx +270 -270
- package/src/color-picker.stories.tsx +65 -65
- package/src/color-picker.tsx +425 -425
- package/src/column-matcher.tsx +84 -0
- package/src/command-palette.tsx +399 -306
- package/src/confirm-action.tsx +98 -0
- package/src/copy-block.stories.tsx +38 -38
- package/src/copy-block.tsx +85 -85
- package/src/data-table.stories.tsx +200 -200
- package/src/data-table.tsx +1687 -1106
- package/src/date-picker.stories.tsx +61 -61
- package/src/date-picker.tsx +457 -422
- package/src/design-cards.stories.tsx +551 -458
- package/src/dialog.stories.tsx +48 -48
- package/src/dialog.tsx +179 -166
- package/src/display-preferences.tsx +59 -0
- package/src/documents/barcode-svg.stories.tsx +72 -72
- package/src/documents/barcode-svg.tsx +79 -79
- package/src/dropdown-menu.stories.tsx +77 -77
- package/src/dropdown-menu.tsx +271 -271
- package/src/editor/agent-panel.tsx +222 -0
- package/src/editor/agents.stories.tsx +81 -0
- package/src/editor/agents.ts +55 -0
- package/src/editor/behaviour.ts +279 -279
- package/src/editor/block-ids.ts +44 -44
- package/src/editor/block-list.tsx +104 -101
- package/src/editor/block-toolbar.tsx +490 -477
- package/src/editor/bubble.tsx +119 -93
- package/src/editor/catalogue.ts +169 -103
- package/src/editor/collab-rail.tsx +746 -746
- package/src/editor/collab.stories.tsx +207 -207
- package/src/editor/collab.ts +87 -87
- package/src/editor/contract.ts +476 -408
- package/src/editor/convert.ts +414 -362
- package/src/editor/doc-editor.stories.tsx +98 -98
- package/src/editor/doc-editor.tsx +1492 -1287
- package/src/editor/editor.css +636 -536
- package/src/editor/extensions.ts +86 -86
- package/src/editor/field-bar.tsx +154 -0
- package/src/editor/field-picker.tsx +109 -107
- package/src/editor/fields.ts +100 -100
- package/src/editor/gutter.tsx +443 -367
- package/src/editor/index.ts +23 -22
- package/src/editor/label-sheet.tsx +289 -289
- package/src/editor/labels.ts +394 -310
- package/src/editor/link-tools.tsx +141 -141
- package/src/editor/node-views.tsx +461 -450
- package/src/editor/page-view.tsx +372 -353
- package/src/editor/phone.tsx +310 -0
- package/src/editor/plugin-block-view.tsx +230 -0
- package/src/editor/plugin-blocks.stories.tsx +96 -0
- package/src/editor/plugin-blocks.ts +52 -0
- package/src/editor/publish-check.tsx +201 -182
- package/src/editor/rich-blocks.stories.tsx +146 -146
- package/src/editor/sample.ts +40 -40
- package/src/editor/save-block-dialog.tsx +141 -0
- package/src/editor/saved-block-view.tsx +205 -0
- package/src/editor/saved-blocks.stories.tsx +105 -0
- package/src/editor/saved-parts.ts +192 -0
- package/src/editor/schema-rich.ts +156 -150
- package/src/editor/schema.ts +368 -315
- package/src/editor/services.tsx +205 -127
- package/src/editor/slash.ts +64 -64
- package/src/editor/suggesting.ts +372 -372
- package/src/editor/suggestions.ts +763 -763
- package/src/editor/table-keys.ts +66 -66
- package/src/editor/templates.stories.tsx +324 -324
- package/src/editor/toolbar.tsx +364 -358
- package/src/empty-state.stories.tsx +51 -51
- package/src/empty-state.tsx +126 -100
- package/src/empty-state.usage-notes.md +30 -30
- package/src/form.stories.tsx +112 -112
- package/src/form.tsx +176 -176
- package/src/globals.css +20 -20
- package/src/icon-button.tsx +85 -85
- package/src/icon-map.ts +335 -244
- package/src/icon.tsx +41 -41
- package/src/index.ts +92 -67
- package/src/input.stories.tsx +157 -157
- package/src/input.tsx +768 -759
- package/src/kpi-strip.tsx +47 -0
- package/src/localized-text.ts +76 -0
- package/src/locked-screen.stories.tsx +29 -29
- package/src/locked-screen.tsx +75 -61
- package/src/lockup.tsx +42 -0
- package/src/lottie.tsx +441 -0
- package/src/mark.tsx +62 -62
- package/src/math-text.stories.tsx +33 -33
- package/src/math-text.tsx +43 -43
- package/src/menu-bar.stories.tsx +198 -198
- package/src/menu-bar.tsx +373 -373
- package/src/message-thread.tsx +181 -0
- package/src/money/currency.ts +244 -230
- package/src/money/money-input.tsx +131 -0
- package/src/money/money.tsx +33 -0
- package/src/open-on-computer.tsx +150 -0
- package/src/otp-input.tsx +161 -0
- package/src/page-header.stories.tsx +95 -95
- package/src/page-header.tsx +122 -122
- package/src/page-shell.stories.tsx +42 -42
- package/src/page-shell.tsx +32 -32
- package/src/page-states.tsx +277 -0
- package/src/pagination.stories.tsx +45 -45
- package/src/pagination.tsx +98 -98
- package/src/paper-sheet.stories.tsx +88 -0
- package/src/paper-sheet.tsx +85 -0
- package/src/phone-input.tsx +252 -0
- package/src/phone-tab-bar.tsx +152 -0
- package/src/plugin-card.stories.tsx +208 -180
- package/src/plugin-card.tsx +931 -848
- package/src/popover.stories.tsx +48 -48
- package/src/popover.tsx +55 -55
- package/src/radio-group.stories.tsx +26 -26
- package/src/radio-group.tsx +44 -44
- package/src/role-summary.stories.tsx +143 -0
- package/src/role-summary.tsx +120 -0
- package/src/route-flow/editor.tsx +1087 -1014
- package/src/route-flow/model.ts +771 -716
- package/src/save-bar.tsx +94 -0
- package/src/scope-grant.tsx +139 -139
- package/src/screen-too-small.stories.tsx +61 -61
- package/src/screen-too-small.tsx +104 -104
- package/src/search-field.tsx +65 -0
- package/src/select.stories.tsx +44 -44
- package/src/select.tsx +197 -197
- package/src/separator.stories.tsx +34 -34
- package/src/separator.tsx +34 -34
- package/src/sheet.stories.tsx +49 -49
- package/src/sheet.tsx +168 -168
- package/src/skeleton.stories.tsx +28 -28
- package/src/skeleton.tsx +19 -19
- package/src/slider.stories.tsx +78 -78
- package/src/slider.tsx +300 -300
- package/src/spinner.stories.tsx +33 -33
- package/src/spinner.tsx +55 -55
- package/src/stepper.tsx +85 -0
- package/src/switch.stories.tsx +42 -42
- package/src/switch.tsx +41 -41
- package/src/switcher.stories.tsx +111 -111
- package/src/switcher.tsx +131 -131
- package/src/system-state.tsx +55 -0
- package/src/table.stories.tsx +48 -48
- package/src/table.tsx +121 -121
- package/src/tabs.stories.tsx +74 -74
- package/src/tabs.tsx +90 -90
- package/src/tag-input.stories.tsx +67 -67
- package/src/tag-input.tsx +117 -117
- package/src/tenant-logo.tsx +63 -63
- package/src/tenant-switcher.stories.tsx +38 -38
- package/src/tenant-switcher.tsx +185 -164
- package/src/textarea.stories.tsx +27 -27
- package/src/textarea.tsx +18 -18
- package/src/theme-mode.ts +74 -52
- package/src/time-grid.tsx +163 -0
- package/src/time-picker.stories.tsx +62 -62
- package/src/time-picker.tsx +616 -615
- package/src/toggle-group.tsx +139 -138
- package/src/tooltip.stories.tsx +43 -43
- package/src/tooltip.tsx +73 -73
- package/src/top-nav.stories.tsx +58 -58
- package/src/top-nav.tsx +324 -324
- package/src/undo-bar.tsx +107 -107
- package/src/utils.ts +45 -45
- package/src/view-toggle.stories.tsx +84 -84
- package/src/view-toggle.tsx +111 -110
|
@@ -1,763 +1,763 @@
|
|
|
1
|
-
import type { Block, Inline, Mark } from "./contract"
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Suggestions as patches (IMPLEMENTATION-NOTES 3.3, editor M5), and the two
|
|
5
|
-
* directions between a draft and what the editor shows. Pure: no React, no
|
|
6
|
-
* ProseMirror, only the contract's blocks.
|
|
7
|
-
*
|
|
8
|
-
* - `renderSuggestions(draft, suggestions)` draws open suggestions onto the
|
|
9
|
-
* draft: a `replace-text` patch's matched text gets the `deletion` mark and
|
|
10
|
-
* its insert follows with the `insertion` mark; inserted and deleted blocks
|
|
11
|
-
* get the block `suggestion` attr; a `format` patch is returned as a range to
|
|
12
|
-
* underline, since the contract has no mark for it.
|
|
13
|
-
* - `suggestEdit(before, after, …)` is Suggesting mode: given the blocks before
|
|
14
|
-
* and after an ordinary edit, it returns the blocks with that edit expressed
|
|
15
|
-
* as local suggestion marks (deleted text stays, struck through; typed text
|
|
16
|
-
* is marked inserted; deleting your own pending insertion just removes it),
|
|
17
|
-
* plus any formatting change as a pending format edit.
|
|
18
|
-
* - `collectPatches(blocks, formats, isLocal)` is the flush: every local
|
|
19
|
-
* change, grouped per block and region, as a patch to POST.
|
|
20
|
-
* - `stripSuggestions(blocks)` is the draft again: what Editing saves.
|
|
21
|
-
*
|
|
22
|
-
* Text is matched within a block's flattened inline text (`flatText`), as the
|
|
23
|
-
* server does (DocumentSuggestionPatch): text runs as they are, and each field,
|
|
24
|
-
* line break or formula as the one character U+FFFC. The occurrence-th match
|
|
25
|
-
* is the occurrence-th start position, scanning one character at a time.
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
/* ---------------------------------------------------------------- Patches */
|
|
29
|
-
|
|
30
|
-
export type SuggestionPatch =
|
|
31
|
-
| { op: "insert-blocks"; afterBlockId: string | null; blocks: Block[] }
|
|
32
|
-
| {
|
|
33
|
-
op: "replace-text"
|
|
34
|
-
blockId: string
|
|
35
|
-
deleteText: string
|
|
36
|
-
insert: Inline[]
|
|
37
|
-
occurrence: number
|
|
38
|
-
/** Pure insertions only: up to 40 characters of the block's text just before the insertion point. */
|
|
39
|
-
before?: string
|
|
40
|
-
}
|
|
41
|
-
| { op: "format"; blockId: string; deleteText: ""; text: string; occurrence: number; mark: Mark; add: boolean }
|
|
42
|
-
| { op: "delete-blocks"; blockIds: string[] }
|
|
43
|
-
| { op: "move-block"; blockId: string; afterBlockId: string | null }
|
|
44
|
-
|
|
45
|
-
export type SuggestionKind = "text" | "format" | "block"
|
|
46
|
-
|
|
47
|
-
/** What rendering needs of an open suggestion. */
|
|
48
|
-
export interface PatchedSuggestion {
|
|
49
|
-
id: string
|
|
50
|
-
patch: SuggestionPatch
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** A pending formatting change, by character offsets in the (marked) block. */
|
|
54
|
-
export interface FormatEdit {
|
|
55
|
-
id: string
|
|
56
|
-
blockId: string
|
|
57
|
-
from: number
|
|
58
|
-
to: number
|
|
59
|
-
mark: Mark
|
|
60
|
-
add: boolean
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** One local change ready to POST: the local ids it replaces once the server answers. */
|
|
64
|
-
export interface LocalChange {
|
|
65
|
-
localIds: string[]
|
|
66
|
-
kind: SuggestionKind
|
|
67
|
-
summary: string
|
|
68
|
-
patch: SuggestionPatch
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export const BEFORE_CHARS = 40
|
|
72
|
-
const OBJECT = String.fromCharCode(0xfffc)
|
|
73
|
-
const FORMAT_MARKS = new Set(["bold", "italic", "underline", "strike", "code", "link", "highlight"])
|
|
74
|
-
|
|
75
|
-
/* ------------------------------------------------------------------ Cells */
|
|
76
|
-
|
|
77
|
-
/** One character of a block's inline content, with its marks. */
|
|
78
|
-
interface Cell {
|
|
79
|
-
ch: string
|
|
80
|
-
/** For a break, field or formula: the inline itself (marks aside). */
|
|
81
|
-
atom?: Inline
|
|
82
|
-
marks: Mark[]
|
|
83
|
-
/** Transient: format suggestions covering this character. */
|
|
84
|
-
fmt?: string[]
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function marksOf(run: Inline): Mark[] {
|
|
88
|
-
return run.type === "text" || run.type === "field" ? (run.marks ?? []) : []
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function toCells(content: Inline[]): Cell[] {
|
|
92
|
-
const cells: Cell[] = []
|
|
93
|
-
for (const run of content) {
|
|
94
|
-
if (run.type === "text") {
|
|
95
|
-
// One cell per UTF-16 unit, so offsets match ProseMirror's positions.
|
|
96
|
-
for (let i = 0; i < run.text.length; i++) cells.push({ ch: run.text[i], marks: run.marks ?? [] })
|
|
97
|
-
} else {
|
|
98
|
-
const { marks: _m, ...atom } = run as Inline & { marks?: Mark[] }
|
|
99
|
-
cells.push({ ch: OBJECT, atom: atom as Inline, marks: marksOf(run) })
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
return cells
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const markKey = (m: Mark) => JSON.stringify(m)
|
|
106
|
-
const sameMarkList = (a: Mark[], b: Mark[]) => a.length === b.length && a.every((m, i) => markKey(m) === markKey(b[i]))
|
|
107
|
-
|
|
108
|
-
const ORDER = ["link", "bold", "italic", "underline", "strike", "code", "highlight", "comment", "insertion", "deletion", "perDocument"]
|
|
109
|
-
const sortMarks = (marks: Mark[]) => [...marks].sort((a, b) => ORDER.indexOf(a.type) - ORDER.indexOf(b.type))
|
|
110
|
-
|
|
111
|
-
function fromCells(cells: Cell[]): Inline[] {
|
|
112
|
-
const out: Inline[] = []
|
|
113
|
-
for (const c of cells) {
|
|
114
|
-
const marks = sortMarks(c.marks)
|
|
115
|
-
if (c.atom) {
|
|
116
|
-
const run = { ...c.atom } as Inline
|
|
117
|
-
if ((run.type === "field" || run.type === "text") && marks.length) (run as { marks?: Mark[] }).marks = marks
|
|
118
|
-
out.push(run)
|
|
119
|
-
continue
|
|
120
|
-
}
|
|
121
|
-
const last = out[out.length - 1]
|
|
122
|
-
if (last && last.type === "text" && sameMarkList(last.marks ?? [], marks)) last.text += c.ch
|
|
123
|
-
else {
|
|
124
|
-
const run: Inline = { type: "text", text: c.ch }
|
|
125
|
-
if (marks.length) run.marks = marks
|
|
126
|
-
out.push(run)
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return out.filter((r) => r.type !== "text" || r.text !== "")
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const insertionOf = (c: Cell) => c.marks.find((m) => m.type === "insertion") as { suggestionId: string } | undefined
|
|
133
|
-
const deletionOf = (c: Cell) => c.marks.find((m) => m.type === "deletion") as { suggestionId: string } | undefined
|
|
134
|
-
const isBase = (c: Cell) => !insertionOf(c)
|
|
135
|
-
const withoutSuggestionMarks = (marks: Mark[]) => marks.filter((m) => m.type !== "insertion" && m.type !== "deletion")
|
|
136
|
-
const formatting = (marks: Mark[]) => marks.filter((m) => FORMAT_MARKS.has(m.type))
|
|
137
|
-
|
|
138
|
-
/** A block's inline text as patches match it. */
|
|
139
|
-
export function flatText(content: Inline[]): string {
|
|
140
|
-
return toCells(content)
|
|
141
|
-
.map((c) => c.ch)
|
|
142
|
-
.join("")
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** The draft's text of a marked block: everything but suggested insertions. */
|
|
146
|
-
export function baseText(content: Inline[]): string {
|
|
147
|
-
return toCells(content)
|
|
148
|
-
.filter(isBase)
|
|
149
|
-
.map((c) => c.ch)
|
|
150
|
-
.join("")
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** How many matches of `needle` start before `limit` (every start position counts, overlapping or not). */
|
|
154
|
-
export function countMatches(haystack: string, needle: string, limit: number): number {
|
|
155
|
-
if (!needle) return 0
|
|
156
|
-
let n = 0
|
|
157
|
-
for (let i = haystack.indexOf(needle); i >= 0 && i < limit; i = haystack.indexOf(needle, i + 1)) n++
|
|
158
|
-
return n
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** The start of the occurrence-th match (0-based), or -1. */
|
|
162
|
-
export function nthMatch(haystack: string, needle: string, occurrence: number): number {
|
|
163
|
-
if (!needle) return -1
|
|
164
|
-
let i = haystack.indexOf(needle)
|
|
165
|
-
for (let n = 0; i >= 0 && n < occurrence; n++) i = haystack.indexOf(needle, i + 1)
|
|
166
|
-
return i
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/* ----------------------------------------------------------------- Blocks */
|
|
170
|
-
|
|
171
|
-
type Content = { content: Inline[] }
|
|
172
|
-
const hasContent = (b: Block): b is Block & Content => "content" in b && Array.isArray((b as Partial<Content>).content)
|
|
173
|
-
|
|
174
|
-
/** Every block list in a document: the top level, toggles' children and both columns. */
|
|
175
|
-
function eachList(blocks: Block[], visit: (list: Block[]) => void) {
|
|
176
|
-
visit(blocks)
|
|
177
|
-
for (const b of blocks) {
|
|
178
|
-
if (b.type === "toggle") eachList(b.children, visit)
|
|
179
|
-
if (b.type === "columns") b.columns.forEach((col) => eachList(col, visit))
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function findBlock(blocks: Block[], id: string): { list: Block[]; index: number } | null {
|
|
184
|
-
let found: { list: Block[]; index: number } | null = null
|
|
185
|
-
eachList(blocks, (list) => {
|
|
186
|
-
if (found) return
|
|
187
|
-
const index = list.findIndex((b) => b.id === id)
|
|
188
|
-
if (index >= 0) found = { list, index }
|
|
189
|
-
})
|
|
190
|
-
return found
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T
|
|
194
|
-
|
|
195
|
-
/** Blocks without any suggestion attr or mark: what goes into a patch or the draft. */
|
|
196
|
-
function cleanBlock(block: Block): Block {
|
|
197
|
-
const { suggestion: _s, ...rest } = block
|
|
198
|
-
const b = rest as Block
|
|
199
|
-
if (hasContent(b)) (b as Content).content = fromCells(toCells(b.content).map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) })))
|
|
200
|
-
if (b.type === "toggle") b.children = b.children.map(cleanBlock)
|
|
201
|
-
if (b.type === "columns") b.columns = [b.columns[0].map(cleanBlock), b.columns[1].map(cleanBlock)]
|
|
202
|
-
return b
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* The draft from a marked document: suggested insertions and inserted blocks
|
|
207
|
-
* removed, deletion marks dropped (their text is still the draft's), block
|
|
208
|
-
* suggestion attrs cleared. What Editing saves (the server refuses marks in a draft).
|
|
209
|
-
*/
|
|
210
|
-
export function stripSuggestions(blocks: Block[]): Block[] {
|
|
211
|
-
const out: Block[] = []
|
|
212
|
-
for (const block of blocks) {
|
|
213
|
-
if (block.suggestion?.action === "insert") continue
|
|
214
|
-
const { suggestion: _s, ...rest } = block
|
|
215
|
-
const b = rest as Block
|
|
216
|
-
if (hasContent(b)) {
|
|
217
|
-
;(b as Content).content = fromCells(
|
|
218
|
-
toCells(b.content)
|
|
219
|
-
.filter(isBase)
|
|
220
|
-
.map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) }))
|
|
221
|
-
)
|
|
222
|
-
}
|
|
223
|
-
if (b.type === "toggle") b.children = stripSuggestions(b.children)
|
|
224
|
-
if (b.type === "columns") b.columns = [stripSuggestions(b.columns[0]), stripSuggestions(b.columns[1])]
|
|
225
|
-
out.push(b)
|
|
226
|
-
}
|
|
227
|
-
return out
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/** True when a document has anything `stripSuggestions` would take out. */
|
|
231
|
-
export function hasSuggestionMarks(blocks: Block[]): boolean {
|
|
232
|
-
let found = false
|
|
233
|
-
eachList(blocks, (list) => {
|
|
234
|
-
for (const b of list) {
|
|
235
|
-
if (b.suggestion) found = true
|
|
236
|
-
if (hasContent(b) && toCells(b.content).some((c) => insertionOf(c) || deletionOf(c))) found = true
|
|
237
|
-
}
|
|
238
|
-
})
|
|
239
|
-
return found
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/* -------------------------------------------------------------- Rendering */
|
|
243
|
-
|
|
244
|
-
export interface RenderedFormat {
|
|
245
|
-
suggestionId: string
|
|
246
|
-
blockId: string
|
|
247
|
-
/** Character offsets in the rendered block. */
|
|
248
|
-
from: number
|
|
249
|
-
to: number
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
export interface Rendered {
|
|
253
|
-
blocks: Block[]
|
|
254
|
-
/** Format suggestions: ranges to underline (dashed). */
|
|
255
|
-
formats: RenderedFormat[]
|
|
256
|
-
/** Suggestions whose anchor wasn't found in this draft (stale on the server's next accept). */
|
|
257
|
-
unplaced: string[]
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Draws open suggestions onto a draft, in the order given (the server's id order). */
|
|
261
|
-
export function renderSuggestions(draft: Block[], suggestions: PatchedSuggestion[]): Rendered {
|
|
262
|
-
const blocks = clone(draft)
|
|
263
|
-
const unplaced: string[] = []
|
|
264
|
-
const cellsById = new Map<string, Cell[]>()
|
|
265
|
-
const cellsOf = (id: string): Cell[] | null => {
|
|
266
|
-
if (cellsById.has(id)) return cellsById.get(id)!
|
|
267
|
-
const at = findBlock(blocks, id)
|
|
268
|
-
if (!at) return null
|
|
269
|
-
const block = at.list[at.index]
|
|
270
|
-
if (!hasContent(block)) return null
|
|
271
|
-
const cells = toCells(block.content)
|
|
272
|
-
cellsById.set(id, cells)
|
|
273
|
-
return cells
|
|
274
|
-
}
|
|
275
|
-
/** The cell index of the base character at `offset` (or the end). */
|
|
276
|
-
const cellAt = (cells: Cell[], offset: number) => {
|
|
277
|
-
let n = 0
|
|
278
|
-
for (let i = 0; i < cells.length; i++) {
|
|
279
|
-
if (!isBase(cells[i])) continue
|
|
280
|
-
if (n === offset) return i
|
|
281
|
-
n++
|
|
282
|
-
}
|
|
283
|
-
return cells.length
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
for (const s of suggestions) {
|
|
287
|
-
const p = s.patch
|
|
288
|
-
if (p.op === "replace-text") {
|
|
289
|
-
const cells = cellsOf(p.blockId)
|
|
290
|
-
if (!cells) {
|
|
291
|
-
unplaced.push(s.id)
|
|
292
|
-
continue
|
|
293
|
-
}
|
|
294
|
-
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
295
|
-
let start: number
|
|
296
|
-
if (p.deleteText) start = nthMatch(base, p.deleteText, p.occurrence)
|
|
297
|
-
else if (!p.before) start = 0
|
|
298
|
-
else {
|
|
299
|
-
const at = nthMatch(base, p.before, p.occurrence)
|
|
300
|
-
start = at < 0 ? -1 : at + p.before.length
|
|
301
|
-
}
|
|
302
|
-
if (start < 0) {
|
|
303
|
-
unplaced.push(s.id)
|
|
304
|
-
continue
|
|
305
|
-
}
|
|
306
|
-
const from = cellAt(cells, start)
|
|
307
|
-
const to = p.deleteText ? cellAt(cells, start + p.deleteText.length - 1) + 1 : from
|
|
308
|
-
// Two suggestions deleting the same text can't both show; the later one waits.
|
|
309
|
-
if (cells.slice(from, to).some((c) => deletionOf(c))) {
|
|
310
|
-
unplaced.push(s.id)
|
|
311
|
-
continue
|
|
312
|
-
}
|
|
313
|
-
for (let i = from; i < to; i++) if (isBase(cells[i])) cells[i] = { ...cells[i], marks: [...cells[i].marks, { type: "deletion", suggestionId: s.id }] }
|
|
314
|
-
const inserted = toCells(p.insert).map((c) => ({ ...c, marks: [...withoutSuggestionMarks(c.marks), { type: "insertion" as const, suggestionId: s.id }] }))
|
|
315
|
-
cells.splice(to, 0, ...inserted)
|
|
316
|
-
} else if (p.op === "format") {
|
|
317
|
-
const cells = cellsOf(p.blockId)
|
|
318
|
-
const base = cells ? cells.filter(isBase).map((c) => c.ch).join("") : ""
|
|
319
|
-
const start = cells ? nthMatch(base, p.text, p.occurrence) : -1
|
|
320
|
-
if (!cells || start < 0) {
|
|
321
|
-
unplaced.push(s.id)
|
|
322
|
-
continue
|
|
323
|
-
}
|
|
324
|
-
const from = cellAt(cells, start)
|
|
325
|
-
const to = cellAt(cells, start + p.text.length - 1) + 1
|
|
326
|
-
for (let i = from; i < to; i++) if (isBase(cells[i])) cells[i] = { ...cells[i], fmt: [...(cells[i].fmt ?? []), s.id] }
|
|
327
|
-
} else if (p.op === "insert-blocks") {
|
|
328
|
-
const added = p.blocks.map((b) => ({ ...cleanBlock(clone(b)), suggestion: { id: s.id, action: "insert" as const } }))
|
|
329
|
-
if (p.afterBlockId === null) {
|
|
330
|
-
blocks.unshift(...added)
|
|
331
|
-
continue
|
|
332
|
-
}
|
|
333
|
-
const at = findBlock(blocks, p.afterBlockId)
|
|
334
|
-
if (!at) {
|
|
335
|
-
unplaced.push(s.id)
|
|
336
|
-
continue
|
|
337
|
-
}
|
|
338
|
-
// After the anchor and after any blocks other suggestions already inserted there.
|
|
339
|
-
let i = at.index + 1
|
|
340
|
-
while (i < at.list.length && at.list[i].suggestion?.action === "insert") i++
|
|
341
|
-
at.list.splice(i, 0, ...added)
|
|
342
|
-
} else if (p.op === "delete-blocks" || p.op === "move-block") {
|
|
343
|
-
const ids = p.op === "delete-blocks" ? p.blockIds : [p.blockId]
|
|
344
|
-
const places = ids.map((id) => findBlock(blocks, id))
|
|
345
|
-
if (places.some((at) => !at || at.list[at.index].suggestion)) {
|
|
346
|
-
unplaced.push(s.id)
|
|
347
|
-
continue
|
|
348
|
-
}
|
|
349
|
-
for (const at of places) {
|
|
350
|
-
const b = at!.list[at!.index]
|
|
351
|
-
at!.list[at!.index] = { ...b, suggestion: { id: s.id, action: p.op === "delete-blocks" ? "delete" : "move" } }
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
const formats: RenderedFormat[] = []
|
|
357
|
-
eachList(blocks, (list) => {
|
|
358
|
-
list.forEach((block, index) => {
|
|
359
|
-
const cells = cellsById.get(block.id)
|
|
360
|
-
if (!cells || !hasContent(block)) return
|
|
361
|
-
for (let i = 0; i < cells.length; i++) {
|
|
362
|
-
for (const id of cells[i].fmt ?? []) {
|
|
363
|
-
if (i > 0 && cells[i - 1].fmt?.includes(id)) continue
|
|
364
|
-
let j = i
|
|
365
|
-
while (j < cells.length && (cells[j].fmt?.includes(id) || !isBase(cells[j]))) j++
|
|
366
|
-
while (j > i && !cells[j - 1].fmt?.includes(id)) j--
|
|
367
|
-
formats.push({ suggestionId: id, blockId: block.id, from: i, to: j })
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
list[index] = { ...block, content: fromCells(cells) } as Block
|
|
371
|
-
})
|
|
372
|
-
})
|
|
373
|
-
return { blocks, formats, unplaced }
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
/* ------------------------------------------------------- Suggesting mode */
|
|
377
|
-
|
|
378
|
-
export interface SuggestEditOptions {
|
|
379
|
-
/** The id local changes made by this edit get. */
|
|
380
|
-
localId: string
|
|
381
|
-
/** Whether a suggestion id is one of this person's pending (unsent) changes. */
|
|
382
|
-
isLocal: (id: string) => boolean
|
|
383
|
-
/**
|
|
384
|
-
* Where the caret was before the edit (block id and character offset), so a
|
|
385
|
-
* Backspace over text leaves the caret before the struck-through text.
|
|
386
|
-
*/
|
|
387
|
-
caretBefore?: { blockId: string; offset: number } | null
|
|
388
|
-
/** Where the caret is after the edit, to map into the result. */
|
|
389
|
-
caretAfter?: { blockId: string; offset: number } | null
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
export interface SuggestEditResult {
|
|
393
|
-
blocks: Block[]
|
|
394
|
-
/** New pending format edits (offsets in the resulting blocks). */
|
|
395
|
-
formats: FormatEdit[]
|
|
396
|
-
/** The caret in the result, when `caretAfter` was given. */
|
|
397
|
-
caret: { blockId: string; offset: number } | null
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
const asJson = (v: unknown) => JSON.stringify(v)
|
|
401
|
-
const sameBlockShape = (a: Block, b: Block) => {
|
|
402
|
-
const { content: _a, suggestion: _sa, ...ra } = a as Block & Partial<Content>
|
|
403
|
-
const { content: _b, suggestion: _sb, ...rb } = b as Block & Partial<Content>
|
|
404
|
-
return asJson(ra) === asJson(rb)
|
|
405
|
-
}
|
|
406
|
-
const cellKey = (c: Cell) => `${c.ch}|${c.atom ? asJson(c.atom) : ""}|${insertionOf(c)?.suggestionId ?? ""}|${deletionOf(c)?.suggestionId ?? ""}`
|
|
407
|
-
|
|
408
|
-
/**
|
|
409
|
-
* Suggesting mode for one edit. `before` and `after` are the same stretch of
|
|
410
|
-
* sibling blocks (the editor passes the blocks the edit touched). Returns null
|
|
411
|
-
* when the edit can't be expressed as a suggestion yet (see the limits in
|
|
412
|
-
* README), so the editor refuses it.
|
|
413
|
-
*/
|
|
414
|
-
export function suggestEdit(before: Block[], after: Block[], opts: SuggestEditOptions): SuggestEditResult | null {
|
|
415
|
-
const { localId, isLocal } = opts
|
|
416
|
-
const oldIndex = new Map(before.map((b, i) => [b.id, i]))
|
|
417
|
-
const newIds = new Set(after.map((b) => b.id).filter(Boolean))
|
|
418
|
-
const out: Block[] = []
|
|
419
|
-
const formats: FormatEdit[] = []
|
|
420
|
-
let caret: SuggestEditResult["caret"] = null
|
|
421
|
-
let pointer = 0
|
|
422
|
-
|
|
423
|
-
const emitRemoved = (upTo: number) => {
|
|
424
|
-
for (; pointer < upTo; pointer++) {
|
|
425
|
-
const old = before[pointer]
|
|
426
|
-
if (newIds.has(old.id)) return false
|
|
427
|
-
if (old.suggestion?.action === "insert") {
|
|
428
|
-
// Your own pending block goes; someone else's suggestion stays until it's decided.
|
|
429
|
-
if (isLocal(old.suggestion.id)) continue
|
|
430
|
-
out.push(old)
|
|
431
|
-
continue
|
|
432
|
-
}
|
|
433
|
-
out.push(old.suggestion ? old : { ...old, suggestion: { id: localId, action: "delete" } })
|
|
434
|
-
}
|
|
435
|
-
return true
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
for (const nb of after) {
|
|
439
|
-
const idx = nb.id ? oldIndex.get(nb.id) : undefined
|
|
440
|
-
if (idx === undefined) {
|
|
441
|
-
// A new block: a whole-block insertion, its text unmarked inside it.
|
|
442
|
-
const added = { ...cleanBlock(nb), suggestion: { id: localId, action: "insert" as const } }
|
|
443
|
-
out.push(added)
|
|
444
|
-
if (opts.caretAfter && opts.caretAfter.blockId === nb.id) caret = opts.caretAfter
|
|
445
|
-
continue
|
|
446
|
-
}
|
|
447
|
-
if (idx < pointer) return null // moved: move suggestions aren't made from the editor yet
|
|
448
|
-
if (!emitRemoved(idx)) return null
|
|
449
|
-
pointer = idx + 1
|
|
450
|
-
const old = before[idx]
|
|
451
|
-
const diffed = diffBlock(old, nb, opts, formats, (c) => (caret = c))
|
|
452
|
-
if (!diffed) return null
|
|
453
|
-
out.push(diffed)
|
|
454
|
-
}
|
|
455
|
-
if (!emitRemoved(before.length)) return null
|
|
456
|
-
return { blocks: out, formats, caret }
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
function diffBlock(
|
|
460
|
-
old: Block,
|
|
461
|
-
nb: Block,
|
|
462
|
-
opts: SuggestEditOptions,
|
|
463
|
-
formats: FormatEdit[],
|
|
464
|
-
setCaret: (c: { blockId: string; offset: number }) => void
|
|
465
|
-
): Block | null {
|
|
466
|
-
const { isLocal } = opts
|
|
467
|
-
const caretHere = opts.caretAfter && opts.caretAfter.blockId === nb.id ? opts.caretAfter.offset : null
|
|
468
|
-
if (asJson(old) === asJson(nb)) {
|
|
469
|
-
if (caretHere !== null) setCaret({ blockId: nb.id, offset: caretHere })
|
|
470
|
-
return old
|
|
471
|
-
}
|
|
472
|
-
// Your own inserted block is yours to change freely until it's sent.
|
|
473
|
-
if (old.suggestion?.action === "insert" && isLocal(old.suggestion.id)) {
|
|
474
|
-
if (caretHere !== null) setCaret({ blockId: nb.id, offset: caretHere })
|
|
475
|
-
return { ...cleanBlock(nb), suggestion: old.suggestion }
|
|
476
|
-
}
|
|
477
|
-
if (old.suggestion) return null // inside a suggested (inserted or struck) block of someone else
|
|
478
|
-
if (!hasContent(old) || !hasContent(nb) || old.type !== nb.type || !sameBlockShape(old, nb)) return null
|
|
479
|
-
|
|
480
|
-
const a = toCells(old.content)
|
|
481
|
-
const b = toCells(nb.content)
|
|
482
|
-
let p = 0
|
|
483
|
-
while (p < a.length && p < b.length && cellKey(a[p]) === cellKey(b[p])) p++
|
|
484
|
-
let s = 0
|
|
485
|
-
while (s < a.length - p && s < b.length - p && cellKey(a[a.length - 1 - s]) === cellKey(b[b.length - 1 - s])) s++
|
|
486
|
-
|
|
487
|
-
// "a b" + " " is ambiguous: the inserted (or deleted) run could sit anywhere it
|
|
488
|
-
// slides to. Put it where the caret says it happened.
|
|
489
|
-
const insLen = b.length - p - s
|
|
490
|
-
const delLen = a.length - p - s
|
|
491
|
-
const slide = (seq: Cell[], len: number, target: number) => {
|
|
492
|
-
let q = p
|
|
493
|
-
while (q > target && q > 0 && cellKey(seq[q - 1]) === cellKey(seq[q - 1 + len])) q--
|
|
494
|
-
return q
|
|
495
|
-
}
|
|
496
|
-
if (delLen === 0 && insLen > 0 && caretHere !== null && caretHere - insLen < p) {
|
|
497
|
-
p = slide(b, insLen, caretHere - insLen)
|
|
498
|
-
s = a.length - p
|
|
499
|
-
} else if (insLen === 0 && delLen > 0 && opts.caretBefore?.blockId === nb.id) {
|
|
500
|
-
const c = opts.caretBefore.offset
|
|
501
|
-
const target = c - delLen < p && c - delLen >= 0 ? c - delLen : c < p ? c : p
|
|
502
|
-
p = slide(a, delLen, target)
|
|
503
|
-
s = b.length - p
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// One run of changes keeps one id: typing on from your pending text extends it.
|
|
507
|
-
const near = [a[p - 1], ...a.slice(p, a.length - s), a[a.length - s]].filter(Boolean)
|
|
508
|
-
const reuse = near
|
|
509
|
-
.map((c) => (insertionOf(c) ?? deletionOf(c))?.suggestionId)
|
|
510
|
-
.find((id): id is string => !!id && isLocal(id))
|
|
511
|
-
const localId = reuse ?? opts.localId
|
|
512
|
-
|
|
513
|
-
const result: Cell[] = []
|
|
514
|
-
// Unchanged text: a formatting difference is a format suggestion, except in your own pending text.
|
|
515
|
-
const keep = (oc: Cell, nc: Cell) => {
|
|
516
|
-
const own = insertionOf(oc) && isLocal(insertionOf(oc)!.suggestionId)
|
|
517
|
-
if (own || sameMarkList(formatting(oc.marks), formatting(nc.marks))) return { ...oc, marks: own ? nc.marks : oc.marks }
|
|
518
|
-
return { ...oc, fmtChange: { from: formatting(oc.marks), to: formatting(nc.marks) } }
|
|
519
|
-
}
|
|
520
|
-
const prefix = a.slice(0, p).map((c, i) => keep(c, b[i]))
|
|
521
|
-
const suffix = a.slice(a.length - s).map((c, i) => keep(c, b[b.length - s + i]))
|
|
522
|
-
|
|
523
|
-
const removed = a.slice(p, a.length - s)
|
|
524
|
-
const kept: Cell[] = []
|
|
525
|
-
for (const c of removed) {
|
|
526
|
-
const ins = insertionOf(c)
|
|
527
|
-
if (ins && isLocal(ins.suggestionId)) continue // your own pending insertion: just removed
|
|
528
|
-
if (ins || deletionOf(c)) kept.push(c) // already a suggestion: stays as it is
|
|
529
|
-
else kept.push({ ...c, marks: [...c.marks, { type: "deletion", suggestionId: localId }] })
|
|
530
|
-
}
|
|
531
|
-
const added = b.slice(p, b.length - s).map((c) => ({ ...c, marks: [...withoutSuggestionMarks(c.marks), { type: "insertion" as const, suggestionId: localId }] }))
|
|
532
|
-
result.push(...prefix, ...kept, ...added, ...suffix)
|
|
533
|
-
|
|
534
|
-
// Format changes become pending format edits on the old text, grouped by mark and direction.
|
|
535
|
-
type Changed = Cell & { fmtChange?: { from: Mark[]; to: Mark[] } }
|
|
536
|
-
const changes = (result as Changed[]).map((c) => {
|
|
537
|
-
if (!c.fmtChange) return [] as { mark: Mark; add: boolean }[]
|
|
538
|
-
const fromKeys = new Set(c.fmtChange.from.map(markKey))
|
|
539
|
-
const toKeys = new Set(c.fmtChange.to.map(markKey))
|
|
540
|
-
return [
|
|
541
|
-
...c.fmtChange.to.filter((m) => !fromKeys.has(markKey(m))).map((mark) => ({ mark, add: true })),
|
|
542
|
-
...c.fmtChange.from.filter((m) => !toKeys.has(markKey(m))).map((mark) => ({ mark, add: false })),
|
|
543
|
-
]
|
|
544
|
-
})
|
|
545
|
-
const done = new Set<string>()
|
|
546
|
-
changes.forEach((list, i) => {
|
|
547
|
-
for (const ch of list) {
|
|
548
|
-
const key = `${markKey(ch.mark)}|${ch.add}|${i}`
|
|
549
|
-
if (done.has(key)) continue
|
|
550
|
-
let j = i
|
|
551
|
-
while (j < changes.length && changes[j].some((x) => x.add === ch.add && markKey(x.mark) === markKey(ch.mark))) {
|
|
552
|
-
done.add(`${markKey(ch.mark)}|${ch.add}|${j}`)
|
|
553
|
-
j++
|
|
554
|
-
}
|
|
555
|
-
formats.push({ id: localId, blockId: nb.id, from: i, to: j, mark: ch.mark, add: ch.add })
|
|
556
|
-
}
|
|
557
|
-
})
|
|
558
|
-
for (const c of result as Changed[]) delete c.fmtChange
|
|
559
|
-
|
|
560
|
-
if (caretHere !== null) {
|
|
561
|
-
const insEnd = p + added.length
|
|
562
|
-
let offset: number
|
|
563
|
-
if (caretHere <= p && !(caretHere === p && added.length)) {
|
|
564
|
-
// Backspace leaves the caret before the struck text; Delete and a range delete, after it.
|
|
565
|
-
const backspace = opts.caretBefore?.blockId === nb.id && opts.caretBefore.offset === a.length - s && removed.length > 0
|
|
566
|
-
offset = caretHere === p && !backspace ? p + kept.length : caretHere
|
|
567
|
-
} else if (caretHere <= insEnd) offset = caretHere + kept.length
|
|
568
|
-
else offset = caretHere - b.length + result.length
|
|
569
|
-
setCaret({ blockId: nb.id, offset })
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
return { ...nb, content: fromCells(result) } as Block
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
/* ----------------------------------------------------------------- Flush */
|
|
576
|
-
|
|
577
|
-
export interface SummaryWords {
|
|
578
|
-
replace: string // "Replace {from} with {to}"
|
|
579
|
-
add: string // "Add {text}"
|
|
580
|
-
delete: string // "Delete {text}"
|
|
581
|
-
format: string // "Format {text}: {mark}"
|
|
582
|
-
unformat: string // "Remove {mark} from {text}"
|
|
583
|
-
addBlocks: string // "Add {n} blocks" / "Add {text}"
|
|
584
|
-
deleteBlocks: string
|
|
585
|
-
moveBlock: string
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
export const SUMMARY_EN: SummaryWords = {
|
|
589
|
-
replace: "Replace {from} with {to}",
|
|
590
|
-
add: "Add {text}",
|
|
591
|
-
delete: "Delete {text}",
|
|
592
|
-
format: "Make {text} {mark}",
|
|
593
|
-
unformat: "Remove {mark} from {text}",
|
|
594
|
-
addBlocks: "Add {text}",
|
|
595
|
-
deleteBlocks: "Delete {text}",
|
|
596
|
-
moveBlock: "Move {text}",
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
const fillIn = (t: string, v: Record<string, string>) => t.replace(/\{(\w+)\}/g, (_, k: string) => v[k] ?? "")
|
|
600
|
-
const shorten = (t: string, n = 60) => (t.length > n ? `${t.slice(0, n - 1)}…` : t)
|
|
601
|
-
const inlineText = (content: Inline[]) => flatText(content).replace(/\uFFFC/g, "…")
|
|
602
|
-
|
|
603
|
-
function blockText(block: Block): string {
|
|
604
|
-
if (hasContent(block)) return inlineText(block.content)
|
|
605
|
-
if (block.type === "code") return block.text
|
|
606
|
-
if (block.type === "toggle") return inlineText(block.summary)
|
|
607
|
-
return block.type
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/** The card's sentence for a patch ("Replace 30 days with 14 days"). */
|
|
611
|
-
export function summarize(patch: SuggestionPatch, words: SummaryWords = SUMMARY_EN, quote = (t: string) => `“${shorten(t)}”`): string {
|
|
612
|
-
switch (patch.op) {
|
|
613
|
-
case "replace-text": {
|
|
614
|
-
const ins = inlineText(patch.insert)
|
|
615
|
-
if (patch.deleteText && ins) return fillIn(words.replace, { from: quote(patch.deleteText), to: quote(ins) })
|
|
616
|
-
if (patch.deleteText) return fillIn(words.delete, { text: quote(patch.deleteText) })
|
|
617
|
-
return fillIn(words.add, { text: quote(ins) })
|
|
618
|
-
}
|
|
619
|
-
case "format":
|
|
620
|
-
return fillIn(patch.add ? words.format : words.unformat, { text: quote(patch.text), mark: patch.mark.type })
|
|
621
|
-
case "insert-blocks":
|
|
622
|
-
return fillIn(words.addBlocks, { text: quote(patch.blocks.map(blockText).join(" ").trim() || patch.blocks[0]?.type || "") })
|
|
623
|
-
case "delete-blocks":
|
|
624
|
-
return fillIn(words.deleteBlocks, { text: quote(patch.blockIds.join(", ")) })
|
|
625
|
-
case "move-block":
|
|
626
|
-
return fillIn(words.moveBlock, { text: quote(patch.blockId) })
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
/**
|
|
631
|
-
* Every local change in a marked document as patches, grouped per block:
|
|
632
|
-
* consecutive inserted blocks are one `insert-blocks`, consecutive deleted
|
|
633
|
-
* ones one `delete-blocks`; within a text block each run of local marks is one
|
|
634
|
-
* `replace-text`; each pending format edit is one `format`.
|
|
635
|
-
*/
|
|
636
|
-
export function collectPatches(blocks: Block[], formats: FormatEdit[], isLocal: (id: string) => boolean): LocalChange[] {
|
|
637
|
-
const changes: LocalChange[] = []
|
|
638
|
-
const deletedText = new Map<string, string>()
|
|
639
|
-
|
|
640
|
-
eachList(blocks, (list) => {
|
|
641
|
-
let i = 0
|
|
642
|
-
while (i < list.length) {
|
|
643
|
-
const block = list[i]
|
|
644
|
-
const s = block.suggestion
|
|
645
|
-
if (s && isLocal(s.id) && (s.action === "insert" || s.action === "delete")) {
|
|
646
|
-
let j = i
|
|
647
|
-
while (j < list.length && list[j].suggestion?.action === s.action && isLocal(list[j].suggestion!.id)) j++
|
|
648
|
-
const group = list.slice(i, j)
|
|
649
|
-
const localIds = [...new Set(group.map((b) => b.suggestion!.id))]
|
|
650
|
-
if (s.action === "insert") {
|
|
651
|
-
// Anchored after the nearest block that is in the draft.
|
|
652
|
-
let k = i - 1
|
|
653
|
-
while (k >= 0 && list[k].suggestion?.action === "insert") k--
|
|
654
|
-
const patch: SuggestionPatch = { op: "insert-blocks", afterBlockId: k >= 0 ? list[k].id : null, blocks: group.map(cleanBlock) }
|
|
655
|
-
changes.push({ localIds, kind: "block", patch, summary: summarize(patch) })
|
|
656
|
-
} else {
|
|
657
|
-
const patch: SuggestionPatch = { op: "delete-blocks", blockIds: group.map((b) => b.id) }
|
|
658
|
-
group.forEach((b) => deletedText.set(b.id, blockText(b)))
|
|
659
|
-
changes.push({
|
|
660
|
-
localIds,
|
|
661
|
-
kind: "block",
|
|
662
|
-
patch,
|
|
663
|
-
summary: fillIn(SUMMARY_EN.deleteBlocks, { text: `“${shorten(group.map(blockText).join(" "))}”` }),
|
|
664
|
-
})
|
|
665
|
-
}
|
|
666
|
-
i = j
|
|
667
|
-
continue
|
|
668
|
-
}
|
|
669
|
-
if (!s && hasContent(block)) changes.push(...textChanges(block, isLocal))
|
|
670
|
-
i++
|
|
671
|
-
}
|
|
672
|
-
})
|
|
673
|
-
|
|
674
|
-
for (const f of formats) {
|
|
675
|
-
if (!isLocal(f.id)) continue
|
|
676
|
-
const at = findBlock(blocks, f.blockId)
|
|
677
|
-
const block = at?.list[at.index]
|
|
678
|
-
if (!block || !hasContent(block)) continue
|
|
679
|
-
const cells = toCells(block.content)
|
|
680
|
-
const baseBefore = cells.slice(0, f.from).filter(isBase).length
|
|
681
|
-
const text = cells.slice(f.from, f.to).filter(isBase).map((c) => c.ch).join("")
|
|
682
|
-
if (!text) continue
|
|
683
|
-
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
684
|
-
const patch: SuggestionPatch = {
|
|
685
|
-
op: "format",
|
|
686
|
-
blockId: block.id,
|
|
687
|
-
deleteText: "",
|
|
688
|
-
text,
|
|
689
|
-
occurrence: countMatches(base, text, baseBefore),
|
|
690
|
-
mark: f.mark,
|
|
691
|
-
add: f.add,
|
|
692
|
-
}
|
|
693
|
-
changes.push({ localIds: [f.id], kind: "format", patch, summary: summarize(patch) })
|
|
694
|
-
}
|
|
695
|
-
return changes
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
function textChanges(block: Block & Content, isLocal: (id: string) => boolean): LocalChange[] {
|
|
699
|
-
const cells = toCells(block.content)
|
|
700
|
-
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
701
|
-
const localOf = (c: Cell) => {
|
|
702
|
-
const m = insertionOf(c) ?? deletionOf(c)
|
|
703
|
-
return m && isLocal(m.suggestionId) ? m.suggestionId : null
|
|
704
|
-
}
|
|
705
|
-
const out: LocalChange[] = []
|
|
706
|
-
let baseOffset = 0
|
|
707
|
-
let i = 0
|
|
708
|
-
while (i < cells.length) {
|
|
709
|
-
if (!localOf(cells[i])) {
|
|
710
|
-
if (isBase(cells[i])) baseOffset++
|
|
711
|
-
i++
|
|
712
|
-
continue
|
|
713
|
-
}
|
|
714
|
-
const start = baseOffset
|
|
715
|
-
const ids = new Set<string>()
|
|
716
|
-
const del: Cell[] = []
|
|
717
|
-
const ins: Cell[] = []
|
|
718
|
-
while (i < cells.length && localOf(cells[i])) {
|
|
719
|
-
ids.add(localOf(cells[i])!)
|
|
720
|
-
if (insertionOf(cells[i])) ins.push(cells[i])
|
|
721
|
-
else {
|
|
722
|
-
del.push(cells[i])
|
|
723
|
-
baseOffset++
|
|
724
|
-
}
|
|
725
|
-
i++
|
|
726
|
-
}
|
|
727
|
-
const deleteText = del.map((c) => c.ch).join("")
|
|
728
|
-
const insert = fromCells(ins.map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) })))
|
|
729
|
-
let patch: SuggestionPatch
|
|
730
|
-
if (deleteText) {
|
|
731
|
-
patch = { op: "replace-text", blockId: block.id, deleteText, insert, occurrence: countMatches(base, deleteText, start) }
|
|
732
|
-
} else {
|
|
733
|
-
const before = base.slice(Math.max(0, start - BEFORE_CHARS), start)
|
|
734
|
-
patch = {
|
|
735
|
-
op: "replace-text",
|
|
736
|
-
blockId: block.id,
|
|
737
|
-
deleteText: "",
|
|
738
|
-
insert,
|
|
739
|
-
before,
|
|
740
|
-
occurrence: before ? countMatches(base, before, start - before.length) : 0,
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
out.push({ localIds: [...ids], kind: "text", patch, summary: summarize(patch) })
|
|
744
|
-
}
|
|
745
|
-
return out
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
/** Swap a local id for the server's in a marked document (after a flush). */
|
|
749
|
-
export function replaceSuggestionId(blocks: Block[], from: string, to: string): Block[] {
|
|
750
|
-
const swap = (marks?: Mark[]) =>
|
|
751
|
-
marks?.map((m) => ((m.type === "insertion" || m.type === "deletion") && m.suggestionId === from ? { ...m, suggestionId: to } : m))
|
|
752
|
-
const walk = (list: Block[]): Block[] =>
|
|
753
|
-
list.map((b) => {
|
|
754
|
-
let next: Block = b.suggestion?.id === from ? { ...b, suggestion: { ...b.suggestion, id: to } } : b
|
|
755
|
-
if (hasContent(next)) {
|
|
756
|
-
next = { ...next, content: next.content.map((r) => (r.type === "text" || r.type === "field" ? { ...r, marks: swap(r.marks) } : r)) } as Block
|
|
757
|
-
}
|
|
758
|
-
if (next.type === "toggle") next = { ...next, children: walk(next.children) }
|
|
759
|
-
if (next.type === "columns") next = { ...next, columns: [walk(next.columns[0]), walk(next.columns[1])] }
|
|
760
|
-
return next
|
|
761
|
-
})
|
|
762
|
-
return walk(blocks)
|
|
763
|
-
}
|
|
1
|
+
import type { Block, Inline, Mark } from "./contract"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Suggestions as patches (IMPLEMENTATION-NOTES 3.3, editor M5), and the two
|
|
5
|
+
* directions between a draft and what the editor shows. Pure: no React, no
|
|
6
|
+
* ProseMirror, only the contract's blocks.
|
|
7
|
+
*
|
|
8
|
+
* - `renderSuggestions(draft, suggestions)` draws open suggestions onto the
|
|
9
|
+
* draft: a `replace-text` patch's matched text gets the `deletion` mark and
|
|
10
|
+
* its insert follows with the `insertion` mark; inserted and deleted blocks
|
|
11
|
+
* get the block `suggestion` attr; a `format` patch is returned as a range to
|
|
12
|
+
* underline, since the contract has no mark for it.
|
|
13
|
+
* - `suggestEdit(before, after, …)` is Suggesting mode: given the blocks before
|
|
14
|
+
* and after an ordinary edit, it returns the blocks with that edit expressed
|
|
15
|
+
* as local suggestion marks (deleted text stays, struck through; typed text
|
|
16
|
+
* is marked inserted; deleting your own pending insertion just removes it),
|
|
17
|
+
* plus any formatting change as a pending format edit.
|
|
18
|
+
* - `collectPatches(blocks, formats, isLocal)` is the flush: every local
|
|
19
|
+
* change, grouped per block and region, as a patch to POST.
|
|
20
|
+
* - `stripSuggestions(blocks)` is the draft again: what Editing saves.
|
|
21
|
+
*
|
|
22
|
+
* Text is matched within a block's flattened inline text (`flatText`), as the
|
|
23
|
+
* server does (DocumentSuggestionPatch): text runs as they are, and each field,
|
|
24
|
+
* line break or formula as the one character U+FFFC. The occurrence-th match
|
|
25
|
+
* is the occurrence-th start position, scanning one character at a time.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/* ---------------------------------------------------------------- Patches */
|
|
29
|
+
|
|
30
|
+
export type SuggestionPatch =
|
|
31
|
+
| { op: "insert-blocks"; afterBlockId: string | null; blocks: Block[] }
|
|
32
|
+
| {
|
|
33
|
+
op: "replace-text"
|
|
34
|
+
blockId: string
|
|
35
|
+
deleteText: string
|
|
36
|
+
insert: Inline[]
|
|
37
|
+
occurrence: number
|
|
38
|
+
/** Pure insertions only: up to 40 characters of the block's text just before the insertion point. */
|
|
39
|
+
before?: string
|
|
40
|
+
}
|
|
41
|
+
| { op: "format"; blockId: string; deleteText: ""; text: string; occurrence: number; mark: Mark; add: boolean }
|
|
42
|
+
| { op: "delete-blocks"; blockIds: string[] }
|
|
43
|
+
| { op: "move-block"; blockId: string; afterBlockId: string | null }
|
|
44
|
+
|
|
45
|
+
export type SuggestionKind = "text" | "format" | "block"
|
|
46
|
+
|
|
47
|
+
/** What rendering needs of an open suggestion. */
|
|
48
|
+
export interface PatchedSuggestion {
|
|
49
|
+
id: string
|
|
50
|
+
patch: SuggestionPatch
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A pending formatting change, by character offsets in the (marked) block. */
|
|
54
|
+
export interface FormatEdit {
|
|
55
|
+
id: string
|
|
56
|
+
blockId: string
|
|
57
|
+
from: number
|
|
58
|
+
to: number
|
|
59
|
+
mark: Mark
|
|
60
|
+
add: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One local change ready to POST: the local ids it replaces once the server answers. */
|
|
64
|
+
export interface LocalChange {
|
|
65
|
+
localIds: string[]
|
|
66
|
+
kind: SuggestionKind
|
|
67
|
+
summary: string
|
|
68
|
+
patch: SuggestionPatch
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const BEFORE_CHARS = 40
|
|
72
|
+
const OBJECT = String.fromCharCode(0xfffc)
|
|
73
|
+
const FORMAT_MARKS = new Set(["bold", "italic", "underline", "strike", "code", "link", "highlight"])
|
|
74
|
+
|
|
75
|
+
/* ------------------------------------------------------------------ Cells */
|
|
76
|
+
|
|
77
|
+
/** One character of a block's inline content, with its marks. */
|
|
78
|
+
interface Cell {
|
|
79
|
+
ch: string
|
|
80
|
+
/** For a break, field or formula: the inline itself (marks aside). */
|
|
81
|
+
atom?: Inline
|
|
82
|
+
marks: Mark[]
|
|
83
|
+
/** Transient: format suggestions covering this character. */
|
|
84
|
+
fmt?: string[]
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function marksOf(run: Inline): Mark[] {
|
|
88
|
+
return run.type === "text" || run.type === "field" ? (run.marks ?? []) : []
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function toCells(content: Inline[]): Cell[] {
|
|
92
|
+
const cells: Cell[] = []
|
|
93
|
+
for (const run of content) {
|
|
94
|
+
if (run.type === "text") {
|
|
95
|
+
// One cell per UTF-16 unit, so offsets match ProseMirror's positions.
|
|
96
|
+
for (let i = 0; i < run.text.length; i++) cells.push({ ch: run.text[i], marks: run.marks ?? [] })
|
|
97
|
+
} else {
|
|
98
|
+
const { marks: _m, ...atom } = run as Inline & { marks?: Mark[] }
|
|
99
|
+
cells.push({ ch: OBJECT, atom: atom as Inline, marks: marksOf(run) })
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return cells
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const markKey = (m: Mark) => JSON.stringify(m)
|
|
106
|
+
const sameMarkList = (a: Mark[], b: Mark[]) => a.length === b.length && a.every((m, i) => markKey(m) === markKey(b[i]))
|
|
107
|
+
|
|
108
|
+
const ORDER = ["link", "bold", "italic", "underline", "strike", "code", "highlight", "comment", "insertion", "deletion", "perDocument"]
|
|
109
|
+
const sortMarks = (marks: Mark[]) => [...marks].sort((a, b) => ORDER.indexOf(a.type) - ORDER.indexOf(b.type))
|
|
110
|
+
|
|
111
|
+
function fromCells(cells: Cell[]): Inline[] {
|
|
112
|
+
const out: Inline[] = []
|
|
113
|
+
for (const c of cells) {
|
|
114
|
+
const marks = sortMarks(c.marks)
|
|
115
|
+
if (c.atom) {
|
|
116
|
+
const run = { ...c.atom } as Inline
|
|
117
|
+
if ((run.type === "field" || run.type === "text") && marks.length) (run as { marks?: Mark[] }).marks = marks
|
|
118
|
+
out.push(run)
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
const last = out[out.length - 1]
|
|
122
|
+
if (last && last.type === "text" && sameMarkList(last.marks ?? [], marks)) last.text += c.ch
|
|
123
|
+
else {
|
|
124
|
+
const run: Inline = { type: "text", text: c.ch }
|
|
125
|
+
if (marks.length) run.marks = marks
|
|
126
|
+
out.push(run)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out.filter((r) => r.type !== "text" || r.text !== "")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const insertionOf = (c: Cell) => c.marks.find((m) => m.type === "insertion") as { suggestionId: string } | undefined
|
|
133
|
+
const deletionOf = (c: Cell) => c.marks.find((m) => m.type === "deletion") as { suggestionId: string } | undefined
|
|
134
|
+
const isBase = (c: Cell) => !insertionOf(c)
|
|
135
|
+
const withoutSuggestionMarks = (marks: Mark[]) => marks.filter((m) => m.type !== "insertion" && m.type !== "deletion")
|
|
136
|
+
const formatting = (marks: Mark[]) => marks.filter((m) => FORMAT_MARKS.has(m.type))
|
|
137
|
+
|
|
138
|
+
/** A block's inline text as patches match it. */
|
|
139
|
+
export function flatText(content: Inline[]): string {
|
|
140
|
+
return toCells(content)
|
|
141
|
+
.map((c) => c.ch)
|
|
142
|
+
.join("")
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The draft's text of a marked block: everything but suggested insertions. */
|
|
146
|
+
export function baseText(content: Inline[]): string {
|
|
147
|
+
return toCells(content)
|
|
148
|
+
.filter(isBase)
|
|
149
|
+
.map((c) => c.ch)
|
|
150
|
+
.join("")
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** How many matches of `needle` start before `limit` (every start position counts, overlapping or not). */
|
|
154
|
+
export function countMatches(haystack: string, needle: string, limit: number): number {
|
|
155
|
+
if (!needle) return 0
|
|
156
|
+
let n = 0
|
|
157
|
+
for (let i = haystack.indexOf(needle); i >= 0 && i < limit; i = haystack.indexOf(needle, i + 1)) n++
|
|
158
|
+
return n
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The start of the occurrence-th match (0-based), or -1. */
|
|
162
|
+
export function nthMatch(haystack: string, needle: string, occurrence: number): number {
|
|
163
|
+
if (!needle) return -1
|
|
164
|
+
let i = haystack.indexOf(needle)
|
|
165
|
+
for (let n = 0; i >= 0 && n < occurrence; n++) i = haystack.indexOf(needle, i + 1)
|
|
166
|
+
return i
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* ----------------------------------------------------------------- Blocks */
|
|
170
|
+
|
|
171
|
+
type Content = { content: Inline[] }
|
|
172
|
+
const hasContent = (b: Block): b is Block & Content => "content" in b && Array.isArray((b as Partial<Content>).content)
|
|
173
|
+
|
|
174
|
+
/** Every block list in a document: the top level, toggles' children and both columns. */
|
|
175
|
+
function eachList(blocks: Block[], visit: (list: Block[]) => void) {
|
|
176
|
+
visit(blocks)
|
|
177
|
+
for (const b of blocks) {
|
|
178
|
+
if (b.type === "toggle") eachList(b.children, visit)
|
|
179
|
+
if (b.type === "columns") b.columns.forEach((col) => eachList(col, visit))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function findBlock(blocks: Block[], id: string): { list: Block[]; index: number } | null {
|
|
184
|
+
let found: { list: Block[]; index: number } | null = null
|
|
185
|
+
eachList(blocks, (list) => {
|
|
186
|
+
if (found) return
|
|
187
|
+
const index = list.findIndex((b) => b.id === id)
|
|
188
|
+
if (index >= 0) found = { list, index }
|
|
189
|
+
})
|
|
190
|
+
return found
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T
|
|
194
|
+
|
|
195
|
+
/** Blocks without any suggestion attr or mark: what goes into a patch or the draft. */
|
|
196
|
+
function cleanBlock(block: Block): Block {
|
|
197
|
+
const { suggestion: _s, ...rest } = block
|
|
198
|
+
const b = rest as Block
|
|
199
|
+
if (hasContent(b)) (b as Content).content = fromCells(toCells(b.content).map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) })))
|
|
200
|
+
if (b.type === "toggle") b.children = b.children.map(cleanBlock)
|
|
201
|
+
if (b.type === "columns") b.columns = [b.columns[0].map(cleanBlock), b.columns[1].map(cleanBlock)]
|
|
202
|
+
return b
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The draft from a marked document: suggested insertions and inserted blocks
|
|
207
|
+
* removed, deletion marks dropped (their text is still the draft's), block
|
|
208
|
+
* suggestion attrs cleared. What Editing saves (the server refuses marks in a draft).
|
|
209
|
+
*/
|
|
210
|
+
export function stripSuggestions(blocks: Block[]): Block[] {
|
|
211
|
+
const out: Block[] = []
|
|
212
|
+
for (const block of blocks) {
|
|
213
|
+
if (block.suggestion?.action === "insert") continue
|
|
214
|
+
const { suggestion: _s, ...rest } = block
|
|
215
|
+
const b = rest as Block
|
|
216
|
+
if (hasContent(b)) {
|
|
217
|
+
;(b as Content).content = fromCells(
|
|
218
|
+
toCells(b.content)
|
|
219
|
+
.filter(isBase)
|
|
220
|
+
.map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) }))
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
if (b.type === "toggle") b.children = stripSuggestions(b.children)
|
|
224
|
+
if (b.type === "columns") b.columns = [stripSuggestions(b.columns[0]), stripSuggestions(b.columns[1])]
|
|
225
|
+
out.push(b)
|
|
226
|
+
}
|
|
227
|
+
return out
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** True when a document has anything `stripSuggestions` would take out. */
|
|
231
|
+
export function hasSuggestionMarks(blocks: Block[]): boolean {
|
|
232
|
+
let found = false
|
|
233
|
+
eachList(blocks, (list) => {
|
|
234
|
+
for (const b of list) {
|
|
235
|
+
if (b.suggestion) found = true
|
|
236
|
+
if (hasContent(b) && toCells(b.content).some((c) => insertionOf(c) || deletionOf(c))) found = true
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
return found
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/* -------------------------------------------------------------- Rendering */
|
|
243
|
+
|
|
244
|
+
export interface RenderedFormat {
|
|
245
|
+
suggestionId: string
|
|
246
|
+
blockId: string
|
|
247
|
+
/** Character offsets in the rendered block. */
|
|
248
|
+
from: number
|
|
249
|
+
to: number
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export interface Rendered {
|
|
253
|
+
blocks: Block[]
|
|
254
|
+
/** Format suggestions: ranges to underline (dashed). */
|
|
255
|
+
formats: RenderedFormat[]
|
|
256
|
+
/** Suggestions whose anchor wasn't found in this draft (stale on the server's next accept). */
|
|
257
|
+
unplaced: string[]
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Draws open suggestions onto a draft, in the order given (the server's id order). */
|
|
261
|
+
export function renderSuggestions(draft: Block[], suggestions: PatchedSuggestion[]): Rendered {
|
|
262
|
+
const blocks = clone(draft)
|
|
263
|
+
const unplaced: string[] = []
|
|
264
|
+
const cellsById = new Map<string, Cell[]>()
|
|
265
|
+
const cellsOf = (id: string): Cell[] | null => {
|
|
266
|
+
if (cellsById.has(id)) return cellsById.get(id)!
|
|
267
|
+
const at = findBlock(blocks, id)
|
|
268
|
+
if (!at) return null
|
|
269
|
+
const block = at.list[at.index]
|
|
270
|
+
if (!hasContent(block)) return null
|
|
271
|
+
const cells = toCells(block.content)
|
|
272
|
+
cellsById.set(id, cells)
|
|
273
|
+
return cells
|
|
274
|
+
}
|
|
275
|
+
/** The cell index of the base character at `offset` (or the end). */
|
|
276
|
+
const cellAt = (cells: Cell[], offset: number) => {
|
|
277
|
+
let n = 0
|
|
278
|
+
for (let i = 0; i < cells.length; i++) {
|
|
279
|
+
if (!isBase(cells[i])) continue
|
|
280
|
+
if (n === offset) return i
|
|
281
|
+
n++
|
|
282
|
+
}
|
|
283
|
+
return cells.length
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
for (const s of suggestions) {
|
|
287
|
+
const p = s.patch
|
|
288
|
+
if (p.op === "replace-text") {
|
|
289
|
+
const cells = cellsOf(p.blockId)
|
|
290
|
+
if (!cells) {
|
|
291
|
+
unplaced.push(s.id)
|
|
292
|
+
continue
|
|
293
|
+
}
|
|
294
|
+
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
295
|
+
let start: number
|
|
296
|
+
if (p.deleteText) start = nthMatch(base, p.deleteText, p.occurrence)
|
|
297
|
+
else if (!p.before) start = 0
|
|
298
|
+
else {
|
|
299
|
+
const at = nthMatch(base, p.before, p.occurrence)
|
|
300
|
+
start = at < 0 ? -1 : at + p.before.length
|
|
301
|
+
}
|
|
302
|
+
if (start < 0) {
|
|
303
|
+
unplaced.push(s.id)
|
|
304
|
+
continue
|
|
305
|
+
}
|
|
306
|
+
const from = cellAt(cells, start)
|
|
307
|
+
const to = p.deleteText ? cellAt(cells, start + p.deleteText.length - 1) + 1 : from
|
|
308
|
+
// Two suggestions deleting the same text can't both show; the later one waits.
|
|
309
|
+
if (cells.slice(from, to).some((c) => deletionOf(c))) {
|
|
310
|
+
unplaced.push(s.id)
|
|
311
|
+
continue
|
|
312
|
+
}
|
|
313
|
+
for (let i = from; i < to; i++) if (isBase(cells[i])) cells[i] = { ...cells[i], marks: [...cells[i].marks, { type: "deletion", suggestionId: s.id }] }
|
|
314
|
+
const inserted = toCells(p.insert).map((c) => ({ ...c, marks: [...withoutSuggestionMarks(c.marks), { type: "insertion" as const, suggestionId: s.id }] }))
|
|
315
|
+
cells.splice(to, 0, ...inserted)
|
|
316
|
+
} else if (p.op === "format") {
|
|
317
|
+
const cells = cellsOf(p.blockId)
|
|
318
|
+
const base = cells ? cells.filter(isBase).map((c) => c.ch).join("") : ""
|
|
319
|
+
const start = cells ? nthMatch(base, p.text, p.occurrence) : -1
|
|
320
|
+
if (!cells || start < 0) {
|
|
321
|
+
unplaced.push(s.id)
|
|
322
|
+
continue
|
|
323
|
+
}
|
|
324
|
+
const from = cellAt(cells, start)
|
|
325
|
+
const to = cellAt(cells, start + p.text.length - 1) + 1
|
|
326
|
+
for (let i = from; i < to; i++) if (isBase(cells[i])) cells[i] = { ...cells[i], fmt: [...(cells[i].fmt ?? []), s.id] }
|
|
327
|
+
} else if (p.op === "insert-blocks") {
|
|
328
|
+
const added = p.blocks.map((b) => ({ ...cleanBlock(clone(b)), suggestion: { id: s.id, action: "insert" as const } }))
|
|
329
|
+
if (p.afterBlockId === null) {
|
|
330
|
+
blocks.unshift(...added)
|
|
331
|
+
continue
|
|
332
|
+
}
|
|
333
|
+
const at = findBlock(blocks, p.afterBlockId)
|
|
334
|
+
if (!at) {
|
|
335
|
+
unplaced.push(s.id)
|
|
336
|
+
continue
|
|
337
|
+
}
|
|
338
|
+
// After the anchor and after any blocks other suggestions already inserted there.
|
|
339
|
+
let i = at.index + 1
|
|
340
|
+
while (i < at.list.length && at.list[i].suggestion?.action === "insert") i++
|
|
341
|
+
at.list.splice(i, 0, ...added)
|
|
342
|
+
} else if (p.op === "delete-blocks" || p.op === "move-block") {
|
|
343
|
+
const ids = p.op === "delete-blocks" ? p.blockIds : [p.blockId]
|
|
344
|
+
const places = ids.map((id) => findBlock(blocks, id))
|
|
345
|
+
if (places.some((at) => !at || at.list[at.index].suggestion)) {
|
|
346
|
+
unplaced.push(s.id)
|
|
347
|
+
continue
|
|
348
|
+
}
|
|
349
|
+
for (const at of places) {
|
|
350
|
+
const b = at!.list[at!.index]
|
|
351
|
+
at!.list[at!.index] = { ...b, suggestion: { id: s.id, action: p.op === "delete-blocks" ? "delete" : "move" } }
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const formats: RenderedFormat[] = []
|
|
357
|
+
eachList(blocks, (list) => {
|
|
358
|
+
list.forEach((block, index) => {
|
|
359
|
+
const cells = cellsById.get(block.id)
|
|
360
|
+
if (!cells || !hasContent(block)) return
|
|
361
|
+
for (let i = 0; i < cells.length; i++) {
|
|
362
|
+
for (const id of cells[i].fmt ?? []) {
|
|
363
|
+
if (i > 0 && cells[i - 1].fmt?.includes(id)) continue
|
|
364
|
+
let j = i
|
|
365
|
+
while (j < cells.length && (cells[j].fmt?.includes(id) || !isBase(cells[j]))) j++
|
|
366
|
+
while (j > i && !cells[j - 1].fmt?.includes(id)) j--
|
|
367
|
+
formats.push({ suggestionId: id, blockId: block.id, from: i, to: j })
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
list[index] = { ...block, content: fromCells(cells) } as Block
|
|
371
|
+
})
|
|
372
|
+
})
|
|
373
|
+
return { blocks, formats, unplaced }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/* ------------------------------------------------------- Suggesting mode */
|
|
377
|
+
|
|
378
|
+
export interface SuggestEditOptions {
|
|
379
|
+
/** The id local changes made by this edit get. */
|
|
380
|
+
localId: string
|
|
381
|
+
/** Whether a suggestion id is one of this person's pending (unsent) changes. */
|
|
382
|
+
isLocal: (id: string) => boolean
|
|
383
|
+
/**
|
|
384
|
+
* Where the caret was before the edit (block id and character offset), so a
|
|
385
|
+
* Backspace over text leaves the caret before the struck-through text.
|
|
386
|
+
*/
|
|
387
|
+
caretBefore?: { blockId: string; offset: number } | null
|
|
388
|
+
/** Where the caret is after the edit, to map into the result. */
|
|
389
|
+
caretAfter?: { blockId: string; offset: number } | null
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export interface SuggestEditResult {
|
|
393
|
+
blocks: Block[]
|
|
394
|
+
/** New pending format edits (offsets in the resulting blocks). */
|
|
395
|
+
formats: FormatEdit[]
|
|
396
|
+
/** The caret in the result, when `caretAfter` was given. */
|
|
397
|
+
caret: { blockId: string; offset: number } | null
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const asJson = (v: unknown) => JSON.stringify(v)
|
|
401
|
+
const sameBlockShape = (a: Block, b: Block) => {
|
|
402
|
+
const { content: _a, suggestion: _sa, ...ra } = a as Block & Partial<Content>
|
|
403
|
+
const { content: _b, suggestion: _sb, ...rb } = b as Block & Partial<Content>
|
|
404
|
+
return asJson(ra) === asJson(rb)
|
|
405
|
+
}
|
|
406
|
+
const cellKey = (c: Cell) => `${c.ch}|${c.atom ? asJson(c.atom) : ""}|${insertionOf(c)?.suggestionId ?? ""}|${deletionOf(c)?.suggestionId ?? ""}`
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Suggesting mode for one edit. `before` and `after` are the same stretch of
|
|
410
|
+
* sibling blocks (the editor passes the blocks the edit touched). Returns null
|
|
411
|
+
* when the edit can't be expressed as a suggestion yet (see the limits in
|
|
412
|
+
* README), so the editor refuses it.
|
|
413
|
+
*/
|
|
414
|
+
export function suggestEdit(before: Block[], after: Block[], opts: SuggestEditOptions): SuggestEditResult | null {
|
|
415
|
+
const { localId, isLocal } = opts
|
|
416
|
+
const oldIndex = new Map(before.map((b, i) => [b.id, i]))
|
|
417
|
+
const newIds = new Set(after.map((b) => b.id).filter(Boolean))
|
|
418
|
+
const out: Block[] = []
|
|
419
|
+
const formats: FormatEdit[] = []
|
|
420
|
+
let caret: SuggestEditResult["caret"] = null
|
|
421
|
+
let pointer = 0
|
|
422
|
+
|
|
423
|
+
const emitRemoved = (upTo: number) => {
|
|
424
|
+
for (; pointer < upTo; pointer++) {
|
|
425
|
+
const old = before[pointer]
|
|
426
|
+
if (newIds.has(old.id)) return false
|
|
427
|
+
if (old.suggestion?.action === "insert") {
|
|
428
|
+
// Your own pending block goes; someone else's suggestion stays until it's decided.
|
|
429
|
+
if (isLocal(old.suggestion.id)) continue
|
|
430
|
+
out.push(old)
|
|
431
|
+
continue
|
|
432
|
+
}
|
|
433
|
+
out.push(old.suggestion ? old : { ...old, suggestion: { id: localId, action: "delete" } })
|
|
434
|
+
}
|
|
435
|
+
return true
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
for (const nb of after) {
|
|
439
|
+
const idx = nb.id ? oldIndex.get(nb.id) : undefined
|
|
440
|
+
if (idx === undefined) {
|
|
441
|
+
// A new block: a whole-block insertion, its text unmarked inside it.
|
|
442
|
+
const added = { ...cleanBlock(nb), suggestion: { id: localId, action: "insert" as const } }
|
|
443
|
+
out.push(added)
|
|
444
|
+
if (opts.caretAfter && opts.caretAfter.blockId === nb.id) caret = opts.caretAfter
|
|
445
|
+
continue
|
|
446
|
+
}
|
|
447
|
+
if (idx < pointer) return null // moved: move suggestions aren't made from the editor yet
|
|
448
|
+
if (!emitRemoved(idx)) return null
|
|
449
|
+
pointer = idx + 1
|
|
450
|
+
const old = before[idx]
|
|
451
|
+
const diffed = diffBlock(old, nb, opts, formats, (c) => (caret = c))
|
|
452
|
+
if (!diffed) return null
|
|
453
|
+
out.push(diffed)
|
|
454
|
+
}
|
|
455
|
+
if (!emitRemoved(before.length)) return null
|
|
456
|
+
return { blocks: out, formats, caret }
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function diffBlock(
|
|
460
|
+
old: Block,
|
|
461
|
+
nb: Block,
|
|
462
|
+
opts: SuggestEditOptions,
|
|
463
|
+
formats: FormatEdit[],
|
|
464
|
+
setCaret: (c: { blockId: string; offset: number }) => void
|
|
465
|
+
): Block | null {
|
|
466
|
+
const { isLocal } = opts
|
|
467
|
+
const caretHere = opts.caretAfter && opts.caretAfter.blockId === nb.id ? opts.caretAfter.offset : null
|
|
468
|
+
if (asJson(old) === asJson(nb)) {
|
|
469
|
+
if (caretHere !== null) setCaret({ blockId: nb.id, offset: caretHere })
|
|
470
|
+
return old
|
|
471
|
+
}
|
|
472
|
+
// Your own inserted block is yours to change freely until it's sent.
|
|
473
|
+
if (old.suggestion?.action === "insert" && isLocal(old.suggestion.id)) {
|
|
474
|
+
if (caretHere !== null) setCaret({ blockId: nb.id, offset: caretHere })
|
|
475
|
+
return { ...cleanBlock(nb), suggestion: old.suggestion }
|
|
476
|
+
}
|
|
477
|
+
if (old.suggestion) return null // inside a suggested (inserted or struck) block of someone else
|
|
478
|
+
if (!hasContent(old) || !hasContent(nb) || old.type !== nb.type || !sameBlockShape(old, nb)) return null
|
|
479
|
+
|
|
480
|
+
const a = toCells(old.content)
|
|
481
|
+
const b = toCells(nb.content)
|
|
482
|
+
let p = 0
|
|
483
|
+
while (p < a.length && p < b.length && cellKey(a[p]) === cellKey(b[p])) p++
|
|
484
|
+
let s = 0
|
|
485
|
+
while (s < a.length - p && s < b.length - p && cellKey(a[a.length - 1 - s]) === cellKey(b[b.length - 1 - s])) s++
|
|
486
|
+
|
|
487
|
+
// "a b" + " " is ambiguous: the inserted (or deleted) run could sit anywhere it
|
|
488
|
+
// slides to. Put it where the caret says it happened.
|
|
489
|
+
const insLen = b.length - p - s
|
|
490
|
+
const delLen = a.length - p - s
|
|
491
|
+
const slide = (seq: Cell[], len: number, target: number) => {
|
|
492
|
+
let q = p
|
|
493
|
+
while (q > target && q > 0 && cellKey(seq[q - 1]) === cellKey(seq[q - 1 + len])) q--
|
|
494
|
+
return q
|
|
495
|
+
}
|
|
496
|
+
if (delLen === 0 && insLen > 0 && caretHere !== null && caretHere - insLen < p) {
|
|
497
|
+
p = slide(b, insLen, caretHere - insLen)
|
|
498
|
+
s = a.length - p
|
|
499
|
+
} else if (insLen === 0 && delLen > 0 && opts.caretBefore?.blockId === nb.id) {
|
|
500
|
+
const c = opts.caretBefore.offset
|
|
501
|
+
const target = c - delLen < p && c - delLen >= 0 ? c - delLen : c < p ? c : p
|
|
502
|
+
p = slide(a, delLen, target)
|
|
503
|
+
s = b.length - p
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// One run of changes keeps one id: typing on from your pending text extends it.
|
|
507
|
+
const near = [a[p - 1], ...a.slice(p, a.length - s), a[a.length - s]].filter(Boolean)
|
|
508
|
+
const reuse = near
|
|
509
|
+
.map((c) => (insertionOf(c) ?? deletionOf(c))?.suggestionId)
|
|
510
|
+
.find((id): id is string => !!id && isLocal(id))
|
|
511
|
+
const localId = reuse ?? opts.localId
|
|
512
|
+
|
|
513
|
+
const result: Cell[] = []
|
|
514
|
+
// Unchanged text: a formatting difference is a format suggestion, except in your own pending text.
|
|
515
|
+
const keep = (oc: Cell, nc: Cell) => {
|
|
516
|
+
const own = insertionOf(oc) && isLocal(insertionOf(oc)!.suggestionId)
|
|
517
|
+
if (own || sameMarkList(formatting(oc.marks), formatting(nc.marks))) return { ...oc, marks: own ? nc.marks : oc.marks }
|
|
518
|
+
return { ...oc, fmtChange: { from: formatting(oc.marks), to: formatting(nc.marks) } }
|
|
519
|
+
}
|
|
520
|
+
const prefix = a.slice(0, p).map((c, i) => keep(c, b[i]))
|
|
521
|
+
const suffix = a.slice(a.length - s).map((c, i) => keep(c, b[b.length - s + i]))
|
|
522
|
+
|
|
523
|
+
const removed = a.slice(p, a.length - s)
|
|
524
|
+
const kept: Cell[] = []
|
|
525
|
+
for (const c of removed) {
|
|
526
|
+
const ins = insertionOf(c)
|
|
527
|
+
if (ins && isLocal(ins.suggestionId)) continue // your own pending insertion: just removed
|
|
528
|
+
if (ins || deletionOf(c)) kept.push(c) // already a suggestion: stays as it is
|
|
529
|
+
else kept.push({ ...c, marks: [...c.marks, { type: "deletion", suggestionId: localId }] })
|
|
530
|
+
}
|
|
531
|
+
const added = b.slice(p, b.length - s).map((c) => ({ ...c, marks: [...withoutSuggestionMarks(c.marks), { type: "insertion" as const, suggestionId: localId }] }))
|
|
532
|
+
result.push(...prefix, ...kept, ...added, ...suffix)
|
|
533
|
+
|
|
534
|
+
// Format changes become pending format edits on the old text, grouped by mark and direction.
|
|
535
|
+
type Changed = Cell & { fmtChange?: { from: Mark[]; to: Mark[] } }
|
|
536
|
+
const changes = (result as Changed[]).map((c) => {
|
|
537
|
+
if (!c.fmtChange) return [] as { mark: Mark; add: boolean }[]
|
|
538
|
+
const fromKeys = new Set(c.fmtChange.from.map(markKey))
|
|
539
|
+
const toKeys = new Set(c.fmtChange.to.map(markKey))
|
|
540
|
+
return [
|
|
541
|
+
...c.fmtChange.to.filter((m) => !fromKeys.has(markKey(m))).map((mark) => ({ mark, add: true })),
|
|
542
|
+
...c.fmtChange.from.filter((m) => !toKeys.has(markKey(m))).map((mark) => ({ mark, add: false })),
|
|
543
|
+
]
|
|
544
|
+
})
|
|
545
|
+
const done = new Set<string>()
|
|
546
|
+
changes.forEach((list, i) => {
|
|
547
|
+
for (const ch of list) {
|
|
548
|
+
const key = `${markKey(ch.mark)}|${ch.add}|${i}`
|
|
549
|
+
if (done.has(key)) continue
|
|
550
|
+
let j = i
|
|
551
|
+
while (j < changes.length && changes[j].some((x) => x.add === ch.add && markKey(x.mark) === markKey(ch.mark))) {
|
|
552
|
+
done.add(`${markKey(ch.mark)}|${ch.add}|${j}`)
|
|
553
|
+
j++
|
|
554
|
+
}
|
|
555
|
+
formats.push({ id: localId, blockId: nb.id, from: i, to: j, mark: ch.mark, add: ch.add })
|
|
556
|
+
}
|
|
557
|
+
})
|
|
558
|
+
for (const c of result as Changed[]) delete c.fmtChange
|
|
559
|
+
|
|
560
|
+
if (caretHere !== null) {
|
|
561
|
+
const insEnd = p + added.length
|
|
562
|
+
let offset: number
|
|
563
|
+
if (caretHere <= p && !(caretHere === p && added.length)) {
|
|
564
|
+
// Backspace leaves the caret before the struck text; Delete and a range delete, after it.
|
|
565
|
+
const backspace = opts.caretBefore?.blockId === nb.id && opts.caretBefore.offset === a.length - s && removed.length > 0
|
|
566
|
+
offset = caretHere === p && !backspace ? p + kept.length : caretHere
|
|
567
|
+
} else if (caretHere <= insEnd) offset = caretHere + kept.length
|
|
568
|
+
else offset = caretHere - b.length + result.length
|
|
569
|
+
setCaret({ blockId: nb.id, offset })
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
return { ...nb, content: fromCells(result) } as Block
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/* ----------------------------------------------------------------- Flush */
|
|
576
|
+
|
|
577
|
+
export interface SummaryWords {
|
|
578
|
+
replace: string // "Replace {from} with {to}"
|
|
579
|
+
add: string // "Add {text}"
|
|
580
|
+
delete: string // "Delete {text}"
|
|
581
|
+
format: string // "Format {text}: {mark}"
|
|
582
|
+
unformat: string // "Remove {mark} from {text}"
|
|
583
|
+
addBlocks: string // "Add {n} blocks" / "Add {text}"
|
|
584
|
+
deleteBlocks: string
|
|
585
|
+
moveBlock: string
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
export const SUMMARY_EN: SummaryWords = {
|
|
589
|
+
replace: "Replace {from} with {to}",
|
|
590
|
+
add: "Add {text}",
|
|
591
|
+
delete: "Delete {text}",
|
|
592
|
+
format: "Make {text} {mark}",
|
|
593
|
+
unformat: "Remove {mark} from {text}",
|
|
594
|
+
addBlocks: "Add {text}",
|
|
595
|
+
deleteBlocks: "Delete {text}",
|
|
596
|
+
moveBlock: "Move {text}",
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const fillIn = (t: string, v: Record<string, string>) => t.replace(/\{(\w+)\}/g, (_, k: string) => v[k] ?? "")
|
|
600
|
+
const shorten = (t: string, n = 60) => (t.length > n ? `${t.slice(0, n - 1)}…` : t)
|
|
601
|
+
const inlineText = (content: Inline[]) => flatText(content).replace(/\uFFFC/g, "…")
|
|
602
|
+
|
|
603
|
+
function blockText(block: Block): string {
|
|
604
|
+
if (hasContent(block)) return inlineText(block.content)
|
|
605
|
+
if (block.type === "code") return block.text
|
|
606
|
+
if (block.type === "toggle") return inlineText(block.summary)
|
|
607
|
+
return block.type
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** The card's sentence for a patch ("Replace 30 days with 14 days"). */
|
|
611
|
+
export function summarize(patch: SuggestionPatch, words: SummaryWords = SUMMARY_EN, quote = (t: string) => `“${shorten(t)}”`): string {
|
|
612
|
+
switch (patch.op) {
|
|
613
|
+
case "replace-text": {
|
|
614
|
+
const ins = inlineText(patch.insert)
|
|
615
|
+
if (patch.deleteText && ins) return fillIn(words.replace, { from: quote(patch.deleteText), to: quote(ins) })
|
|
616
|
+
if (patch.deleteText) return fillIn(words.delete, { text: quote(patch.deleteText) })
|
|
617
|
+
return fillIn(words.add, { text: quote(ins) })
|
|
618
|
+
}
|
|
619
|
+
case "format":
|
|
620
|
+
return fillIn(patch.add ? words.format : words.unformat, { text: quote(patch.text), mark: patch.mark.type })
|
|
621
|
+
case "insert-blocks":
|
|
622
|
+
return fillIn(words.addBlocks, { text: quote(patch.blocks.map(blockText).join(" ").trim() || patch.blocks[0]?.type || "") })
|
|
623
|
+
case "delete-blocks":
|
|
624
|
+
return fillIn(words.deleteBlocks, { text: quote(patch.blockIds.join(", ")) })
|
|
625
|
+
case "move-block":
|
|
626
|
+
return fillIn(words.moveBlock, { text: quote(patch.blockId) })
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Every local change in a marked document as patches, grouped per block:
|
|
632
|
+
* consecutive inserted blocks are one `insert-blocks`, consecutive deleted
|
|
633
|
+
* ones one `delete-blocks`; within a text block each run of local marks is one
|
|
634
|
+
* `replace-text`; each pending format edit is one `format`.
|
|
635
|
+
*/
|
|
636
|
+
export function collectPatches(blocks: Block[], formats: FormatEdit[], isLocal: (id: string) => boolean): LocalChange[] {
|
|
637
|
+
const changes: LocalChange[] = []
|
|
638
|
+
const deletedText = new Map<string, string>()
|
|
639
|
+
|
|
640
|
+
eachList(blocks, (list) => {
|
|
641
|
+
let i = 0
|
|
642
|
+
while (i < list.length) {
|
|
643
|
+
const block = list[i]
|
|
644
|
+
const s = block.suggestion
|
|
645
|
+
if (s && isLocal(s.id) && (s.action === "insert" || s.action === "delete")) {
|
|
646
|
+
let j = i
|
|
647
|
+
while (j < list.length && list[j].suggestion?.action === s.action && isLocal(list[j].suggestion!.id)) j++
|
|
648
|
+
const group = list.slice(i, j)
|
|
649
|
+
const localIds = [...new Set(group.map((b) => b.suggestion!.id))]
|
|
650
|
+
if (s.action === "insert") {
|
|
651
|
+
// Anchored after the nearest block that is in the draft.
|
|
652
|
+
let k = i - 1
|
|
653
|
+
while (k >= 0 && list[k].suggestion?.action === "insert") k--
|
|
654
|
+
const patch: SuggestionPatch = { op: "insert-blocks", afterBlockId: k >= 0 ? list[k].id : null, blocks: group.map(cleanBlock) }
|
|
655
|
+
changes.push({ localIds, kind: "block", patch, summary: summarize(patch) })
|
|
656
|
+
} else {
|
|
657
|
+
const patch: SuggestionPatch = { op: "delete-blocks", blockIds: group.map((b) => b.id) }
|
|
658
|
+
group.forEach((b) => deletedText.set(b.id, blockText(b)))
|
|
659
|
+
changes.push({
|
|
660
|
+
localIds,
|
|
661
|
+
kind: "block",
|
|
662
|
+
patch,
|
|
663
|
+
summary: fillIn(SUMMARY_EN.deleteBlocks, { text: `“${shorten(group.map(blockText).join(" "))}”` }),
|
|
664
|
+
})
|
|
665
|
+
}
|
|
666
|
+
i = j
|
|
667
|
+
continue
|
|
668
|
+
}
|
|
669
|
+
if (!s && hasContent(block)) changes.push(...textChanges(block, isLocal))
|
|
670
|
+
i++
|
|
671
|
+
}
|
|
672
|
+
})
|
|
673
|
+
|
|
674
|
+
for (const f of formats) {
|
|
675
|
+
if (!isLocal(f.id)) continue
|
|
676
|
+
const at = findBlock(blocks, f.blockId)
|
|
677
|
+
const block = at?.list[at.index]
|
|
678
|
+
if (!block || !hasContent(block)) continue
|
|
679
|
+
const cells = toCells(block.content)
|
|
680
|
+
const baseBefore = cells.slice(0, f.from).filter(isBase).length
|
|
681
|
+
const text = cells.slice(f.from, f.to).filter(isBase).map((c) => c.ch).join("")
|
|
682
|
+
if (!text) continue
|
|
683
|
+
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
684
|
+
const patch: SuggestionPatch = {
|
|
685
|
+
op: "format",
|
|
686
|
+
blockId: block.id,
|
|
687
|
+
deleteText: "",
|
|
688
|
+
text,
|
|
689
|
+
occurrence: countMatches(base, text, baseBefore),
|
|
690
|
+
mark: f.mark,
|
|
691
|
+
add: f.add,
|
|
692
|
+
}
|
|
693
|
+
changes.push({ localIds: [f.id], kind: "format", patch, summary: summarize(patch) })
|
|
694
|
+
}
|
|
695
|
+
return changes
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function textChanges(block: Block & Content, isLocal: (id: string) => boolean): LocalChange[] {
|
|
699
|
+
const cells = toCells(block.content)
|
|
700
|
+
const base = cells.filter(isBase).map((c) => c.ch).join("")
|
|
701
|
+
const localOf = (c: Cell) => {
|
|
702
|
+
const m = insertionOf(c) ?? deletionOf(c)
|
|
703
|
+
return m && isLocal(m.suggestionId) ? m.suggestionId : null
|
|
704
|
+
}
|
|
705
|
+
const out: LocalChange[] = []
|
|
706
|
+
let baseOffset = 0
|
|
707
|
+
let i = 0
|
|
708
|
+
while (i < cells.length) {
|
|
709
|
+
if (!localOf(cells[i])) {
|
|
710
|
+
if (isBase(cells[i])) baseOffset++
|
|
711
|
+
i++
|
|
712
|
+
continue
|
|
713
|
+
}
|
|
714
|
+
const start = baseOffset
|
|
715
|
+
const ids = new Set<string>()
|
|
716
|
+
const del: Cell[] = []
|
|
717
|
+
const ins: Cell[] = []
|
|
718
|
+
while (i < cells.length && localOf(cells[i])) {
|
|
719
|
+
ids.add(localOf(cells[i])!)
|
|
720
|
+
if (insertionOf(cells[i])) ins.push(cells[i])
|
|
721
|
+
else {
|
|
722
|
+
del.push(cells[i])
|
|
723
|
+
baseOffset++
|
|
724
|
+
}
|
|
725
|
+
i++
|
|
726
|
+
}
|
|
727
|
+
const deleteText = del.map((c) => c.ch).join("")
|
|
728
|
+
const insert = fromCells(ins.map((c) => ({ ...c, marks: withoutSuggestionMarks(c.marks) })))
|
|
729
|
+
let patch: SuggestionPatch
|
|
730
|
+
if (deleteText) {
|
|
731
|
+
patch = { op: "replace-text", blockId: block.id, deleteText, insert, occurrence: countMatches(base, deleteText, start) }
|
|
732
|
+
} else {
|
|
733
|
+
const before = base.slice(Math.max(0, start - BEFORE_CHARS), start)
|
|
734
|
+
patch = {
|
|
735
|
+
op: "replace-text",
|
|
736
|
+
blockId: block.id,
|
|
737
|
+
deleteText: "",
|
|
738
|
+
insert,
|
|
739
|
+
before,
|
|
740
|
+
occurrence: before ? countMatches(base, before, start - before.length) : 0,
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
out.push({ localIds: [...ids], kind: "text", patch, summary: summarize(patch) })
|
|
744
|
+
}
|
|
745
|
+
return out
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** Swap a local id for the server's in a marked document (after a flush). */
|
|
749
|
+
export function replaceSuggestionId(blocks: Block[], from: string, to: string): Block[] {
|
|
750
|
+
const swap = (marks?: Mark[]) =>
|
|
751
|
+
marks?.map((m) => ((m.type === "insertion" || m.type === "deletion") && m.suggestionId === from ? { ...m, suggestionId: to } : m))
|
|
752
|
+
const walk = (list: Block[]): Block[] =>
|
|
753
|
+
list.map((b) => {
|
|
754
|
+
let next: Block = b.suggestion?.id === from ? { ...b, suggestion: { ...b.suggestion, id: to } } : b
|
|
755
|
+
if (hasContent(next)) {
|
|
756
|
+
next = { ...next, content: next.content.map((r) => (r.type === "text" || r.type === "field" ? { ...r, marks: swap(r.marks) } : r)) } as Block
|
|
757
|
+
}
|
|
758
|
+
if (next.type === "toggle") next = { ...next, children: walk(next.children) }
|
|
759
|
+
if (next.type === "columns") next = { ...next, columns: [walk(next.columns[0]), walk(next.columns[1])] }
|
|
760
|
+
return next
|
|
761
|
+
})
|
|
762
|
+
return walk(blocks)
|
|
763
|
+
}
|