@stll/docx-core 0.28.0 → 0.29.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.
- package/README.md +6 -1
- package/dist/{document-Bz9rYlJI.js → document-DdWrTPQY.js} +7 -1
- package/dist/{document-BtGS_I3E.d.ts → document-DrtmJ_hz.d.ts} +48 -3
- package/dist/docx_kernel_bg.wasm +0 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +170 -22
- package/dist/model/document.d.ts +2 -2
- package/dist/model/document.js +1 -1
- package/dist/ops/documentOps.d.ts +339 -28
- package/dist/ops/documentOps.js +2388 -342
- package/package.json +2 -2
package/dist/ops/documentOps.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../document-
|
|
1
|
+
import "../document-DdWrTPQY.js";
|
|
2
2
|
import { r as hasIllegalXmlCharacters } from "../xmlEscape-T-2DeGlS.js";
|
|
3
3
|
import { Result, TaggedError, panic } from "better-result";
|
|
4
4
|
//#region src/ops/equality.ts
|
|
@@ -37,11 +37,19 @@ const derivedFields = (entries) => entries.some(([key, value]) => key === "type"
|
|
|
37
37
|
const equalForStaleness = (left, right) => equal(left, right, derivedFields);
|
|
38
38
|
//#endregion
|
|
39
39
|
//#region src/ops/types.ts
|
|
40
|
-
/**
|
|
41
|
-
|
|
40
|
+
/**
|
|
41
|
+
* The operation schema this module reads and writes.
|
|
42
|
+
*
|
|
43
|
+
* Version 3 adds paragraph insertion through `insertBlocks` and the table-row
|
|
44
|
+
* operations `insertRow`, `deleteRow` and `setTableRows`.
|
|
45
|
+
* Version 2 added tracked changes: the `revision` stamp on the text, formatting
|
|
46
|
+
* and paragraph operations, and the review operations `setParagraphReview`,
|
|
47
|
+
* `replaceInline` and `resolveRevision`.
|
|
48
|
+
*/
|
|
49
|
+
const DOCUMENT_OP_SCHEMA_VERSION = 3;
|
|
42
50
|
/**
|
|
43
51
|
* The stories an operation can address. Headers, footers, notes and comment
|
|
44
|
-
* bodies are stories too; version
|
|
52
|
+
* bodies are stories too; this version addresses the main story only.
|
|
45
53
|
*/
|
|
46
54
|
const OP_STORIES = Object.freeze({ MAIN: "main" });
|
|
47
55
|
/**
|
|
@@ -58,8 +66,9 @@ const EMPTY_PROPERTY_SETS = Object.freeze({
|
|
|
58
66
|
* unit before the position, or the one after it at the start of a paragraph.
|
|
59
67
|
*/
|
|
60
68
|
const INHERIT_RUN_PROPS = "inherit";
|
|
61
|
-
/** The operation kinds of schema version
|
|
69
|
+
/** The operation kinds of schema version 3. */
|
|
62
70
|
const DOCUMENT_OP_TYPES = Object.freeze({
|
|
71
|
+
INSERT_BLOCKS: "insertBlocks",
|
|
63
72
|
INSERT_TEXT: "insertText",
|
|
64
73
|
INSERT_CONTENT: "insertContent",
|
|
65
74
|
DELETE_RANGE: "deleteRange",
|
|
@@ -69,11 +78,33 @@ const DOCUMENT_OP_TYPES = Object.freeze({
|
|
|
69
78
|
SET_PARAGRAPH_PROPS: "setParagraphProps",
|
|
70
79
|
SPLIT_BLOCK: "splitBlock",
|
|
71
80
|
JOIN_BLOCKS: "joinBlocks",
|
|
72
|
-
REPLACE_BLOCKS: "replaceBlocks"
|
|
81
|
+
REPLACE_BLOCKS: "replaceBlocks",
|
|
82
|
+
SET_PARAGRAPH_REVIEW: "setParagraphReview",
|
|
83
|
+
REPLACE_INLINE: "replaceInline",
|
|
84
|
+
RESOLVE_REVISION: "resolveRevision",
|
|
85
|
+
INSERT_ROW: "insertRow",
|
|
86
|
+
DELETE_ROW: "deleteRow",
|
|
87
|
+
SET_TABLE_ROWS: "setTableRows"
|
|
88
|
+
});
|
|
89
|
+
/**
|
|
90
|
+
* Paragraph formatting that belongs to the paragraph mark's run properties
|
|
91
|
+
* (`w:pPr/w:rPr`) rather than to the paragraph properties a `w:pPrChange`
|
|
92
|
+
* records.
|
|
93
|
+
*/
|
|
94
|
+
const PARAGRAPH_MARK_FORMATTING_KEYS = Object.freeze(["runProperties", "runInWithNext"]);
|
|
95
|
+
/** Which half of a split, or of a join, a rule applies to. */
|
|
96
|
+
const SPLIT_HALVES = Object.freeze({
|
|
97
|
+
FIRST: "first",
|
|
98
|
+
SECOND: "second"
|
|
99
|
+
});
|
|
100
|
+
/** What resolving a tracked change does with it. */
|
|
101
|
+
const REVISION_DECISIONS = Object.freeze({
|
|
102
|
+
ACCEPT: "accept",
|
|
103
|
+
REJECT: "reject"
|
|
73
104
|
});
|
|
74
105
|
/** An operation in the envelope it is journaled and sent in. */
|
|
75
106
|
const toOpEnvelope = (op) => ({
|
|
76
|
-
schema:
|
|
107
|
+
schema: 3,
|
|
77
108
|
op
|
|
78
109
|
});
|
|
79
110
|
//#endregion
|
|
@@ -109,6 +140,12 @@ const collectParagraphs = (blocks, list, out) => {
|
|
|
109
140
|
block: index
|
|
110
141
|
}], out);
|
|
111
142
|
break;
|
|
143
|
+
case "blockCustomXml":
|
|
144
|
+
collectParagraphs(block.content, [...list, {
|
|
145
|
+
kind: "blockCustomXml",
|
|
146
|
+
block: index
|
|
147
|
+
}], out);
|
|
148
|
+
break;
|
|
112
149
|
case "preservedBlock":
|
|
113
150
|
case "bookmarkStart":
|
|
114
151
|
case "bookmarkEnd": break;
|
|
@@ -132,6 +169,7 @@ const sameStep = (left, right) => {
|
|
|
132
169
|
switch (left.kind) {
|
|
133
170
|
case "tableCell": return right.kind === "tableCell" && left.block === right.block && left.row === right.row && left.cell === right.cell;
|
|
134
171
|
case "blockSdt": return right.kind === "blockSdt" && left.block === right.block;
|
|
172
|
+
case "blockCustomXml": return right.kind === "blockCustomXml" && left.block === right.block;
|
|
135
173
|
default: return left;
|
|
136
174
|
}
|
|
137
175
|
};
|
|
@@ -140,6 +178,48 @@ const sameBlockList = (left, right) => left.length === right.length && left.ever
|
|
|
140
178
|
const other = right[index];
|
|
141
179
|
return other !== void 0 && sameStep(step, other);
|
|
142
180
|
});
|
|
181
|
+
/** The block list a location's steps lead to. */
|
|
182
|
+
const blockListAt = (blocks, list) => {
|
|
183
|
+
let current = blocks;
|
|
184
|
+
for (const step of list) {
|
|
185
|
+
const block = current[step.block];
|
|
186
|
+
switch (step.kind) {
|
|
187
|
+
case "tableCell": {
|
|
188
|
+
const cell = block?.type === "table" ? block.rows[step.row]?.cells[step.cell] : void 0;
|
|
189
|
+
if (cell === void 0) return panic(`Block list step does not name a table cell at block ${step.block}.`);
|
|
190
|
+
current = cell.content;
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
case "blockSdt":
|
|
194
|
+
if (block?.type !== "blockSdt") return panic(`Block list step does not name a block content control at ${step.block}.`);
|
|
195
|
+
current = block.content;
|
|
196
|
+
break;
|
|
197
|
+
case "blockCustomXml":
|
|
198
|
+
if (block?.type !== "blockCustomXml") return panic(`Block list step does not name a custom XML wrapper at ${step.block}.`);
|
|
199
|
+
current = block.content;
|
|
200
|
+
break;
|
|
201
|
+
default: return step;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return current;
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* Whether a block is the last one of its story body or table cell. A block
|
|
208
|
+
* content control or custom XML wrapper is a step in the block list, not a
|
|
209
|
+
* container: the last block inside one ends the container only when the
|
|
210
|
+
* wrapper does.
|
|
211
|
+
*/
|
|
212
|
+
const endsItsContainer = (body, { list, index }) => {
|
|
213
|
+
let steps = list;
|
|
214
|
+
let position = index;
|
|
215
|
+
for (;;) {
|
|
216
|
+
if (position !== blockListAt(body.content, steps).length - 1) return false;
|
|
217
|
+
const last = steps.at(-1);
|
|
218
|
+
if (last === void 0 || last.kind === "tableCell") return true;
|
|
219
|
+
steps = steps.slice(0, -1);
|
|
220
|
+
position = last.block;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
143
223
|
const updateBlockList = (blocks, list, update) => {
|
|
144
224
|
const [step, ...rest] = list;
|
|
145
225
|
if (step === void 0) return update(blocks);
|
|
@@ -173,6 +253,13 @@ const updateBlockList = (blocks, list, update) => {
|
|
|
173
253
|
content: updateBlockList(block.content, rest, update)
|
|
174
254
|
};
|
|
175
255
|
return out;
|
|
256
|
+
case "blockCustomXml":
|
|
257
|
+
if (block?.type !== "blockCustomXml") return panic(`Block list step does not name a custom XML wrapper at ${step.block}.`);
|
|
258
|
+
out[step.block] = {
|
|
259
|
+
...block,
|
|
260
|
+
content: updateBlockList(block.content, rest, update)
|
|
261
|
+
};
|
|
262
|
+
return out;
|
|
176
263
|
default: return step;
|
|
177
264
|
}
|
|
178
265
|
};
|
|
@@ -358,7 +445,11 @@ const IDENTITY_SPACES = Object.freeze({
|
|
|
358
445
|
CONTROL: "control"
|
|
359
446
|
});
|
|
360
447
|
const slotKey = ({ space, id }) => `${space}:${id}`;
|
|
361
|
-
const revisionIdOf = (entries) => {
|
|
448
|
+
const revisionIdOf = (entries, heldBy) => {
|
|
449
|
+
if (heldBy === "gridChange" && Array.isArray(fieldOf(entries, "columnWidths"))) {
|
|
450
|
+
const id = fieldOf(entries, "id");
|
|
451
|
+
return typeof id === "number" ? id : void 0;
|
|
452
|
+
}
|
|
362
453
|
const info = fieldOf(entries, "info");
|
|
363
454
|
if (typeof info !== "object" || info === null) return void 0;
|
|
364
455
|
const infoEntries = Object.entries(info);
|
|
@@ -378,7 +469,7 @@ const identityKeysIn = (value) => {
|
|
|
378
469
|
const out = [];
|
|
379
470
|
const stacked = /* @__PURE__ */ new Map();
|
|
380
471
|
walk(value, (entries, heldBy) => {
|
|
381
|
-
const revision = revisionIdOf(entries);
|
|
472
|
+
const revision = revisionIdOf(entries, heldBy);
|
|
382
473
|
if (revision !== void 0) out.push(slotKey({
|
|
383
474
|
space: IDENTITY_SPACES.REVISION,
|
|
384
475
|
id: revision
|
|
@@ -556,6 +647,7 @@ const INLINE_SDT_CHILD_TYPES = {
|
|
|
556
647
|
preservedInline: true
|
|
557
648
|
};
|
|
558
649
|
const isHyperlinkChild = (item) => Object.hasOwn(HYPERLINK_CHILD_TYPES, item.type);
|
|
650
|
+
/** Whether a tracked change (`w:ins`, `w:del`, a move) can hold the record. */
|
|
559
651
|
const isTrackedChild = (item) => Object.hasOwn(TRACKED_CHILD_TYPES, item.type);
|
|
560
652
|
const isInlineSdtChild = (item) => Object.hasOwn(INLINE_SDT_CHILD_TYPES, item.type);
|
|
561
653
|
/**
|
|
@@ -744,13 +836,13 @@ const kindOf = (node) => {
|
|
|
744
836
|
return inlineWidth(node) === 1 ? "unit" : "zeroWidth";
|
|
745
837
|
};
|
|
746
838
|
/**
|
|
747
|
-
* Whether a
|
|
748
|
-
*
|
|
839
|
+
* Whether a text node, run, or revision wrapper holds nothing. Such records say
|
|
840
|
+
* nothing, operations never create one, and a document is normalized so it
|
|
749
841
|
* holds none (see `contract.ts`): otherwise each is a zero-width leaf that
|
|
750
842
|
* positions would have to count. An empty hyperlink or content control is
|
|
751
843
|
* not empty in this sense: it is markup, and stays a zero-width leaf.
|
|
752
844
|
*/
|
|
753
|
-
const isEmptyRecord = (node) => node.type === "text" && node.text === "" || node.type === "run" && node.content.length === 0;
|
|
845
|
+
const isEmptyRecord = (node) => node.type === "text" && node.text === "" || (node.type === "run" || node.type === "insertion" || node.type === "deletion" || node.type === "moveFrom" || node.type === "moveTo") && node.content.length === 0;
|
|
754
846
|
const startCursor = () => ({
|
|
755
847
|
position: 0,
|
|
756
848
|
zeroWidthSeen: 0
|
|
@@ -785,6 +877,7 @@ const rebuildNode = (node, children) => {
|
|
|
785
877
|
if (isRunContent(node) || !isInlineContainer(node)) return panic(`A ${node.type} has no children to rebuild.`);
|
|
786
878
|
return withChildren(node, narrowNodes(children, isParagraphContent));
|
|
787
879
|
};
|
|
880
|
+
/** A record's pieces between gaps, the cursor moved past it. */
|
|
788
881
|
const partitionNode = (node, gaps, cursor) => {
|
|
789
882
|
if (node.type === "text" && node.text !== "") {
|
|
790
883
|
const start = cursor.position;
|
|
@@ -1099,232 +1192,55 @@ const runGaps = (items) => {
|
|
|
1099
1192
|
walk(items);
|
|
1100
1193
|
return out;
|
|
1101
1194
|
};
|
|
1102
|
-
//#endregion
|
|
1103
|
-
//#region src/ops/refusal.ts
|
|
1104
|
-
/**
|
|
1105
|
-
* Why an operation was not applied. A refused operation changes nothing: the
|
|
1106
|
-
* document it was applied to is returned as it was.
|
|
1107
|
-
*/
|
|
1108
|
-
const DOCUMENT_OP_REFUSAL_REASONS = Object.freeze({
|
|
1109
|
-
/** No paragraph in the story carries the id. */
|
|
1110
|
-
BLOCK_NOT_FOUND: "blockNotFound",
|
|
1111
|
-
/** An offset is not an integer from `0` to the paragraph's length, or a range runs backwards. */
|
|
1112
|
-
INVALID_OFFSET: "invalidOffset",
|
|
1113
|
-
/** A range starts and ends in different paragraphs or stories. */
|
|
1114
|
-
CROSS_BLOCK_RANGE: "crossBlockRange",
|
|
1115
|
-
/** A position falls between the two halves of a surrogate pair. */
|
|
1116
|
-
SPLITS_SURROGATE_PAIR: "splitsSurrogatePair",
|
|
1117
|
-
/** Inserted text is empty, holds a tab or line-break character, or cannot be written to XML. */
|
|
1118
|
-
INVALID_TEXT: "invalidText",
|
|
1119
|
-
/**
|
|
1120
|
-
* A paragraph id the operation (or its inverse) creates is not eight hex
|
|
1121
|
-
* digits below `0x80000000`, or is the reserved `00000000`.
|
|
1122
|
-
*/
|
|
1123
|
-
INVALID_BLOCK_ID: "invalidBlockId",
|
|
1124
|
-
/**
|
|
1125
|
-
* An id the operation brings in (a paragraph id, or a revision or
|
|
1126
|
-
* content-control id a replacement carries) is already used in the package.
|
|
1127
|
-
*/
|
|
1128
|
-
ID_COLLISION: "idCollision",
|
|
1129
|
-
/** The paragraphs to join or replace are not adjacent siblings of one container. */
|
|
1130
|
-
NOT_ADJACENT: "notAdjacent",
|
|
1131
|
-
/**
|
|
1132
|
-
* The operation would move or remove a section break (joining a paragraph
|
|
1133
|
-
* that ends a section, replacing paragraphs across or at one); that is a
|
|
1134
|
-
* section operation.
|
|
1135
|
-
*/
|
|
1136
|
-
SECTION_BOUNDARY: "sectionBoundary",
|
|
1137
|
-
/** Direct text would land inside tracked-deleted or moved-away content. */
|
|
1138
|
-
INSIDE_TRACKED_DELETION: "insideTrackedDeletion",
|
|
1139
|
-
/**
|
|
1140
|
-
* The operation cuts a record carrying a revision or content-control id in
|
|
1141
|
-
* two and names too few `newIds` for the halves after the first.
|
|
1142
|
-
*/
|
|
1143
|
-
NEEDS_NEW_IDS: "needsNewIds",
|
|
1144
|
-
/** A new revision or content-control id is not an integer from 0 to 2^31 - 1. */
|
|
1145
|
-
INVALID_NEW_ID: "invalidNewId",
|
|
1146
|
-
/**
|
|
1147
|
-
* The operation would merge two records carrying the same revision or
|
|
1148
|
-
* content-control id: nothing could tell them apart again to undo it.
|
|
1149
|
-
*/
|
|
1150
|
-
SHARED_ID: "sharedId",
|
|
1151
|
-
/**
|
|
1152
|
-
* What the operation expects (paragraphs to replace, a slice to delete,
|
|
1153
|
-
* the values a patch replaced) is not what is there.
|
|
1154
|
-
*/
|
|
1155
|
-
STALE: "stale",
|
|
1156
|
-
/**
|
|
1157
|
-
* The records at a position are not the shape the operation needs: an open
|
|
1158
|
-
* end meets a record it cannot merge with, records to join differ, a slice
|
|
1159
|
-
* would merge records that were separate, or there are fewer records to cut
|
|
1160
|
-
* than the operation names.
|
|
1161
|
-
*/
|
|
1162
|
-
STRUCTURE_MISMATCH: "structureMismatch",
|
|
1163
|
-
/** Inserted content is empty, or holds an empty run or text node. */
|
|
1164
|
-
EMPTY_CONTENT: "emptyContent",
|
|
1165
|
-
/** A replacement names no paragraph to replace, or none to put in its place. */
|
|
1166
|
-
EMPTY_BLOCK_LIST: "emptyBlockList",
|
|
1167
|
-
/** Seed contract: a main-story paragraph has no `paraId`. */
|
|
1168
|
-
MISSING_BLOCK_ID: "missingBlockId",
|
|
1169
|
-
/** Seed contract: two paragraphs in the package carry one id. */
|
|
1170
|
-
DUPLICATE_BLOCK_ID: "duplicateBlockId",
|
|
1171
|
-
/** Seed contract: two records in the package carry one revision or content-control id. */
|
|
1172
|
-
DUPLICATE_RECORD_ID: "duplicateRecordId",
|
|
1173
|
-
/** Seed contract: the body's section view does not match its blocks. */
|
|
1174
|
-
SECTIONS_OUT_OF_STEP: "sectionsOutOfStep",
|
|
1175
|
-
/** Seed contract: the main story holds an empty run or empty text node. */
|
|
1176
|
-
EMPTY_RECORD: "emptyRecord"
|
|
1177
|
-
});
|
|
1178
|
-
/** An operation the document cannot take as stated. */
|
|
1179
|
-
var DocumentOpRefusal = class extends TaggedError("DocumentOpRefusal") {};
|
|
1180
|
-
//#endregion
|
|
1181
|
-
//#region src/ops/contract.ts
|
|
1182
1195
|
/**
|
|
1183
|
-
*
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
*
|
|
1187
|
-
* footers and notes included, and makes ids unique), parse, then
|
|
1188
|
-
* {@link normalizeForOps}. {@link validateOpsDocument} states the result:
|
|
1189
|
-
*
|
|
1190
|
-
* - every paragraph of the main story has a `w14:paraId`;
|
|
1191
|
-
* - no paragraph id repeats anywhere in the package, compared as hex, so an
|
|
1192
|
-
* inverse can always recreate the ids it removed;
|
|
1193
|
-
* - no revision id (tracked changes, property changes) or content-control id
|
|
1194
|
-
* repeats, so the one record carrying an id is the one it names;
|
|
1195
|
-
* - the body's section view says what its blocks say;
|
|
1196
|
-
* - the main story holds no empty run or empty text node.
|
|
1197
|
-
*
|
|
1198
|
-
* Paragraphs in text boxes, headers, footers, notes and comments are other
|
|
1199
|
-
* stories: they are not addressable in schema version 1, and their ids count
|
|
1200
|
-
* toward uniqueness like any other.
|
|
1201
|
-
*
|
|
1202
|
-
* Every operation checks the contract before applying and leaves it holding,
|
|
1203
|
-
* so a document an operation produced is not checked again: documents are
|
|
1204
|
-
* values, never modified in place.
|
|
1196
|
+
* How many levels the record ending `left` and the one starting `right` merge
|
|
1197
|
+
* before a pair differs: text with text, and records alike in everything but
|
|
1198
|
+
* their content and ids, down the chain of last and first children. `0` when
|
|
1199
|
+
* the two are not alike at all.
|
|
1205
1200
|
*/
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
const
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
});
|
|
1216
|
-
const repeated = [...countIds(packageParagraphIds(document.package))].find(([, count]) => count > 1);
|
|
1217
|
-
if (repeated !== void 0) return new DocumentOpsContractError({
|
|
1218
|
-
reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_BLOCK_ID,
|
|
1219
|
-
message: `${repeated[1]} paragraphs in the package are ${repeated[0]}.`
|
|
1220
|
-
});
|
|
1221
|
-
const repeatedRecord = [...countKeys(packageIdentityKeys(document.package))].find(([, count]) => count > 1);
|
|
1222
|
-
if (repeatedRecord !== void 0) return new DocumentOpsContractError({
|
|
1223
|
-
reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_RECORD_ID,
|
|
1224
|
-
message: `${repeatedRecord[1]} records in the package carry ${repeatedRecord[0]}.`
|
|
1225
|
-
});
|
|
1226
|
-
if (!sectionsInStep(body)) return new DocumentOpsContractError({
|
|
1227
|
-
reason: DOCUMENT_OP_REFUSAL_REASONS.SECTIONS_OUT_OF_STEP,
|
|
1228
|
-
message: "The body's section view does not match its blocks."
|
|
1229
|
-
});
|
|
1230
|
-
if (paragraphs.some(({ paragraph }) => holdsEmptyRecord$1(paragraph.content))) return new DocumentOpsContractError({
|
|
1231
|
-
reason: DOCUMENT_OP_REFUSAL_REASONS.EMPTY_RECORD,
|
|
1232
|
-
message: "The main story holds an empty run or text node; normalizeForOps removes them."
|
|
1233
|
-
});
|
|
1234
|
-
};
|
|
1235
|
-
/** Documents known to meet the contract: checked ones and ones an operation produced. */
|
|
1236
|
-
const MEETS_CONTRACT = /* @__PURE__ */ new WeakSet();
|
|
1237
|
-
/** Check a document against the seed contract. */
|
|
1238
|
-
const validateOpsDocument = (document) => {
|
|
1239
|
-
if (MEETS_CONTRACT.has(document)) return Result.ok(document);
|
|
1240
|
-
const found = violation(document);
|
|
1241
|
-
if (found !== void 0) return Result.err(found);
|
|
1242
|
-
MEETS_CONTRACT.add(document);
|
|
1243
|
-
return Result.ok(document);
|
|
1244
|
-
};
|
|
1245
|
-
/** Record that an operation produced `document` from one that met the contract. */
|
|
1246
|
-
const meetsContract = (document) => {
|
|
1247
|
-
MEETS_CONTRACT.add(document);
|
|
1248
|
-
};
|
|
1249
|
-
const withoutEmpty = (nodes) => {
|
|
1250
|
-
let changed = false;
|
|
1251
|
-
const out = [];
|
|
1252
|
-
for (const node of nodes) {
|
|
1253
|
-
if (isEmptyRecord(node)) {
|
|
1254
|
-
changed = true;
|
|
1255
|
-
continue;
|
|
1256
|
-
}
|
|
1257
|
-
const children = childNodes(node);
|
|
1258
|
-
const kept = children === void 0 ? children : withoutEmpty(children);
|
|
1259
|
-
if (kept !== children && kept !== void 0) {
|
|
1260
|
-
changed = true;
|
|
1261
|
-
const rebuilt = rebuildNode(node, kept);
|
|
1262
|
-
if (!isEmptyRecord(rebuilt)) out.push(rebuilt);
|
|
1263
|
-
continue;
|
|
1264
|
-
}
|
|
1265
|
-
out.push(node);
|
|
1266
|
-
}
|
|
1267
|
-
return changed ? out : nodes;
|
|
1201
|
+
const alikeDepth = (left, right) => {
|
|
1202
|
+
if (left === void 0 || right === void 0) return 0;
|
|
1203
|
+
const kind = kindOf(left);
|
|
1204
|
+
if (kind !== kindOf(right) || kind !== "characters" && kind !== "branch") return 0;
|
|
1205
|
+
if (left.type === "text" && right.type === "text") return 1;
|
|
1206
|
+
const leftChildren = childNodes(left);
|
|
1207
|
+
const rightChildren = childNodes(right);
|
|
1208
|
+
if (leftChildren === void 0 || rightChildren === void 0 || !sameOwnFields(left, right)) return 0;
|
|
1209
|
+
return 1 + alikeDepth(leftChildren.at(-1), rightChildren.at(0));
|
|
1268
1210
|
};
|
|
1269
|
-
|
|
1211
|
+
/** Two lists end to end, the records meeting there merged as far as they are alike. */
|
|
1212
|
+
const mergeAlike = (left, right) => mergeLists(left, right, alikeDepth(left.at(-1), right.at(0))) ?? panic("Records alike to a depth merge to that depth.");
|
|
1213
|
+
/** Every leaf of a list in document order: run text by text node, units, zero-width leaves. */
|
|
1214
|
+
const leafSpans = (items) => {
|
|
1270
1215
|
const out = [];
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
...
|
|
1276
|
-
|
|
1277
|
-
});
|
|
1278
|
-
break;
|
|
1279
|
-
}
|
|
1280
|
-
case "table": {
|
|
1281
|
-
const rows = [];
|
|
1282
|
-
for (const row of block.rows) {
|
|
1283
|
-
const cells = [];
|
|
1284
|
-
for (const cell of row.cells) cells.push({
|
|
1285
|
-
...cell,
|
|
1286
|
-
content: normalizeBlocks(cell.content)
|
|
1287
|
-
});
|
|
1288
|
-
rows.push({
|
|
1289
|
-
...row,
|
|
1290
|
-
cells
|
|
1291
|
-
});
|
|
1216
|
+
const cursor = startCursor();
|
|
1217
|
+
const walk = (list, ancestors) => {
|
|
1218
|
+
for (const node of list) {
|
|
1219
|
+
if (kindOf(node) === "branch") {
|
|
1220
|
+
walk(childNodes(node) ?? [], [...ancestors, node]);
|
|
1221
|
+
continue;
|
|
1292
1222
|
}
|
|
1223
|
+
const before = {
|
|
1224
|
+
offset: cursor.position,
|
|
1225
|
+
zeroWidthBefore: cursor.zeroWidthSeen
|
|
1226
|
+
};
|
|
1227
|
+
advance(node, cursor);
|
|
1293
1228
|
out.push({
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
...block,
|
|
1302
|
-
content: normalizeBlocks(block.content)
|
|
1229
|
+
node,
|
|
1230
|
+
ancestors,
|
|
1231
|
+
before,
|
|
1232
|
+
after: {
|
|
1233
|
+
offset: cursor.position,
|
|
1234
|
+
zeroWidthBefore: cursor.zeroWidthSeen
|
|
1235
|
+
}
|
|
1303
1236
|
});
|
|
1304
|
-
break;
|
|
1305
|
-
case "preservedBlock":
|
|
1306
|
-
case "bookmarkStart":
|
|
1307
|
-
case "bookmarkEnd":
|
|
1308
|
-
out.push(block);
|
|
1309
|
-
break;
|
|
1310
|
-
default: return block;
|
|
1311
|
-
}
|
|
1312
|
-
return out;
|
|
1313
|
-
};
|
|
1314
|
-
/**
|
|
1315
|
-
* The document with every empty run and empty text node of the main story
|
|
1316
|
-
* removed, and its section view derived again. Nothing else changes.
|
|
1317
|
-
*/
|
|
1318
|
-
const normalizeForOps = (document) => {
|
|
1319
|
-
const body = document.package.document;
|
|
1320
|
-
return {
|
|
1321
|
-
...document,
|
|
1322
|
-
package: {
|
|
1323
|
-
...document.package,
|
|
1324
|
-
document: withBodyContent(body, normalizeBlocks(body.content))
|
|
1325
1237
|
}
|
|
1326
1238
|
};
|
|
1239
|
+
walk(items, []);
|
|
1240
|
+
return out;
|
|
1327
1241
|
};
|
|
1242
|
+
/** Gaps in document order: by offset, then by the zero-width leaves before them. */
|
|
1243
|
+
const compareGaps = (left, right) => left.offset === right.offset ? left.zeroWidthBefore - right.zeroWidthBefore : left.offset - right.offset;
|
|
1328
1244
|
//#endregion
|
|
1329
1245
|
//#region src/ops/identity.ts
|
|
1330
1246
|
/**
|
|
@@ -1504,9 +1420,705 @@ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /*
|
|
|
1504
1420
|
};
|
|
1505
1421
|
};
|
|
1506
1422
|
//#endregion
|
|
1507
|
-
//#region src/ops/
|
|
1423
|
+
//#region src/ops/refusal.ts
|
|
1508
1424
|
/**
|
|
1509
|
-
*
|
|
1425
|
+
* Why an operation was not applied. A refused operation changes nothing: the
|
|
1426
|
+
* document it was applied to is returned as it was.
|
|
1427
|
+
*/
|
|
1428
|
+
const DOCUMENT_OP_REFUSAL_REASONS = Object.freeze({
|
|
1429
|
+
/** No paragraph in the story carries the id. */
|
|
1430
|
+
BLOCK_NOT_FOUND: "blockNotFound",
|
|
1431
|
+
/** An offset is not an integer from `0` to the paragraph's length, or a range runs backwards. */
|
|
1432
|
+
INVALID_OFFSET: "invalidOffset",
|
|
1433
|
+
/** A range starts and ends in different paragraphs or stories. */
|
|
1434
|
+
CROSS_BLOCK_RANGE: "crossBlockRange",
|
|
1435
|
+
/** A position falls between the two halves of a surrogate pair. */
|
|
1436
|
+
SPLITS_SURROGATE_PAIR: "splitsSurrogatePair",
|
|
1437
|
+
/** Inserted text is empty, holds a tab or line-break character, or cannot be written to XML. */
|
|
1438
|
+
INVALID_TEXT: "invalidText",
|
|
1439
|
+
/**
|
|
1440
|
+
* A paragraph id the operation (or its inverse) creates is not eight hex
|
|
1441
|
+
* digits below `0x80000000`, or is the reserved `00000000`.
|
|
1442
|
+
*/
|
|
1443
|
+
INVALID_BLOCK_ID: "invalidBlockId",
|
|
1444
|
+
/**
|
|
1445
|
+
* An id the operation brings in (a paragraph id, or a revision or
|
|
1446
|
+
* content-control id a replacement carries) is already used in the package.
|
|
1447
|
+
*/
|
|
1448
|
+
ID_COLLISION: "idCollision",
|
|
1449
|
+
/** The paragraphs to join or replace are not adjacent siblings of one container. */
|
|
1450
|
+
NOT_ADJACENT: "notAdjacent",
|
|
1451
|
+
/**
|
|
1452
|
+
* The operation would move or remove a section break (joining a paragraph
|
|
1453
|
+
* that ends a section, replacing paragraphs across or at one); that is a
|
|
1454
|
+
* section operation.
|
|
1455
|
+
*/
|
|
1456
|
+
SECTION_BOUNDARY: "sectionBoundary",
|
|
1457
|
+
/** Direct text would land inside tracked-deleted or moved-away content. */
|
|
1458
|
+
INSIDE_TRACKED_DELETION: "insideTrackedDeletion",
|
|
1459
|
+
/**
|
|
1460
|
+
* The operation cuts a record carrying a revision or content-control id in
|
|
1461
|
+
* two and names too few `newIds` for the halves after the first.
|
|
1462
|
+
*/
|
|
1463
|
+
NEEDS_NEW_IDS: "needsNewIds",
|
|
1464
|
+
/** A new revision or content-control id (a stamp's too) is not an integer from 0 to 2^31 - 1. */
|
|
1465
|
+
INVALID_NEW_ID: "invalidNewId",
|
|
1466
|
+
/**
|
|
1467
|
+
* The operation would merge two records carrying the same revision or
|
|
1468
|
+
* content-control id: nothing could tell them apart again to undo it.
|
|
1469
|
+
*/
|
|
1470
|
+
SHARED_ID: "sharedId",
|
|
1471
|
+
/**
|
|
1472
|
+
* What the operation expects (paragraphs to replace, a slice to delete,
|
|
1473
|
+
* the values a patch replaced) is not what is there.
|
|
1474
|
+
*/
|
|
1475
|
+
STALE: "stale",
|
|
1476
|
+
/**
|
|
1477
|
+
* The records at a position are not the shape the operation needs: an open
|
|
1478
|
+
* end meets a record it cannot merge with, records to join differ, a slice
|
|
1479
|
+
* would merge records that were separate, or there are fewer records to cut
|
|
1480
|
+
* than the operation names.
|
|
1481
|
+
*/
|
|
1482
|
+
STRUCTURE_MISMATCH: "structureMismatch",
|
|
1483
|
+
/** Inserted content is empty, or holds an empty run or text node. */
|
|
1484
|
+
EMPTY_CONTENT: "emptyContent",
|
|
1485
|
+
/** A replacement names no paragraph to replace, or none to put in its place. */
|
|
1486
|
+
EMPTY_BLOCK_LIST: "emptyBlockList",
|
|
1487
|
+
/**
|
|
1488
|
+
* The operation would record a tracked change over one the target already
|
|
1489
|
+
* carries (a paragraph mark, a split that would drop a paragraph's property
|
|
1490
|
+
* change), or would give a tracked split a mark of its own.
|
|
1491
|
+
*/
|
|
1492
|
+
REVISION_CONFLICT: "revisionConflict",
|
|
1493
|
+
/** The operation would put a mark on a paragraph that ends its story body or table cell. */
|
|
1494
|
+
CONTAINER_FINAL_MARK: "containerFinalMark",
|
|
1495
|
+
/**
|
|
1496
|
+
* No tracked change can record the edit, or no resolution op can carry it
|
|
1497
|
+
* out yet: comment boundaries in a tracked range, the paragraph mark's run
|
|
1498
|
+
* properties, a join at a section break, a record inside a field.
|
|
1499
|
+
*/
|
|
1500
|
+
UNTRACKABLE: "untrackable",
|
|
1501
|
+
/** Seed contract: a main-story paragraph has no `paraId`. */
|
|
1502
|
+
MISSING_BLOCK_ID: "missingBlockId",
|
|
1503
|
+
/** Seed contract: two paragraphs in the package carry one id. */
|
|
1504
|
+
DUPLICATE_BLOCK_ID: "duplicateBlockId",
|
|
1505
|
+
/** Seed contract: two records in the package carry one revision or content-control id. */
|
|
1506
|
+
DUPLICATE_RECORD_ID: "duplicateRecordId",
|
|
1507
|
+
/** Seed contract: the body's section view does not match its blocks. */
|
|
1508
|
+
SECTIONS_OUT_OF_STEP: "sectionsOutOfStep",
|
|
1509
|
+
/** Seed contract: the main story holds an empty run or empty text node. */
|
|
1510
|
+
EMPTY_RECORD: "emptyRecord"
|
|
1511
|
+
});
|
|
1512
|
+
/** An operation the document cannot take as stated. */
|
|
1513
|
+
var DocumentOpRefusal = class extends TaggedError("DocumentOpRefusal") {};
|
|
1514
|
+
//#endregion
|
|
1515
|
+
//#region src/ops/review.ts
|
|
1516
|
+
/** The tracked-change metadata a stamp writes on the records it creates. */
|
|
1517
|
+
const stampInfo = (stamp) => {
|
|
1518
|
+
const info = {
|
|
1519
|
+
id: stamp.id,
|
|
1520
|
+
author: stamp.author,
|
|
1521
|
+
date: stamp.date
|
|
1522
|
+
};
|
|
1523
|
+
if (stamp.initials !== void 0) info.initials = stamp.initials;
|
|
1524
|
+
return info;
|
|
1525
|
+
};
|
|
1526
|
+
/** Whether a record's metadata is the stamp's, whatever its id. */
|
|
1527
|
+
const carriesStamp = (info, stamp) => structurallyEqual({
|
|
1528
|
+
...info,
|
|
1529
|
+
id: 0
|
|
1530
|
+
}, {
|
|
1531
|
+
...stampInfo(stamp),
|
|
1532
|
+
id: 0
|
|
1533
|
+
});
|
|
1534
|
+
const isTrackedWrapper = (node) => node.type === "insertion" || node.type === "deletion" || node.type === "moveFrom" || node.type === "moveTo";
|
|
1535
|
+
/** Tracked content on its way in: an insertion or the destination of a move. */
|
|
1536
|
+
const isAddedRevision = (node) => node.type === "insertion" || node.type === "moveTo";
|
|
1537
|
+
/** Tracked content on its way out: a deletion or the source of a move. */
|
|
1538
|
+
const isRemovedRevisionNode = (node) => node.type === "deletion" || node.type === "moveFrom";
|
|
1539
|
+
/** The tracked-change metadata of every record a paragraph and its content carry. */
|
|
1540
|
+
const revisionInfosOf = (paragraph) => {
|
|
1541
|
+
const out = [];
|
|
1542
|
+
for (const change of paragraph.propertyChanges ?? []) out.push(change.info);
|
|
1543
|
+
if (paragraph.pPrMark !== void 0) out.push(paragraph.pPrMark.info);
|
|
1544
|
+
const visit = (nodes) => {
|
|
1545
|
+
for (const node of nodes) {
|
|
1546
|
+
if (isTrackedWrapper(node)) out.push(node.info);
|
|
1547
|
+
else if (node.type === "run") for (const change of node.propertyChanges ?? []) out.push(change.info);
|
|
1548
|
+
visit(childNodes(node) ?? []);
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
visit(paragraph.content);
|
|
1552
|
+
return out;
|
|
1553
|
+
};
|
|
1554
|
+
/**
|
|
1555
|
+
* The revision ids of the records carrying the stamp that `known` does not
|
|
1556
|
+
* name (slot keys): the records an operation created, in document order.
|
|
1557
|
+
*/
|
|
1558
|
+
const stampedRevisionIds = (paragraphs, stamp, known) => {
|
|
1559
|
+
const out = [];
|
|
1560
|
+
for (const paragraph of paragraphs) for (const info of revisionInfosOf(paragraph)) {
|
|
1561
|
+
const key = slotKey({
|
|
1562
|
+
space: IDENTITY_SPACES.REVISION,
|
|
1563
|
+
id: info.id
|
|
1564
|
+
});
|
|
1565
|
+
if (carriesStamp(info, stamp) && !known.has(key) && !out.includes(info.id)) out.push(info.id);
|
|
1566
|
+
}
|
|
1567
|
+
return out;
|
|
1568
|
+
};
|
|
1569
|
+
const MARK_KEYS = new Set(PARAGRAPH_MARK_FORMATTING_KEYS);
|
|
1570
|
+
/** Whether a patch or property set names a key of the paragraph mark's run properties. */
|
|
1571
|
+
const namesMarkFormatting = (formatting) => Object.entries(formatting).some(([key, value]) => value !== void 0 && MARK_KEYS.has(key));
|
|
1572
|
+
const pick = (formatting, keep) => {
|
|
1573
|
+
if (formatting === void 0) return;
|
|
1574
|
+
return Object.fromEntries(Object.entries(formatting).filter(([key]) => keep(key)));
|
|
1575
|
+
};
|
|
1576
|
+
/** The paragraph properties a `w:pPrChange` records: all but the mark's run properties. */
|
|
1577
|
+
const paragraphPropertiesOf = (formatting) => pick(formatting, (key) => !MARK_KEYS.has(key));
|
|
1578
|
+
/** The paragraph mark's run properties of a property set; `undefined` when it states none. */
|
|
1579
|
+
const markFormattingOf = (formatting) => {
|
|
1580
|
+
const marks = pick(formatting, (key) => MARK_KEYS.has(key));
|
|
1581
|
+
return marks === void 0 || Object.keys(marks).length === 0 ? void 0 : marks;
|
|
1582
|
+
};
|
|
1583
|
+
/** Whether two property sets state the same paragraph properties. */
|
|
1584
|
+
const sameParagraphProperties = (left, right) => structurallyEqual(paragraphPropertiesOf(left) ?? {}, paragraphPropertiesOf(right) ?? {});
|
|
1585
|
+
/**
|
|
1586
|
+
* The paragraph properties of `properties` with the mark's run properties of
|
|
1587
|
+
* `marks`. `undefined` when the first is absent and the second states no mark
|
|
1588
|
+
* properties.
|
|
1589
|
+
*/
|
|
1590
|
+
const withMarkFormatting = (properties, marks) => {
|
|
1591
|
+
const markFormatting = markFormattingOf(marks);
|
|
1592
|
+
if (properties === void 0 && markFormatting === void 0) return;
|
|
1593
|
+
return {
|
|
1594
|
+
...paragraphPropertiesOf(properties),
|
|
1595
|
+
...markFormatting
|
|
1596
|
+
};
|
|
1597
|
+
};
|
|
1598
|
+
/** A tracked paragraph property change from `previous`. */
|
|
1599
|
+
const paragraphPropertyChange = (info, previous) => {
|
|
1600
|
+
const change = {
|
|
1601
|
+
type: "paragraphPropertyChange",
|
|
1602
|
+
info
|
|
1603
|
+
};
|
|
1604
|
+
const recorded = paragraphPropertiesOf(previous);
|
|
1605
|
+
if (recorded !== void 0) change.previousFormatting = recorded;
|
|
1606
|
+
return change;
|
|
1607
|
+
};
|
|
1608
|
+
/** The review fields a paragraph states, each only when present. */
|
|
1609
|
+
const reviewFieldsOf = (paragraph) => {
|
|
1610
|
+
const fields = {};
|
|
1611
|
+
if (paragraph.formatting !== void 0) fields.formatting = paragraph.formatting;
|
|
1612
|
+
if (paragraph.propertyChanges !== void 0) fields.propertyChanges = paragraph.propertyChanges;
|
|
1613
|
+
if (paragraph.pPrMark !== void 0) fields.pPrMark = paragraph.pPrMark;
|
|
1614
|
+
return fields;
|
|
1615
|
+
};
|
|
1616
|
+
/** The paragraph with exactly these review fields. */
|
|
1617
|
+
const withReviewFields = (paragraph, review) => {
|
|
1618
|
+
const next = { ...paragraph };
|
|
1619
|
+
delete next.formatting;
|
|
1620
|
+
delete next.propertyChanges;
|
|
1621
|
+
delete next.pPrMark;
|
|
1622
|
+
if (review.formatting !== void 0) next.formatting = review.formatting;
|
|
1623
|
+
if (review.propertyChanges !== void 0) next.propertyChanges = review.propertyChanges;
|
|
1624
|
+
if (review.pPrMark !== void 0) next.pPrMark = review.pPrMark;
|
|
1625
|
+
return next;
|
|
1626
|
+
};
|
|
1627
|
+
/** Which tracked change a wrap records. */
|
|
1628
|
+
const WRAP_KINDS = Object.freeze({
|
|
1629
|
+
INSERTION: "insertion",
|
|
1630
|
+
DELETION: "deletion"
|
|
1631
|
+
});
|
|
1632
|
+
/** Comment boundaries and references: no tracked change can hold them. */
|
|
1633
|
+
const COMMENT_ANCHORS$1 = /* @__PURE__ */ new Set([
|
|
1634
|
+
"commentRangeStart",
|
|
1635
|
+
"commentRangeEnd",
|
|
1636
|
+
"commentReference"
|
|
1637
|
+
]);
|
|
1638
|
+
const spanningAction = (node, kind, stamp) => {
|
|
1639
|
+
if (node.type === "inlineSdt" || node.type === "inlineWrapper") return "descend";
|
|
1640
|
+
if (isTrackedWrapper(node) && isAddedRevision(node)) {
|
|
1641
|
+
if (kind === WRAP_KINDS.DELETION) return "descend";
|
|
1642
|
+
return carriesStamp(node.info, stamp) ? "keep" : "cut";
|
|
1643
|
+
}
|
|
1644
|
+
if (isRemovedRevisionNode(node)) return kind === WRAP_KINDS.DELETION ? "keep" : "refuse";
|
|
1645
|
+
return "cut";
|
|
1646
|
+
};
|
|
1647
|
+
const coveredAction = (node, kind) => {
|
|
1648
|
+
if (COMMENT_ANCHORS$1.has(node.type)) return "refuse";
|
|
1649
|
+
if (kind === WRAP_KINDS.DELETION) {
|
|
1650
|
+
if (isRemovedRevisionNode(node)) return "skip";
|
|
1651
|
+
if (isAddedRevision(node)) return "descend";
|
|
1652
|
+
}
|
|
1653
|
+
return "wrap";
|
|
1654
|
+
};
|
|
1655
|
+
/** Merge a created wrapper into a neighbour carrying the same stamp: the left one, else the right. */
|
|
1656
|
+
const mergeWithStampedNeighbour = (out, index, state) => {
|
|
1657
|
+
const wrapper = out[index];
|
|
1658
|
+
if (wrapper === void 0 || !isTrackedWrapper(wrapper)) return;
|
|
1659
|
+
const matching = (neighbour) => neighbour !== void 0 && isTrackedWrapper(neighbour) && neighbour.type === wrapper.type && !state.created.has(neighbour) && carriesStamp(neighbour.info, state.stamp);
|
|
1660
|
+
const left = out[index - 1];
|
|
1661
|
+
if (matching(left)) {
|
|
1662
|
+
const merged = mergeLists([left], [wrapper], 1);
|
|
1663
|
+
if (merged !== void 0) {
|
|
1664
|
+
state.created.delete(wrapper);
|
|
1665
|
+
out.splice(index - 1, 2, ...merged);
|
|
1666
|
+
}
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
const right = out[index + 1];
|
|
1670
|
+
if (matching(right)) {
|
|
1671
|
+
const merged = mergeLists([wrapper], [right], 1, {
|
|
1672
|
+
mode: "exact",
|
|
1673
|
+
identity: "second"
|
|
1674
|
+
});
|
|
1675
|
+
if (merged !== void 0) {
|
|
1676
|
+
state.created.delete(wrapper);
|
|
1677
|
+
out.splice(index, 2, ...merged);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
};
|
|
1681
|
+
const trackedContent = (nodes, state) => {
|
|
1682
|
+
const out = [];
|
|
1683
|
+
for (const node of nodes) {
|
|
1684
|
+
if (!isParagraphContent(node) || !isTrackedChild(node)) {
|
|
1685
|
+
state.refusal = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE;
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
out.push(node);
|
|
1689
|
+
}
|
|
1690
|
+
return out;
|
|
1691
|
+
};
|
|
1692
|
+
/** Group the covered entries of a list into wrappers; `undefined` once refused. */
|
|
1693
|
+
const groupCovered = (entries, state) => {
|
|
1694
|
+
const out = [];
|
|
1695
|
+
const wrapperAt = [];
|
|
1696
|
+
let stretch = [];
|
|
1697
|
+
const flush = () => {
|
|
1698
|
+
if (stretch.length === 0) return true;
|
|
1699
|
+
const content = trackedContent(stretch, state);
|
|
1700
|
+
if (content === void 0) return false;
|
|
1701
|
+
const info = stampInfo(state.stamp);
|
|
1702
|
+
const wrapper = state.kind === WRAP_KINDS.INSERTION ? {
|
|
1703
|
+
type: "insertion",
|
|
1704
|
+
info,
|
|
1705
|
+
content
|
|
1706
|
+
} : {
|
|
1707
|
+
type: "deletion",
|
|
1708
|
+
info,
|
|
1709
|
+
content
|
|
1710
|
+
};
|
|
1711
|
+
state.created.add(wrapper);
|
|
1712
|
+
state.recorded = true;
|
|
1713
|
+
wrapperAt.push(out.length);
|
|
1714
|
+
out.push(wrapper);
|
|
1715
|
+
stretch = [];
|
|
1716
|
+
return true;
|
|
1717
|
+
};
|
|
1718
|
+
for (const { node, covered } of entries) {
|
|
1719
|
+
const action = covered ? coveredAction(node, state.kind) : "skip";
|
|
1720
|
+
switch (action) {
|
|
1721
|
+
case "refuse":
|
|
1722
|
+
state.refusal = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE;
|
|
1723
|
+
return;
|
|
1724
|
+
case "skip":
|
|
1725
|
+
if (!flush()) return void 0;
|
|
1726
|
+
out.push(node);
|
|
1727
|
+
break;
|
|
1728
|
+
case "descend": {
|
|
1729
|
+
if (!flush()) return void 0;
|
|
1730
|
+
const children = childNodes(node) ?? [];
|
|
1731
|
+
const wrapped = groupCovered(children.map((child) => ({
|
|
1732
|
+
node: child,
|
|
1733
|
+
covered: true
|
|
1734
|
+
})), state);
|
|
1735
|
+
if (wrapped === void 0) return void 0;
|
|
1736
|
+
out.push(rebuildNode(node, wrapped));
|
|
1737
|
+
break;
|
|
1738
|
+
}
|
|
1739
|
+
case "wrap":
|
|
1740
|
+
stretch.push(node);
|
|
1741
|
+
break;
|
|
1742
|
+
default: return action;
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
if (!flush()) return void 0;
|
|
1746
|
+
for (const index of wrapperAt.toReversed()) mergeWithStampedNeighbour(out, index, state);
|
|
1747
|
+
return out;
|
|
1748
|
+
};
|
|
1749
|
+
const wrapList = (nodes, cursor, state) => {
|
|
1750
|
+
const entries = [];
|
|
1751
|
+
for (const node of nodes) {
|
|
1752
|
+
const start = { ...cursor };
|
|
1753
|
+
const measured = partitionNode(node, state.gaps, cursor);
|
|
1754
|
+
if (measured.min === measured.max) {
|
|
1755
|
+
entries.push({
|
|
1756
|
+
node,
|
|
1757
|
+
covered: measured.min === 1
|
|
1758
|
+
});
|
|
1759
|
+
continue;
|
|
1760
|
+
}
|
|
1761
|
+
const action = spanningAction(node, state.kind, state.stamp);
|
|
1762
|
+
switch (action) {
|
|
1763
|
+
case "refuse":
|
|
1764
|
+
state.refusal = DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION;
|
|
1765
|
+
return;
|
|
1766
|
+
case "keep":
|
|
1767
|
+
entries.push({
|
|
1768
|
+
node,
|
|
1769
|
+
covered: false
|
|
1770
|
+
});
|
|
1771
|
+
break;
|
|
1772
|
+
case "descend": {
|
|
1773
|
+
const end = { ...cursor };
|
|
1774
|
+
cursor.position = start.position;
|
|
1775
|
+
cursor.zeroWidthSeen = start.zeroWidthSeen;
|
|
1776
|
+
const children = wrapList(childNodes(node) ?? [], cursor, state);
|
|
1777
|
+
if (children === void 0) return void 0;
|
|
1778
|
+
cursor.position = end.position;
|
|
1779
|
+
cursor.zeroWidthSeen = end.zeroWidthSeen;
|
|
1780
|
+
entries.push({
|
|
1781
|
+
node: rebuildNode(node, children),
|
|
1782
|
+
covered: false
|
|
1783
|
+
});
|
|
1784
|
+
break;
|
|
1785
|
+
}
|
|
1786
|
+
case "cut":
|
|
1787
|
+
for (const [region, piece] of measured.pieces) {
|
|
1788
|
+
const unwrap = region === 1 && state.kind === WRAP_KINDS.INSERTION && isTrackedWrapper(piece);
|
|
1789
|
+
for (const part of unwrap ? childNodes(piece) ?? [] : [piece]) entries.push({
|
|
1790
|
+
node: part,
|
|
1791
|
+
covered: region === 1
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
break;
|
|
1795
|
+
default: return action;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
return groupCovered(entries, state);
|
|
1799
|
+
};
|
|
1800
|
+
/**
|
|
1801
|
+
* Wrap the leaves between two gaps in a tracked change carrying the stamp.
|
|
1802
|
+
* `unchanged` when there is nothing to record: every leaf is already
|
|
1803
|
+
* deleted, or an insertion sits inside a wrapper carrying the same stamp.
|
|
1804
|
+
*/
|
|
1805
|
+
const wrapTracked = ({ items, from, to, kind, stamp }) => {
|
|
1806
|
+
const state = {
|
|
1807
|
+
gaps: [from, to],
|
|
1808
|
+
kind,
|
|
1809
|
+
stamp,
|
|
1810
|
+
created: /* @__PURE__ */ new Set(),
|
|
1811
|
+
recorded: false,
|
|
1812
|
+
refusal: void 0
|
|
1813
|
+
};
|
|
1814
|
+
const content = wrapList(items, startCursor(), state);
|
|
1815
|
+
if (content === void 0) return {
|
|
1816
|
+
kind: "refused",
|
|
1817
|
+
reason: state.refusal ?? DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE
|
|
1818
|
+
};
|
|
1819
|
+
if (!state.recorded) return { kind: "unchanged" };
|
|
1820
|
+
const out = [];
|
|
1821
|
+
for (const node of content) {
|
|
1822
|
+
if (!isParagraphContent(node)) return {
|
|
1823
|
+
kind: "refused",
|
|
1824
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE
|
|
1825
|
+
};
|
|
1826
|
+
out.push(node);
|
|
1827
|
+
}
|
|
1828
|
+
return {
|
|
1829
|
+
kind: "wrapped",
|
|
1830
|
+
content: out
|
|
1831
|
+
};
|
|
1832
|
+
};
|
|
1833
|
+
//#endregion
|
|
1834
|
+
//#region src/ops/blockInsertion.ts
|
|
1835
|
+
/** Paragraph insertion, isolated from the inline and table operation implementations. */
|
|
1836
|
+
const insertBlocks = ({ document, op, applyOps }) => {
|
|
1837
|
+
const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
|
|
1838
|
+
reason,
|
|
1839
|
+
message,
|
|
1840
|
+
opType: op.type
|
|
1841
|
+
}));
|
|
1842
|
+
if (op.blocks.length === 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "No paragraphs to insert.");
|
|
1843
|
+
if (op.at.type !== "before" && op.at.type !== "after") return refuse(DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Insert before or after a paragraph.");
|
|
1844
|
+
const body = storyBody(document, op.story);
|
|
1845
|
+
const location = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(op.at.blockId));
|
|
1846
|
+
if (location === void 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "The insertion anchor does not exist.");
|
|
1847
|
+
if (op.blocks.some(({ sectionProperties }) => sectionProperties !== void 0)) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Inserting section breaks requires section operations.");
|
|
1848
|
+
const following = blockListAt(body.content, location.list)[location.index + 1];
|
|
1849
|
+
const before = op.at.type === "before" || following?.type === "paragraph";
|
|
1850
|
+
const anchor = op.at.type === "after" && following?.type === "paragraph" ? following : location.paragraph;
|
|
1851
|
+
if (op.revision !== void 0 && !before) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion requires a following paragraph in the same block list.");
|
|
1852
|
+
const replacement = (blocks) => ({
|
|
1853
|
+
type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
|
|
1854
|
+
story: op.story,
|
|
1855
|
+
expected: [anchor],
|
|
1856
|
+
blocks: before ? [...blocks, anchor] : [anchor, ...blocks]
|
|
1857
|
+
});
|
|
1858
|
+
const direct = applyOps(document, [replacement(op.blocks)]);
|
|
1859
|
+
if (direct.isErr()) return Result.err(new DocumentOpRefusal({
|
|
1860
|
+
reason: direct.error.reason,
|
|
1861
|
+
message: direct.error.message,
|
|
1862
|
+
opType: op.type
|
|
1863
|
+
}));
|
|
1864
|
+
const insertedIds = new Set(op.blocks.map(({ paraId }) => idKey(paraId ?? "")));
|
|
1865
|
+
if (storyParagraphs(storyBody(direct.value.document, op.story)).some((at) => insertedIds.has(idKey(at.paragraph.paraId ?? "")) && at.paragraph.pPrMark !== void 0 && endsItsContainer(storyBody(direct.value.document, op.story), at))) return refuse(DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK, "Insertion would leave a tracked mark on a container-final paragraph.");
|
|
1866
|
+
const touched = {
|
|
1867
|
+
modified: [],
|
|
1868
|
+
inserted: op.blocks.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]),
|
|
1869
|
+
removed: []
|
|
1870
|
+
};
|
|
1871
|
+
if (op.revision === void 0) return Result.ok({
|
|
1872
|
+
...direct.value,
|
|
1873
|
+
touched
|
|
1874
|
+
});
|
|
1875
|
+
if (identityKeysIn(op.blocks).length > 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion of identified review or content-control records is unsupported.");
|
|
1876
|
+
const blocks = [];
|
|
1877
|
+
for (const paragraph of op.blocks) {
|
|
1878
|
+
const wrapped = wrapTracked({
|
|
1879
|
+
items: paragraph.content,
|
|
1880
|
+
from: {
|
|
1881
|
+
offset: 0,
|
|
1882
|
+
zeroWidthBefore: 0
|
|
1883
|
+
},
|
|
1884
|
+
to: {
|
|
1885
|
+
offset: paragraphLength(paragraph),
|
|
1886
|
+
zeroWidthBefore: Number.MAX_SAFE_INTEGER
|
|
1887
|
+
},
|
|
1888
|
+
kind: WRAP_KINDS.INSERTION,
|
|
1889
|
+
stamp: op.revision
|
|
1890
|
+
});
|
|
1891
|
+
if (wrapped.kind === "refused") return refuse(wrapped.reason, "The inserted content cannot be tracked.");
|
|
1892
|
+
blocks.push({
|
|
1893
|
+
...paragraph,
|
|
1894
|
+
content: wrapped.kind === "wrapped" ? wrapped.content : paragraph.content,
|
|
1895
|
+
pPrMark: {
|
|
1896
|
+
kind: "ins",
|
|
1897
|
+
info: stampInfo(op.revision)
|
|
1898
|
+
}
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
const fresh = freshenIdentities({
|
|
1902
|
+
before: [],
|
|
1903
|
+
after: blocks,
|
|
1904
|
+
newIds: op.newIds ?? {},
|
|
1905
|
+
usedElsewhere: () => new Set(packageIdentityKeys(document.package))
|
|
1906
|
+
});
|
|
1907
|
+
switch (fresh.kind) {
|
|
1908
|
+
case "needsIds": return refuse(DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS, "Inserted paragraph review records need more revision ids.");
|
|
1909
|
+
case "invalidId": return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "An inserted review record has an invalid revision id.");
|
|
1910
|
+
case "fresh": {
|
|
1911
|
+
const tracked = applyOps(document, [replacement(fresh.paragraphs)]);
|
|
1912
|
+
return tracked.isErr() ? Result.err(new DocumentOpRefusal({
|
|
1913
|
+
reason: tracked.error.reason,
|
|
1914
|
+
message: tracked.error.message,
|
|
1915
|
+
opType: op.type
|
|
1916
|
+
})) : Result.ok({
|
|
1917
|
+
...tracked.value,
|
|
1918
|
+
touched
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
default: return fresh;
|
|
1922
|
+
}
|
|
1923
|
+
};
|
|
1924
|
+
//#endregion
|
|
1925
|
+
//#region src/ops/contract.ts
|
|
1926
|
+
/**
|
|
1927
|
+
* The seed contract: what a document must be for operations to apply to it.
|
|
1928
|
+
*
|
|
1929
|
+
* A host establishes it once, when a document enters the journal: run
|
|
1930
|
+
* `ensureParaIds` over the package bytes (it stamps every story, headers,
|
|
1931
|
+
* footers and notes included, and makes ids unique), parse, then
|
|
1932
|
+
* {@link normalizeForOps}. {@link validateOpsDocument} states the result:
|
|
1933
|
+
*
|
|
1934
|
+
* - every paragraph of the main story has a `w14:paraId`;
|
|
1935
|
+
* - no paragraph id repeats anywhere in the package, compared as hex, so an
|
|
1936
|
+
* inverse can always recreate the ids it removed;
|
|
1937
|
+
* - no revision id (tracked changes, property changes) or content-control id
|
|
1938
|
+
* repeats, so the one record carrying an id is the one it names;
|
|
1939
|
+
* - the body's section view says what its blocks say;
|
|
1940
|
+
* - the main story holds no empty run, text node, or revision wrapper.
|
|
1941
|
+
*
|
|
1942
|
+
* Paragraphs in text boxes, headers, footers, notes and comments are other
|
|
1943
|
+
* stories: they are not addressable in schema version 1, and their ids count
|
|
1944
|
+
* toward uniqueness like any other.
|
|
1945
|
+
*
|
|
1946
|
+
* Every operation checks the contract before applying and leaves it holding,
|
|
1947
|
+
* so a document an operation produced is not checked again: documents are
|
|
1948
|
+
* values, never modified in place.
|
|
1949
|
+
*/
|
|
1950
|
+
/** A document that does not meet the seed contract. */
|
|
1951
|
+
var DocumentOpsContractError = class extends TaggedError("DocumentOpsContractError") {};
|
|
1952
|
+
const holdsEmptyRecord$1 = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord$1(childNodes(node) ?? []));
|
|
1953
|
+
const violation = (document) => {
|
|
1954
|
+
const body = document.package.document;
|
|
1955
|
+
const paragraphs = storyParagraphs(body);
|
|
1956
|
+
if (paragraphs.some(({ paragraph }) => paragraph.paraId === void 0)) return new DocumentOpsContractError({
|
|
1957
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.MISSING_BLOCK_ID,
|
|
1958
|
+
message: "A main-story paragraph has no paraId; ensureParaIds establishes one."
|
|
1959
|
+
});
|
|
1960
|
+
const repeated = [...countIds(packageParagraphIds(document.package))].find(([, count]) => count > 1);
|
|
1961
|
+
if (repeated !== void 0) return new DocumentOpsContractError({
|
|
1962
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_BLOCK_ID,
|
|
1963
|
+
message: `${repeated[1]} paragraphs in the package are ${repeated[0]}.`
|
|
1964
|
+
});
|
|
1965
|
+
const repeatedRecord = [...countKeys(packageIdentityKeys(document.package))].find(([, count]) => count > 1);
|
|
1966
|
+
if (repeatedRecord !== void 0) return new DocumentOpsContractError({
|
|
1967
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_RECORD_ID,
|
|
1968
|
+
message: `${repeatedRecord[1]} records in the package carry ${repeatedRecord[0]}.`
|
|
1969
|
+
});
|
|
1970
|
+
if (!sectionsInStep(body)) return new DocumentOpsContractError({
|
|
1971
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.SECTIONS_OUT_OF_STEP,
|
|
1972
|
+
message: "The body's section view does not match its blocks."
|
|
1973
|
+
});
|
|
1974
|
+
if (paragraphs.some(({ paragraph }) => holdsEmptyRecord$1(paragraph.content))) return new DocumentOpsContractError({
|
|
1975
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.EMPTY_RECORD,
|
|
1976
|
+
message: "The main story holds an empty run, text node, or revision wrapper; normalizeForOps removes them."
|
|
1977
|
+
});
|
|
1978
|
+
};
|
|
1979
|
+
/** Documents known to meet the contract: checked ones and ones an operation produced. */
|
|
1980
|
+
const MEETS_CONTRACT = /* @__PURE__ */ new WeakSet();
|
|
1981
|
+
/** Check a document against the seed contract. */
|
|
1982
|
+
const validateOpsDocument = (document) => {
|
|
1983
|
+
if (MEETS_CONTRACT.has(document)) return Result.ok(document);
|
|
1984
|
+
const found = violation(document);
|
|
1985
|
+
if (found !== void 0) return Result.err(found);
|
|
1986
|
+
MEETS_CONTRACT.add(document);
|
|
1987
|
+
return Result.ok(document);
|
|
1988
|
+
};
|
|
1989
|
+
/** Record that an operation produced `document` from one that met the contract. */
|
|
1990
|
+
const meetsContract = (document) => {
|
|
1991
|
+
MEETS_CONTRACT.add(document);
|
|
1992
|
+
};
|
|
1993
|
+
const withoutEmpty = (nodes) => {
|
|
1994
|
+
let changed = false;
|
|
1995
|
+
const out = [];
|
|
1996
|
+
for (const node of nodes) {
|
|
1997
|
+
if (isEmptyRecord(node)) {
|
|
1998
|
+
changed = true;
|
|
1999
|
+
continue;
|
|
2000
|
+
}
|
|
2001
|
+
const children = childNodes(node);
|
|
2002
|
+
const kept = children === void 0 ? children : withoutEmpty(children);
|
|
2003
|
+
if (kept !== children && kept !== void 0) {
|
|
2004
|
+
changed = true;
|
|
2005
|
+
const rebuilt = rebuildNode(node, kept);
|
|
2006
|
+
if (!isEmptyRecord(rebuilt)) out.push(rebuilt);
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
out.push(node);
|
|
2010
|
+
}
|
|
2011
|
+
return changed ? out : nodes;
|
|
2012
|
+
};
|
|
2013
|
+
const normalizeBlocks = (blocks) => {
|
|
2014
|
+
const out = [];
|
|
2015
|
+
for (const block of blocks) switch (block.type) {
|
|
2016
|
+
case "paragraph": {
|
|
2017
|
+
const content = withoutEmpty(block.content);
|
|
2018
|
+
out.push(content === block.content ? block : {
|
|
2019
|
+
...block,
|
|
2020
|
+
content: asParagraphContent(content)
|
|
2021
|
+
});
|
|
2022
|
+
break;
|
|
2023
|
+
}
|
|
2024
|
+
case "table": {
|
|
2025
|
+
const rows = [];
|
|
2026
|
+
for (const row of block.rows) {
|
|
2027
|
+
const cells = [];
|
|
2028
|
+
for (const cell of row.cells) cells.push({
|
|
2029
|
+
...cell,
|
|
2030
|
+
content: normalizeBlocks(cell.content)
|
|
2031
|
+
});
|
|
2032
|
+
rows.push({
|
|
2033
|
+
...row,
|
|
2034
|
+
cells
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
out.push({
|
|
2038
|
+
...block,
|
|
2039
|
+
rows
|
|
2040
|
+
});
|
|
2041
|
+
break;
|
|
2042
|
+
}
|
|
2043
|
+
case "blockSdt":
|
|
2044
|
+
case "blockCustomXml":
|
|
2045
|
+
out.push({
|
|
2046
|
+
...block,
|
|
2047
|
+
content: normalizeBlocks(block.content)
|
|
2048
|
+
});
|
|
2049
|
+
break;
|
|
2050
|
+
case "preservedBlock":
|
|
2051
|
+
case "bookmarkStart":
|
|
2052
|
+
case "bookmarkEnd":
|
|
2053
|
+
out.push(block);
|
|
2054
|
+
break;
|
|
2055
|
+
default: return block;
|
|
2056
|
+
}
|
|
2057
|
+
return out;
|
|
2058
|
+
};
|
|
2059
|
+
/**
|
|
2060
|
+
* The document with every empty run and empty text node of the main story
|
|
2061
|
+
* removed, and its section view derived again. Nothing else changes.
|
|
2062
|
+
*/
|
|
2063
|
+
const normalizeForOps = (document) => {
|
|
2064
|
+
const body = document.package.document;
|
|
2065
|
+
return {
|
|
2066
|
+
...document,
|
|
2067
|
+
package: {
|
|
2068
|
+
...document.package,
|
|
2069
|
+
document: withBodyContent(body, normalizeBlocks(body.content))
|
|
2070
|
+
}
|
|
2071
|
+
};
|
|
2072
|
+
};
|
|
2073
|
+
//#endregion
|
|
2074
|
+
//#region src/ops/edits.ts
|
|
2075
|
+
const TOUCHED_STATES = [
|
|
2076
|
+
"modified",
|
|
2077
|
+
"inserted",
|
|
2078
|
+
"removed"
|
|
2079
|
+
];
|
|
2080
|
+
/** A block's net change after two changes in turn; `undefined` when it came and went. */
|
|
2081
|
+
const TOUCH_TRANSITIONS = {
|
|
2082
|
+
modified: {
|
|
2083
|
+
modified: "modified",
|
|
2084
|
+
inserted: "modified",
|
|
2085
|
+
removed: "removed"
|
|
2086
|
+
},
|
|
2087
|
+
inserted: {
|
|
2088
|
+
modified: "inserted",
|
|
2089
|
+
inserted: "inserted",
|
|
2090
|
+
removed: void 0
|
|
2091
|
+
},
|
|
2092
|
+
removed: {
|
|
2093
|
+
modified: "modified",
|
|
2094
|
+
inserted: "modified",
|
|
2095
|
+
removed: "removed"
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
/** Edits made in turn, starting from `document`, as one edit. */
|
|
2099
|
+
const combineEdits = (document, edits) => {
|
|
2100
|
+
const touched = /* @__PURE__ */ new Map();
|
|
2101
|
+
for (const edit of edits) for (const state of TOUCHED_STATES) for (const id of edit.touched[state]) {
|
|
2102
|
+
const previous = touched.get(id);
|
|
2103
|
+
const next = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
|
|
2104
|
+
if (next === void 0) touched.delete(id);
|
|
2105
|
+
else touched.set(id, next);
|
|
2106
|
+
}
|
|
2107
|
+
const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
|
|
2108
|
+
return {
|
|
2109
|
+
document: edits.at(-1)?.document ?? document,
|
|
2110
|
+
inverse: edits.toReversed().flatMap(({ inverse }) => inverse),
|
|
2111
|
+
touched: {
|
|
2112
|
+
modified: ids("modified"),
|
|
2113
|
+
inserted: ids("inserted"),
|
|
2114
|
+
removed: ids("removed")
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
2117
|
+
};
|
|
2118
|
+
//#endregion
|
|
2119
|
+
//#region src/ops/patch.ts
|
|
2120
|
+
/**
|
|
2121
|
+
* The keys an object states.
|
|
1510
2122
|
*
|
|
1511
2123
|
* SAFETY: `Object.keys` widens to `string[]`. Both callers pass a model
|
|
1512
2124
|
* property set or a patch over one, object literals whose own keys are all
|
|
@@ -1856,7 +2468,7 @@ const insertTextInContent = (items, offset, text, runProps) => {
|
|
|
1856
2468
|
if (halves.right !== void 0) replacement.push(halves.right);
|
|
1857
2469
|
return replaceAtPath(items, host.path, replacement);
|
|
1858
2470
|
};
|
|
1859
|
-
const patchRunsIn = (nodes, patch, whenEmpty, prior) => {
|
|
2471
|
+
const patchRunsIn = (nodes, patch, whenEmpty, prior, decorate) => {
|
|
1860
2472
|
const out = [];
|
|
1861
2473
|
for (const node of nodes) {
|
|
1862
2474
|
if (node.type === "run") {
|
|
@@ -1865,14 +2477,15 @@ const patchRunsIn = (nodes, patch, whenEmpty, prior) => {
|
|
|
1865
2477
|
out.push(node);
|
|
1866
2478
|
continue;
|
|
1867
2479
|
}
|
|
1868
|
-
const
|
|
2480
|
+
const patchedRun = withRunFormatting(node, formatting);
|
|
2481
|
+
const run = decorate === void 0 ? patchedRun : decorate(patchedRun, node);
|
|
1869
2482
|
prior.set(run, node.formatting);
|
|
1870
2483
|
out.push(run);
|
|
1871
2484
|
continue;
|
|
1872
2485
|
}
|
|
1873
2486
|
if (isParagraphContent(node) && isInlineContainer(node)) {
|
|
1874
2487
|
const children = childrenOf(node);
|
|
1875
|
-
const next = patchRunsIn(children, patch, whenEmpty, prior);
|
|
2488
|
+
const next = patchRunsIn(children, patch, whenEmpty, prior, decorate);
|
|
1876
2489
|
const same = next.every((child, index) => child === children[index]);
|
|
1877
2490
|
out.push(same ? node : withChildren(node, asParagraphContent(next)));
|
|
1878
2491
|
continue;
|
|
@@ -1905,12 +2518,14 @@ const runsBetween = (items, from, to) => {
|
|
|
1905
2518
|
* `restoring` gives the changed runs back the values the patch replaced, one
|
|
1906
2519
|
* patch per stretch of adjacent runs that had the same values. A run the
|
|
1907
2520
|
* patch left alone ends a stretch, so a restoring patch never reaches it.
|
|
2521
|
+
*
|
|
2522
|
+
* `decorate` adds to each changed run what a tracked patch records on it.
|
|
1908
2523
|
*/
|
|
1909
|
-
const patchRunsBetween = (items, from, to, patch, whenEmpty) => {
|
|
2524
|
+
const patchRunsBetween = (items, from, to, patch, whenEmpty, decorate) => {
|
|
1910
2525
|
const gaps = [from, to];
|
|
1911
2526
|
const [before = [], middle = [], after = []] = partitionContent(items, gaps);
|
|
1912
2527
|
const prior = /* @__PURE__ */ new Map();
|
|
1913
|
-
const patchedMiddle = patchRunsIn(middle, patch, whenEmpty, prior);
|
|
2528
|
+
const patchedMiddle = patchRunsIn(middle, patch, whenEmpty, prior, decorate);
|
|
1914
2529
|
if (prior.size === 0) return;
|
|
1915
2530
|
const alike = { mode: "asFarAsAlike" };
|
|
1916
2531
|
const content = asParagraphContent(mergeLists(mergeLists(before, patchedMiddle, spanningRecords(items, gaps, 0, 1).length, alike) ?? [], after, spanningRecords(items, gaps, 1, 2).length, alike) ?? []);
|
|
@@ -1938,14 +2553,861 @@ const patchRunsBetween = (items, from, to, patch, whenEmpty) => {
|
|
|
1938
2553
|
stretchOpen = true;
|
|
1939
2554
|
}
|
|
1940
2555
|
return {
|
|
1941
|
-
content,
|
|
1942
|
-
restoring: restoring.map(({ from: start, to: end, patch: restore, whenEmpty: spelling }) => ({
|
|
1943
|
-
from: start,
|
|
1944
|
-
to: end,
|
|
1945
|
-
patch: restore,
|
|
1946
|
-
whenEmpty: spelling
|
|
1947
|
-
}))
|
|
2556
|
+
content,
|
|
2557
|
+
restoring: restoring.map(({ from: start, to: end, patch: restore, whenEmpty: spelling }) => ({
|
|
2558
|
+
from: start,
|
|
2559
|
+
to: end,
|
|
2560
|
+
patch: restore,
|
|
2561
|
+
whenEmpty: spelling
|
|
2562
|
+
}))
|
|
2563
|
+
};
|
|
2564
|
+
};
|
|
2565
|
+
//#endregion
|
|
2566
|
+
//#region src/ops/tableRows.ts
|
|
2567
|
+
/** Row edits and their exact inverse, addressed through a paragraph in the row. */
|
|
2568
|
+
const refused = ({ op, reason, message }) => Result.err(new DocumentOpRefusal({
|
|
2569
|
+
opType: op.type,
|
|
2570
|
+
reason,
|
|
2571
|
+
message
|
|
2572
|
+
}));
|
|
2573
|
+
/** A paragraph selects its innermost table, even through block wrappers. */
|
|
2574
|
+
const locateTableRow = (document, op) => {
|
|
2575
|
+
const body = storyBody(document, op.story);
|
|
2576
|
+
const location = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(op.blockId));
|
|
2577
|
+
if (location === void 0) return refused({
|
|
2578
|
+
op,
|
|
2579
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
|
|
2580
|
+
message: `No paragraph is ${op.blockId}.`
|
|
2581
|
+
});
|
|
2582
|
+
const stepIndex = location.list.findLastIndex((step) => step.kind === "tableCell");
|
|
2583
|
+
const step = location.list[stepIndex];
|
|
2584
|
+
if (step?.kind !== "tableCell") return refused({
|
|
2585
|
+
op,
|
|
2586
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
|
|
2587
|
+
message: "The paragraph is not in a table row."
|
|
2588
|
+
});
|
|
2589
|
+
const list = location.list.slice(0, stepIndex);
|
|
2590
|
+
const table = blockListAt(body.content, list)[step.block];
|
|
2591
|
+
if (table?.type !== "table") return panic("A table-cell path must name a table.");
|
|
2592
|
+
return Result.ok({
|
|
2593
|
+
list,
|
|
2594
|
+
index: step.block,
|
|
2595
|
+
rowIndex: step.row,
|
|
2596
|
+
table
|
|
2597
|
+
});
|
|
2598
|
+
};
|
|
2599
|
+
const paragraphsIn = (rows) => storyParagraphs({ content: [{
|
|
2600
|
+
type: "table",
|
|
2601
|
+
rows: [...rows]
|
|
2602
|
+
}] }).map(({ paragraph }) => paragraph);
|
|
2603
|
+
/** Rebuild only paths to changed paragraphs, retaining every other record. */
|
|
2604
|
+
const mapParagraphs = (blocks, replace) => blocks.map((block) => {
|
|
2605
|
+
switch (block.type) {
|
|
2606
|
+
case "paragraph": return replace(block);
|
|
2607
|
+
case "blockSdt":
|
|
2608
|
+
case "blockCustomXml": return {
|
|
2609
|
+
...block,
|
|
2610
|
+
content: mapParagraphs(block.content, replace)
|
|
2611
|
+
};
|
|
2612
|
+
case "table": return {
|
|
2613
|
+
...block,
|
|
2614
|
+
rows: block.rows.map((row) => ({
|
|
2615
|
+
...row,
|
|
2616
|
+
cells: row.cells.map((cell) => ({
|
|
2617
|
+
...cell,
|
|
2618
|
+
content: mapParagraphs(cell.content, replace)
|
|
2619
|
+
}))
|
|
2620
|
+
}))
|
|
2621
|
+
};
|
|
2622
|
+
case "preservedBlock":
|
|
2623
|
+
case "bookmarkStart":
|
|
2624
|
+
case "bookmarkEnd": return block;
|
|
2625
|
+
default: return block;
|
|
2626
|
+
}
|
|
2627
|
+
});
|
|
2628
|
+
const rowWithParagraphs = (row, replace) => ({
|
|
2629
|
+
...row,
|
|
2630
|
+
cells: row.cells.map((cell) => ({
|
|
2631
|
+
...cell,
|
|
2632
|
+
content: mapParagraphs(cell.content, replace)
|
|
2633
|
+
}))
|
|
2634
|
+
});
|
|
2635
|
+
/** Indexed markup and shared row wrappers need a structural table operation. */
|
|
2636
|
+
const needsTableEdit = (table) => table.preserved !== void 0 || table.bookmarks !== void 0 || table.carrierStack !== void 0 || table.rows.some((row) => row.contentControls !== void 0 || row.carrierStack !== void 0);
|
|
2637
|
+
/** Nested tables, captured blocks and cell revisions have no tracked-row construction yet. */
|
|
2638
|
+
const trackableBlocks = (blocks) => blocks.every((block) => {
|
|
2639
|
+
switch (block.type) {
|
|
2640
|
+
case "paragraph": return block.sectionProperties === void 0;
|
|
2641
|
+
case "blockSdt":
|
|
2642
|
+
case "blockCustomXml": return trackableBlocks(block.content);
|
|
2643
|
+
case "table":
|
|
2644
|
+
case "preservedBlock":
|
|
2645
|
+
case "bookmarkStart":
|
|
2646
|
+
case "bookmarkEnd": return false;
|
|
2647
|
+
default: return block;
|
|
2648
|
+
}
|
|
2649
|
+
});
|
|
2650
|
+
const trackRow = ({ document, op, row, revision, newIds, kind }) => {
|
|
2651
|
+
if (row.structuralChange !== void 0) return refused({
|
|
2652
|
+
op,
|
|
2653
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
|
|
2654
|
+
message: "The row already carries a structural revision."
|
|
2655
|
+
});
|
|
2656
|
+
if (row.cells.some((cell) => cell.structuralChange !== void 0 || !trackableBlocks(cell.content))) return refused({
|
|
2657
|
+
op,
|
|
2658
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2659
|
+
message: "The row contains an unsupported tracked structure."
|
|
2660
|
+
});
|
|
2661
|
+
const before = paragraphsIn([row]);
|
|
2662
|
+
const after = [];
|
|
2663
|
+
for (const paragraph of before) {
|
|
2664
|
+
const wrapped = wrapTracked({
|
|
2665
|
+
items: paragraph.content,
|
|
2666
|
+
from: {
|
|
2667
|
+
offset: 0,
|
|
2668
|
+
zeroWidthBefore: 0
|
|
2669
|
+
},
|
|
2670
|
+
to: {
|
|
2671
|
+
offset: paragraphLength(paragraph),
|
|
2672
|
+
zeroWidthBefore: Number.MAX_SAFE_INTEGER
|
|
2673
|
+
},
|
|
2674
|
+
kind,
|
|
2675
|
+
stamp: revision
|
|
2676
|
+
});
|
|
2677
|
+
if (wrapped.kind === "refused") return refused({
|
|
2678
|
+
op,
|
|
2679
|
+
reason: wrapped.reason,
|
|
2680
|
+
message: "The row's content cannot record this revision."
|
|
2681
|
+
});
|
|
2682
|
+
after.push(wrapped.kind === "unchanged" ? paragraph : {
|
|
2683
|
+
...paragraph,
|
|
2684
|
+
content: wrapped.content
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
const outside = new Set(packageIdentityKeys(document.package));
|
|
2688
|
+
if (op.type === DOCUMENT_OP_TYPES.DELETE_ROW) for (const key of identityKeysIn(before)) outside.delete(key);
|
|
2689
|
+
outside.add(slotKey({
|
|
2690
|
+
space: IDENTITY_SPACES.REVISION,
|
|
2691
|
+
id: revision.id
|
|
2692
|
+
}));
|
|
2693
|
+
const freshened = freshenIdentities({
|
|
2694
|
+
before,
|
|
2695
|
+
after,
|
|
2696
|
+
newIds: newIds ?? {},
|
|
2697
|
+
usedElsewhere: () => outside
|
|
2698
|
+
});
|
|
2699
|
+
switch (freshened.kind) {
|
|
2700
|
+
case "needsIds": return refused({
|
|
2701
|
+
op,
|
|
2702
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
|
|
2703
|
+
message: `The row needs ${freshened.missing} additional revision ids.`
|
|
2704
|
+
});
|
|
2705
|
+
case "invalidId": return refused({
|
|
2706
|
+
op,
|
|
2707
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
|
|
2708
|
+
message: `${freshened.id} cannot be a new revision id.`
|
|
2709
|
+
});
|
|
2710
|
+
case "fresh": {
|
|
2711
|
+
const byId = new Map(freshened.paragraphs.map((paragraph) => [idKey(paragraph.paraId ?? ""), paragraph]));
|
|
2712
|
+
return Result.ok({
|
|
2713
|
+
...rowWithParagraphs(row, (paragraph) => byId.get(idKey(paragraph.paraId ?? "")) ?? panic("A tracked row lost a paragraph.")),
|
|
2714
|
+
structuralChange: {
|
|
2715
|
+
type: kind === WRAP_KINDS.INSERTION ? "tableRowInsertion" : "tableRowDeletion",
|
|
2716
|
+
info: stampInfo(revision)
|
|
2717
|
+
}
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
default: return freshened;
|
|
2721
|
+
}
|
|
2722
|
+
};
|
|
2723
|
+
const withRows = ({ document, story, location, rows }) => {
|
|
2724
|
+
const body = storyBody(document, story);
|
|
2725
|
+
const content = updateBlockList(body.content, location.list, (blocks) => {
|
|
2726
|
+
const out = [...blocks];
|
|
2727
|
+
out[location.index] = {
|
|
2728
|
+
...location.table,
|
|
2729
|
+
rows
|
|
2730
|
+
};
|
|
2731
|
+
return out;
|
|
2732
|
+
});
|
|
2733
|
+
switch (story) {
|
|
2734
|
+
case OP_STORIES.MAIN: return {
|
|
2735
|
+
...document,
|
|
2736
|
+
package: {
|
|
2737
|
+
...document.package,
|
|
2738
|
+
document: withBodyContent(body, content)
|
|
2739
|
+
}
|
|
2740
|
+
};
|
|
2741
|
+
default: return story;
|
|
2742
|
+
}
|
|
2743
|
+
};
|
|
2744
|
+
const commitRows = ({ document, op, location, rows }) => {
|
|
2745
|
+
if (rows.length === 0) return refused({
|
|
2746
|
+
op,
|
|
2747
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2748
|
+
message: "Removing the last row requires a table operation."
|
|
2749
|
+
});
|
|
2750
|
+
const before = location.table.rows;
|
|
2751
|
+
if (structurallyEqual(before, rows)) return Result.ok({
|
|
2752
|
+
document,
|
|
2753
|
+
inverse: [],
|
|
2754
|
+
touched: {
|
|
2755
|
+
modified: [],
|
|
2756
|
+
inserted: [],
|
|
2757
|
+
removed: []
|
|
2758
|
+
}
|
|
2759
|
+
});
|
|
2760
|
+
const afterParagraphs = paragraphsIn(rows);
|
|
2761
|
+
if (rows.some((row) => row.cells.length === 0 || row.cells.some((cell) => storyParagraphs({ content: cell.content }).length === 0))) return refused({
|
|
2762
|
+
op,
|
|
2763
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
|
|
2764
|
+
message: "Every row has cells, and every cell has a paragraph."
|
|
2765
|
+
});
|
|
2766
|
+
if (afterParagraphs.some(({ content }) => textsIn(content).some(hasIllegalXmlCharacters))) return refused({
|
|
2767
|
+
op,
|
|
2768
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT,
|
|
2769
|
+
message: "The row holds text that cannot be written to XML."
|
|
2770
|
+
});
|
|
2771
|
+
const body = { content: [{
|
|
2772
|
+
type: "table",
|
|
2773
|
+
rows
|
|
2774
|
+
}] };
|
|
2775
|
+
const originalParagraphs = new Map(paragraphsIn(before).map((paragraph) => [idKey(paragraph.paraId ?? ""), paragraph]));
|
|
2776
|
+
for (const paragraphLocation of storyParagraphs(body)) {
|
|
2777
|
+
const mark = paragraphLocation.paragraph.pPrMark;
|
|
2778
|
+
if (mark !== void 0 && endsItsContainer(body, paragraphLocation) && !structurallyEqual(mark, originalParagraphs.get(idKey(paragraphLocation.paragraph.paraId ?? ""))?.pPrMark)) return refused({
|
|
2779
|
+
op,
|
|
2780
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK,
|
|
2781
|
+
message: "A row operation cannot add a mark to a cell's final paragraph."
|
|
2782
|
+
});
|
|
2783
|
+
}
|
|
2784
|
+
const beforeIds = new Set(paragraphIdsIn(before).map(idKey));
|
|
2785
|
+
if (afterParagraphs.some(({ paraId }) => paraId === void 0 || !beforeIds.has(idKey(paraId)) && !isParaId(paraId))) return refused({
|
|
2786
|
+
op,
|
|
2787
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
|
|
2788
|
+
message: "An added paragraph has no usable id."
|
|
2789
|
+
});
|
|
2790
|
+
const remainingParagraphs = countIds(packageParagraphIds(document.package));
|
|
2791
|
+
for (const id of paragraphIdsIn(before)) remainingParagraphs.set(idKey(id), (remainingParagraphs.get(idKey(id)) ?? 1) - 1);
|
|
2792
|
+
if (collides(remainingParagraphs, paragraphIdsIn(rows))) return refused({
|
|
2793
|
+
op,
|
|
2794
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
|
|
2795
|
+
message: "A row paragraph id is already used in the package."
|
|
2796
|
+
});
|
|
2797
|
+
const remainingRecords = countKeys(packageIdentityKeys(document.package));
|
|
2798
|
+
for (const key of identityKeysIn(before)) remainingRecords.set(key, (remainingRecords.get(key) ?? 1) - 1);
|
|
2799
|
+
const incomingRecords = identityKeysIn(rows);
|
|
2800
|
+
if (incomingRecords.some((key) => (remainingRecords.get(key) ?? 0) > 0) || new Set(incomingRecords).size !== incomingRecords.length) return refused({
|
|
2801
|
+
op,
|
|
2802
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
|
|
2803
|
+
message: "A row revision or content-control id is already used in the package."
|
|
2804
|
+
});
|
|
2805
|
+
const next = withRows({
|
|
2806
|
+
document,
|
|
2807
|
+
story: op.story,
|
|
2808
|
+
location,
|
|
2809
|
+
rows
|
|
2810
|
+
});
|
|
2811
|
+
const valid = validateOpsDocument(next);
|
|
2812
|
+
if (valid.isErr()) return refused({
|
|
2813
|
+
op,
|
|
2814
|
+
reason: valid.error.reason,
|
|
2815
|
+
message: valid.error.message
|
|
2816
|
+
});
|
|
2817
|
+
const afterIds = new Set(paragraphIdsIn(rows).map(idKey));
|
|
2818
|
+
const beforeParagraphIds = paragraphIdsIn(before);
|
|
2819
|
+
const afterParagraphIds = paragraphIdsIn(rows);
|
|
2820
|
+
const changedIds = new Set(rows.filter((row) => !before.includes(row)).flatMap(paragraphIdsIn).map(idKey));
|
|
2821
|
+
const anchor = afterParagraphIds.at(0);
|
|
2822
|
+
if (anchor === void 0) return panic("A row list must have an addressable paragraph.");
|
|
2823
|
+
return Result.ok({
|
|
2824
|
+
document: next,
|
|
2825
|
+
inverse: [{
|
|
2826
|
+
type: DOCUMENT_OP_TYPES.SET_TABLE_ROWS,
|
|
2827
|
+
story: op.story,
|
|
2828
|
+
blockId: anchor,
|
|
2829
|
+
expected: rows,
|
|
2830
|
+
rows: before
|
|
2831
|
+
}],
|
|
2832
|
+
touched: {
|
|
2833
|
+
modified: beforeParagraphIds.filter((id) => afterIds.has(idKey(id)) && changedIds.has(idKey(id))),
|
|
2834
|
+
inserted: afterParagraphIds.filter((id) => !beforeIds.has(idKey(id))),
|
|
2835
|
+
removed: beforeParagraphIds.filter((id) => !afterIds.has(idKey(id)))
|
|
2836
|
+
}
|
|
2837
|
+
});
|
|
2838
|
+
};
|
|
2839
|
+
const applyRowOp = (document, op) => {
|
|
2840
|
+
const located = locateTableRow(document, op);
|
|
2841
|
+
if (located.isErr()) return Result.err(located.error);
|
|
2842
|
+
const location = located.value;
|
|
2843
|
+
const before = location.table.rows;
|
|
2844
|
+
const rows = [...before];
|
|
2845
|
+
switch (op.type) {
|
|
2846
|
+
case DOCUMENT_OP_TYPES.INSERT_ROW: {
|
|
2847
|
+
if (!Number.isInteger(op.at) || op.at < 0 || op.at > rows.length) return refused({
|
|
2848
|
+
op,
|
|
2849
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET,
|
|
2850
|
+
message: "The row index is outside the table."
|
|
2851
|
+
});
|
|
2852
|
+
if (needsTableEdit(location.table)) return refused({
|
|
2853
|
+
op,
|
|
2854
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2855
|
+
message: "Indexed table markup or shared row wrappers require a table operation."
|
|
2856
|
+
});
|
|
2857
|
+
const incoming = structuredClone(op.row);
|
|
2858
|
+
if (paragraphIdsIn(incoming).some((id) => paragraphIdsIn(before).some((existing) => idKey(existing) === idKey(id)))) return refused({
|
|
2859
|
+
op,
|
|
2860
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
|
|
2861
|
+
message: "An inserted paragraph id is already used in the table."
|
|
2862
|
+
});
|
|
2863
|
+
const tracked = op.revision === void 0 ? Result.ok(incoming) : trackRow({
|
|
2864
|
+
document,
|
|
2865
|
+
op,
|
|
2866
|
+
row: incoming,
|
|
2867
|
+
revision: op.revision,
|
|
2868
|
+
newIds: op.newIds,
|
|
2869
|
+
kind: WRAP_KINDS.INSERTION
|
|
2870
|
+
});
|
|
2871
|
+
if (tracked.isErr()) return Result.err(tracked.error);
|
|
2872
|
+
rows.splice(op.at, 0, tracked.value);
|
|
2873
|
+
return commitRows({
|
|
2874
|
+
document,
|
|
2875
|
+
op,
|
|
2876
|
+
location,
|
|
2877
|
+
rows
|
|
2878
|
+
});
|
|
2879
|
+
}
|
|
2880
|
+
case DOCUMENT_OP_TYPES.DELETE_ROW: {
|
|
2881
|
+
const row = before[location.rowIndex];
|
|
2882
|
+
if (row === void 0) return panic("A row location must name a row.");
|
|
2883
|
+
if (op.expected !== void 0 && !equalForStaleness(row, op.expected)) return refused({
|
|
2884
|
+
op,
|
|
2885
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
|
|
2886
|
+
message: "The row to remove has changed."
|
|
2887
|
+
});
|
|
2888
|
+
if (needsTableEdit(location.table)) return refused({
|
|
2889
|
+
op,
|
|
2890
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2891
|
+
message: "Indexed table markup or shared row wrappers require a table operation."
|
|
2892
|
+
});
|
|
2893
|
+
if (op.revision === void 0) rows.splice(location.rowIndex, 1);
|
|
2894
|
+
else {
|
|
2895
|
+
if (before.filter((candidate) => candidate.structuralChange?.type !== "tableRowDeletion").length <= 1) return refused({
|
|
2896
|
+
op,
|
|
2897
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2898
|
+
message: "Deleting the last remaining row requires a table operation."
|
|
2899
|
+
});
|
|
2900
|
+
const tracked = trackRow({
|
|
2901
|
+
document,
|
|
2902
|
+
op,
|
|
2903
|
+
row,
|
|
2904
|
+
revision: op.revision,
|
|
2905
|
+
newIds: op.newIds,
|
|
2906
|
+
kind: WRAP_KINDS.DELETION
|
|
2907
|
+
});
|
|
2908
|
+
if (tracked.isErr()) return Result.err(tracked.error);
|
|
2909
|
+
rows[location.rowIndex] = tracked.value;
|
|
2910
|
+
}
|
|
2911
|
+
return commitRows({
|
|
2912
|
+
document,
|
|
2913
|
+
op,
|
|
2914
|
+
location,
|
|
2915
|
+
rows
|
|
2916
|
+
});
|
|
2917
|
+
}
|
|
2918
|
+
case DOCUMENT_OP_TYPES.SET_TABLE_ROWS: {
|
|
2919
|
+
if (!equalForStaleness(before, op.expected)) return refused({
|
|
2920
|
+
op,
|
|
2921
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
|
|
2922
|
+
message: "The table rows have changed."
|
|
2923
|
+
});
|
|
2924
|
+
if (op.rows.length !== before.length && needsTableEdit(location.table)) return refused({
|
|
2925
|
+
op,
|
|
2926
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2927
|
+
message: "Indexed table markup or shared row wrappers require a table operation."
|
|
2928
|
+
});
|
|
2929
|
+
const replacement = op.rows.map((row) => before.find((existing) => structurallyEqual(existing, row)) ?? structuredClone(row));
|
|
2930
|
+
return commitRows({
|
|
2931
|
+
document,
|
|
2932
|
+
op,
|
|
2933
|
+
location,
|
|
2934
|
+
rows: replacement
|
|
2935
|
+
});
|
|
2936
|
+
}
|
|
2937
|
+
default: return op;
|
|
2938
|
+
}
|
|
2939
|
+
};
|
|
2940
|
+
//#endregion
|
|
2941
|
+
//#region src/ops/resolveTableRows.ts
|
|
2942
|
+
/** Row resolution after inline review, before paragraph-mark joins. */
|
|
2943
|
+
const collectTables = (blocks, out) => {
|
|
2944
|
+
for (const block of blocks) switch (block.type) {
|
|
2945
|
+
case "table":
|
|
2946
|
+
for (const row of block.rows) for (const cell of row.cells) collectTables(cell.content, out);
|
|
2947
|
+
out.push(block);
|
|
2948
|
+
break;
|
|
2949
|
+
case "blockSdt":
|
|
2950
|
+
case "blockCustomXml":
|
|
2951
|
+
collectTables(block.content, out);
|
|
2952
|
+
break;
|
|
2953
|
+
case "paragraph":
|
|
2954
|
+
case "preservedBlock":
|
|
2955
|
+
case "bookmarkStart":
|
|
2956
|
+
case "bookmarkEnd": break;
|
|
2957
|
+
default: return block;
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
const tablesIn = (document, story) => {
|
|
2961
|
+
const out = [];
|
|
2962
|
+
collectTables(storyBody(document, story).content, out);
|
|
2963
|
+
return out;
|
|
2964
|
+
};
|
|
2965
|
+
/** Only row insert/delete records are reachable; cell and property revisions remain refused. */
|
|
2966
|
+
const reachableRowIds = (document, story) => tablesIn(document, story).flatMap((table) => table.rows.flatMap((row) => {
|
|
2967
|
+
const change = row.structuralChange;
|
|
2968
|
+
return change?.type === "tableRowInsertion" || change?.type === "tableRowDeletion" ? [change.info.id] : [];
|
|
2969
|
+
}));
|
|
2970
|
+
const resolveTableRows = ({ document, op, applyOps }) => {
|
|
2971
|
+
const ids = new Set(op.revisionIds);
|
|
2972
|
+
let current = document;
|
|
2973
|
+
const edits = [];
|
|
2974
|
+
for (const table of tablesIn(document, op.story)) {
|
|
2975
|
+
if (!table.rows.some((row) => row.structuralChange !== void 0 && ids.has(row.structuralChange.info.id))) continue;
|
|
2976
|
+
const blockId = storyParagraphs({ content: [table] }).find(({ list }) => list.filter((step) => step.kind === "tableCell").length === 1)?.paragraph.paraId;
|
|
2977
|
+
if (blockId === void 0) return Result.err(new DocumentOpRefusal({
|
|
2978
|
+
opType: op.type,
|
|
2979
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
|
|
2980
|
+
message: "The table has no paragraph that can address its rows."
|
|
2981
|
+
}));
|
|
2982
|
+
const target = {
|
|
2983
|
+
type: DOCUMENT_OP_TYPES.SET_TABLE_ROWS,
|
|
2984
|
+
story: op.story,
|
|
2985
|
+
blockId,
|
|
2986
|
+
expected: table.rows,
|
|
2987
|
+
rows: table.rows
|
|
2988
|
+
};
|
|
2989
|
+
const located = locateTableRow(current, target);
|
|
2990
|
+
if (located.isErr()) return Result.err(located.error);
|
|
2991
|
+
const expected = located.value.table.rows;
|
|
2992
|
+
const rows = expected.flatMap((row) => {
|
|
2993
|
+
const change = row.structuralChange;
|
|
2994
|
+
if (change === void 0 || !ids.has(change.info.id)) return [row];
|
|
2995
|
+
if (change.type === "tableRowInsertion" !== (op.decision === REVISION_DECISIONS.ACCEPT)) return [];
|
|
2996
|
+
const next = { ...row };
|
|
2997
|
+
delete next.structuralChange;
|
|
2998
|
+
return [next];
|
|
2999
|
+
});
|
|
3000
|
+
const applied = applyOps(current, [{
|
|
3001
|
+
type: DOCUMENT_OP_TYPES.SET_TABLE_ROWS,
|
|
3002
|
+
story: op.story,
|
|
3003
|
+
blockId,
|
|
3004
|
+
expected,
|
|
3005
|
+
rows
|
|
3006
|
+
}]);
|
|
3007
|
+
if (applied.isErr()) return Result.err(applied.error);
|
|
3008
|
+
edits.push(applied.value);
|
|
3009
|
+
current = applied.value.document;
|
|
3010
|
+
}
|
|
3011
|
+
return Result.ok(combineEdits(document, edits));
|
|
3012
|
+
};
|
|
3013
|
+
//#endregion
|
|
3014
|
+
//#region src/ops/resolve.ts
|
|
3015
|
+
/**
|
|
3016
|
+
* `resolveRevision`: accepting or rejecting tracked changes, expanded to the
|
|
3017
|
+
* primitive operations that carry it out.
|
|
3018
|
+
*
|
|
3019
|
+
* The expansion follows the order an editor resolves a review in. First each
|
|
3020
|
+
* paragraph's inline changes (insertions, deletions and moves, nested ones
|
|
3021
|
+
* included, and run property changes) become one `replaceInline`, and its
|
|
3022
|
+
* property changes and kept marks one `setParagraphReview`. Then the marks
|
|
3023
|
+
* that go are removed, from the last paragraph to the first: each leaves the
|
|
3024
|
+
* next paragraph, which takes the content before it, so a chain of removed
|
|
3025
|
+
* marks ends in the paragraph after the last.
|
|
3026
|
+
*/
|
|
3027
|
+
const refusal$1 = (op, reason, message) => new DocumentOpRefusal({
|
|
3028
|
+
message,
|
|
3029
|
+
reason,
|
|
3030
|
+
opType: op.type
|
|
3031
|
+
});
|
|
3032
|
+
/** Whether a decision removes the content of a tracked change of this kind. */
|
|
3033
|
+
const removesContent = (node, decision) => decision === REVISION_DECISIONS.ACCEPT ? !isAddedRevision(node) : isAddedRevision(node);
|
|
3034
|
+
/** Whether a mark of this kind recorded a break being added. */
|
|
3035
|
+
const markWasAdded = (kind) => kind === "ins" || kind === "moveTo";
|
|
3036
|
+
const removePropertyChanges = (changes, remove) => {
|
|
3037
|
+
const remaining = [];
|
|
3038
|
+
let removedPrevious = void 0;
|
|
3039
|
+
let removedAny = false;
|
|
3040
|
+
let removing = false;
|
|
3041
|
+
for (const change of changes) {
|
|
3042
|
+
if (remove(change)) {
|
|
3043
|
+
if (!removing) {
|
|
3044
|
+
removedPrevious = change.previousFormatting;
|
|
3045
|
+
removing = true;
|
|
3046
|
+
}
|
|
3047
|
+
removedAny = true;
|
|
3048
|
+
continue;
|
|
3049
|
+
}
|
|
3050
|
+
if (!removing) {
|
|
3051
|
+
remaining.push(change);
|
|
3052
|
+
continue;
|
|
3053
|
+
}
|
|
3054
|
+
const rebased = { ...change };
|
|
3055
|
+
delete rebased.previousFormatting;
|
|
3056
|
+
if (removedPrevious !== void 0) Object.assign(rebased, { previousFormatting: removedPrevious });
|
|
3057
|
+
remaining.push(rebased);
|
|
3058
|
+
removedPrevious = void 0;
|
|
3059
|
+
removing = false;
|
|
3060
|
+
}
|
|
3061
|
+
if (!removedAny) return { kind: "unchanged" };
|
|
3062
|
+
if (!removing) return {
|
|
3063
|
+
kind: "keepLive",
|
|
3064
|
+
remaining
|
|
3065
|
+
};
|
|
3066
|
+
return {
|
|
3067
|
+
kind: "restore",
|
|
3068
|
+
remaining,
|
|
3069
|
+
previous: removedPrevious
|
|
3070
|
+
};
|
|
3071
|
+
};
|
|
3072
|
+
const NOTHING_EMPTIED = { has: () => false };
|
|
3073
|
+
const resolveRun = (run, { ids, decision }) => {
|
|
3074
|
+
const changes = run.propertyChanges ?? [];
|
|
3075
|
+
const selected = (change) => ids.has(change.info.id);
|
|
3076
|
+
if (!changes.some(selected)) return run;
|
|
3077
|
+
const next = { ...run };
|
|
3078
|
+
let remaining = changes.filter((change) => !selected(change));
|
|
3079
|
+
if (decision === REVISION_DECISIONS.REJECT) {
|
|
3080
|
+
const removed = removePropertyChanges(changes, selected);
|
|
3081
|
+
if (removed.kind !== "unchanged") remaining = removed.remaining;
|
|
3082
|
+
if (removed.kind === "restore") if (removed.previous === void 0) delete next.formatting;
|
|
3083
|
+
else next.formatting = removed.previous;
|
|
3084
|
+
}
|
|
3085
|
+
if (remaining.length > 0) next.propertyChanges = remaining;
|
|
3086
|
+
else delete next.propertyChanges;
|
|
3087
|
+
return next;
|
|
3088
|
+
};
|
|
3089
|
+
/**
|
|
3090
|
+
* Whether `empty` is a piece of `other` that resolution left with nothing: a
|
|
3091
|
+
* container of the same kind and fields that the resolution emptied, where
|
|
3092
|
+
* the other holds something. A container that held nothing before (an empty
|
|
3093
|
+
* content control or hyperlink) is markup of its own and is never merged.
|
|
3094
|
+
*/
|
|
3095
|
+
const emptyPieceOf = (empty, other, emptied) => {
|
|
3096
|
+
const emptyChildren = childNodes(empty);
|
|
3097
|
+
const otherChildren = childNodes(other);
|
|
3098
|
+
return empty.type !== "run" && emptyChildren !== void 0 && otherChildren !== void 0 && emptyChildren.length === 0 && otherChildren.length > 0 && emptied.has(empty) && sameOwnFields(empty, other);
|
|
3099
|
+
};
|
|
3100
|
+
/**
|
|
3101
|
+
* Two records meeting where a change was resolved, merged as far as they are
|
|
3102
|
+
* alike. A piece of a cut container that resolution emptied (one `emptied`
|
|
3103
|
+
* holds) goes into the piece it was cut from, which keeps the first one's ids.
|
|
3104
|
+
* Two alike containers merged meet inside too, and that seam is merged the
|
|
3105
|
+
* same way, emptied pieces included, so a merge leaves no seam it would merge
|
|
3106
|
+
* again.
|
|
3107
|
+
*/
|
|
3108
|
+
const mergeAtSeam = (left, right, emptied = NOTHING_EMPTIED) => {
|
|
3109
|
+
if (alikeDepth(left, right) > 0) {
|
|
3110
|
+
const leftChildren = childNodes(left);
|
|
3111
|
+
const rightChildren = childNodes(right);
|
|
3112
|
+
return leftChildren === void 0 || rightChildren === void 0 ? mergeAlike([left], [right]) : [rebuildNode(left, mergedAtSeam(leftChildren, rightChildren, emptied))];
|
|
3113
|
+
}
|
|
3114
|
+
if (emptyPieceOf(left, right, emptied)) return [rebuildNode(left, childNodes(right) ?? [])];
|
|
3115
|
+
return emptyPieceOf(right, left, emptied) ? [left] : [left, right];
|
|
3116
|
+
};
|
|
3117
|
+
/** Two lists end to end, merged at the seam as {@link mergeAtSeam} merges. */
|
|
3118
|
+
const mergedAtSeam = (left, right, emptied) => {
|
|
3119
|
+
const last = left.at(-1);
|
|
3120
|
+
const first = right.at(0);
|
|
3121
|
+
if (last === void 0 || first === void 0) return [...left, ...right];
|
|
3122
|
+
return [
|
|
3123
|
+
...left.slice(0, -1),
|
|
3124
|
+
...mergeAtSeam(last, first, emptied),
|
|
3125
|
+
...right.slice(1)
|
|
3126
|
+
];
|
|
3127
|
+
};
|
|
3128
|
+
/**
|
|
3129
|
+
* A list with its tracked changes resolved. Where a change was resolved,
|
|
3130
|
+
* the records left meeting are merged as far as they are alike.
|
|
3131
|
+
*/
|
|
3132
|
+
const resolveList = (nodes, resolution) => {
|
|
3133
|
+
const out = [];
|
|
3134
|
+
const seams = [];
|
|
3135
|
+
let changed = false;
|
|
3136
|
+
for (const node of nodes) {
|
|
3137
|
+
if (isTrackedWrapper(node) && resolution.ids.has(node.info.id)) {
|
|
3138
|
+
changed = true;
|
|
3139
|
+
seams.push(out.length);
|
|
3140
|
+
if (removesContent(node, resolution.decision)) continue;
|
|
3141
|
+
out.push(...resolveList(node.content, resolution).nodes);
|
|
3142
|
+
seams.push(out.length);
|
|
3143
|
+
continue;
|
|
3144
|
+
}
|
|
3145
|
+
if (node.type === "run") {
|
|
3146
|
+
const run = resolveRun(node, resolution);
|
|
3147
|
+
if (run !== node) {
|
|
3148
|
+
changed = true;
|
|
3149
|
+
seams.push(out.length, out.length + 1);
|
|
3150
|
+
}
|
|
3151
|
+
out.push(run);
|
|
3152
|
+
continue;
|
|
3153
|
+
}
|
|
3154
|
+
const children = childNodes(node);
|
|
3155
|
+
const inner = children === void 0 ? void 0 : resolveList(children, resolution);
|
|
3156
|
+
if (children === void 0 || inner === void 0 || !inner.changed) {
|
|
3157
|
+
out.push(node);
|
|
3158
|
+
continue;
|
|
3159
|
+
}
|
|
3160
|
+
changed = true;
|
|
3161
|
+
if (isTrackedWrapper(node) && inner.nodes.length === 0 && children.length > 0) {
|
|
3162
|
+
seams.push(out.length);
|
|
3163
|
+
continue;
|
|
3164
|
+
}
|
|
3165
|
+
const rebuilt = rebuildNode(node, inner.nodes);
|
|
3166
|
+
if (inner.nodes.length === 0) resolution.emptied.add(rebuilt);
|
|
3167
|
+
out.push(rebuilt);
|
|
3168
|
+
}
|
|
3169
|
+
if (!changed) return {
|
|
3170
|
+
nodes: out,
|
|
3171
|
+
changed
|
|
3172
|
+
};
|
|
3173
|
+
for (const seam of [...new Set(seams)].toSorted((left, right) => right - left)) {
|
|
3174
|
+
const left = out[seam - 1];
|
|
3175
|
+
const right = out[seam];
|
|
3176
|
+
if (left === void 0 || right === void 0) continue;
|
|
3177
|
+
out.splice(seam - 1, 2, ...mergeAtSeam(left, right, resolution.emptied));
|
|
3178
|
+
}
|
|
3179
|
+
return {
|
|
3180
|
+
nodes: out,
|
|
3181
|
+
changed
|
|
3182
|
+
};
|
|
3183
|
+
};
|
|
3184
|
+
/** A paragraph's review fields once its property changes and mark are resolved; `undefined` when unchanged. */
|
|
3185
|
+
const resolveParagraphReview = (paragraph, { ids, decision }, keepsBreak) => {
|
|
3186
|
+
const review = reviewFieldsOf(paragraph);
|
|
3187
|
+
let changed = false;
|
|
3188
|
+
const changes = paragraph.propertyChanges ?? [];
|
|
3189
|
+
const selected = (change) => ids.has(change.info.id);
|
|
3190
|
+
if (changes.some(selected)) {
|
|
3191
|
+
changed = true;
|
|
3192
|
+
let remaining = changes.filter((change) => !selected(change));
|
|
3193
|
+
if (decision === REVISION_DECISIONS.REJECT) {
|
|
3194
|
+
const removed = removePropertyChanges(changes, selected);
|
|
3195
|
+
if (removed.kind !== "unchanged") remaining = removed.remaining;
|
|
3196
|
+
if (removed.kind === "restore") {
|
|
3197
|
+
const restored = withMarkFormatting(removed.previous, paragraph.formatting);
|
|
3198
|
+
if (restored === void 0) delete review.formatting;
|
|
3199
|
+
else review.formatting = restored;
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
if (remaining.length > 0) review.propertyChanges = remaining;
|
|
3203
|
+
else delete review.propertyChanges;
|
|
3204
|
+
}
|
|
3205
|
+
if (keepsBreak) {
|
|
3206
|
+
changed = true;
|
|
3207
|
+
delete review.pPrMark;
|
|
3208
|
+
}
|
|
3209
|
+
return changed ? review : void 0;
|
|
3210
|
+
};
|
|
3211
|
+
/** Revision ids resolution reaches: tracked changes and run property changes in content, and a paragraph's own. */
|
|
3212
|
+
const reachableIds = (paragraph) => {
|
|
3213
|
+
const out = /* @__PURE__ */ new Set();
|
|
3214
|
+
for (const change of paragraph.propertyChanges ?? []) out.add(change.info.id);
|
|
3215
|
+
if (paragraph.pPrMark !== void 0) out.add(paragraph.pPrMark.info.id);
|
|
3216
|
+
const visit = (nodes) => {
|
|
3217
|
+
for (const node of nodes) {
|
|
3218
|
+
if (isTrackedWrapper(node)) out.add(node.info.id);
|
|
3219
|
+
if (node.type === "run") for (const change of node.propertyChanges ?? []) out.add(change.info.id);
|
|
3220
|
+
visit(childNodes(node) ?? []);
|
|
3221
|
+
}
|
|
3222
|
+
};
|
|
3223
|
+
visit(paragraph.content);
|
|
3224
|
+
return out;
|
|
3225
|
+
};
|
|
3226
|
+
const NO_EMPTIED_ENDS = {
|
|
3227
|
+
first: false,
|
|
3228
|
+
last: false
|
|
3229
|
+
};
|
|
3230
|
+
/** The innermost record at one edge of a list, down the chain of first or last children. */
|
|
3231
|
+
const edgeRecord = (nodes, edge) => {
|
|
3232
|
+
const at = (list) => edge === "first" ? list.at(0) : list.at(-1);
|
|
3233
|
+
let node = at(nodes);
|
|
3234
|
+
while (node !== void 0) {
|
|
3235
|
+
const children = childNodes(node);
|
|
3236
|
+
const inner = children === void 0 ? void 0 : at(children);
|
|
3237
|
+
if (inner === void 0) return node;
|
|
3238
|
+
node = inner;
|
|
3239
|
+
}
|
|
3240
|
+
return node;
|
|
3241
|
+
};
|
|
3242
|
+
/** Which edges of a list end in a record `emptied` holds. */
|
|
3243
|
+
const emptiedEndsOf = (nodes, emptied) => {
|
|
3244
|
+
const first = edgeRecord(nodes, "first");
|
|
3245
|
+
const last = edgeRecord(nodes, "last");
|
|
3246
|
+
return {
|
|
3247
|
+
first: first !== void 0 && emptied.has(first),
|
|
3248
|
+
last: last !== void 0 && emptied.has(last)
|
|
3249
|
+
};
|
|
3250
|
+
};
|
|
3251
|
+
/**
|
|
3252
|
+
* The operations that remove a paragraph's resolved mark, against the document
|
|
3253
|
+
* as it stands. `ends` is updated for the paragraph a join leaves.
|
|
3254
|
+
*/
|
|
3255
|
+
const joinOps = (document, { op, story, paraId, added }, ends) => {
|
|
3256
|
+
const body = storyBody(document, story);
|
|
3257
|
+
const location = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(paraId));
|
|
3258
|
+
if (location === void 0) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, `No paragraph is ${paraId}.`));
|
|
3259
|
+
const { paragraph } = location;
|
|
3260
|
+
if (paragraph.sectionProperties !== void 0) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, `The mark of ${paraId} ends a section: joining it is a section operation.`));
|
|
3261
|
+
const blocks = blockListAt(body.content, location.list);
|
|
3262
|
+
const next = blocks[location.index + 1];
|
|
3263
|
+
const empty = paragraphLength(paragraph) === 0;
|
|
3264
|
+
if (next?.type === "paragraph") {
|
|
3265
|
+
const firstEnds = ends.get(idKey(paraId)) ?? NO_EMPTIED_ENDS;
|
|
3266
|
+
const nextId = idKey(next.paraId ?? "");
|
|
3267
|
+
const nextEnds = ends.get(nextId) ?? NO_EMPTIED_ENDS;
|
|
3268
|
+
const emptied = /* @__PURE__ */ new Set();
|
|
3269
|
+
const marked = [
|
|
3270
|
+
[
|
|
3271
|
+
paragraph.content,
|
|
3272
|
+
"first",
|
|
3273
|
+
firstEnds.first
|
|
3274
|
+
],
|
|
3275
|
+
[
|
|
3276
|
+
paragraph.content,
|
|
3277
|
+
"last",
|
|
3278
|
+
firstEnds.last
|
|
3279
|
+
],
|
|
3280
|
+
[
|
|
3281
|
+
next.content,
|
|
3282
|
+
"first",
|
|
3283
|
+
nextEnds.first
|
|
3284
|
+
],
|
|
3285
|
+
[
|
|
3286
|
+
next.content,
|
|
3287
|
+
"last",
|
|
3288
|
+
nextEnds.last
|
|
3289
|
+
]
|
|
3290
|
+
];
|
|
3291
|
+
for (const [content, edge, isEmptied] of marked) {
|
|
3292
|
+
const record = edgeRecord(content, edge);
|
|
3293
|
+
if (isEmptied && record !== void 0) emptied.add(record);
|
|
3294
|
+
}
|
|
3295
|
+
const merged = mergedAtSeam(paragraph.content, next.content, emptied);
|
|
3296
|
+
ends.set(nextId, emptiedEndsOf(merged, emptied));
|
|
3297
|
+
const survivor = {
|
|
3298
|
+
...next,
|
|
3299
|
+
content: asParagraphContent(merged)
|
|
3300
|
+
};
|
|
3301
|
+
return Result.ok([{
|
|
3302
|
+
type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
|
|
3303
|
+
story,
|
|
3304
|
+
expected: [paragraph, next],
|
|
3305
|
+
blocks: [survivor]
|
|
3306
|
+
}]);
|
|
3307
|
+
}
|
|
3308
|
+
if (next !== void 0 && (next.type === "bookmarkStart" || next.type === "bookmarkEnd")) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, `A block-level bookmark stands between ${paraId} and the next paragraph.`));
|
|
3309
|
+
const canGo = added || !endsItsContainer(body, location);
|
|
3310
|
+
if (empty && canGo && blocks.length > 1) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, `Resolving the mark of ${paraId} removes the paragraph, which is a block operation.`));
|
|
3311
|
+
const review = reviewFieldsOf(paragraph);
|
|
3312
|
+
delete review.pPrMark;
|
|
3313
|
+
return Result.ok([{
|
|
3314
|
+
type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
|
|
3315
|
+
story,
|
|
3316
|
+
blockId: paraId,
|
|
3317
|
+
expected: reviewFieldsOf(paragraph),
|
|
3318
|
+
review
|
|
3319
|
+
}]);
|
|
3320
|
+
};
|
|
3321
|
+
/** The main story's own content: the body's blocks, without its comments or section view. */
|
|
3322
|
+
const storyIdentityKeys = (document, story) => new Set(identityKeysIn(storyBody(document, story).content));
|
|
3323
|
+
/**
|
|
3324
|
+
* Resolve tracked changes by revision id, applied as the primitive
|
|
3325
|
+
* operations it expands to. An id no record in the story carries is
|
|
3326
|
+
* skipped; one carried by a record resolution does not reach yet (a table,
|
|
3327
|
+
* cell or section change, a record inside a field) is refused.
|
|
3328
|
+
*/
|
|
3329
|
+
const resolveRevision = (document, op, applyOps) => {
|
|
3330
|
+
if (!Object.values(REVISION_DECISIONS).includes(op.decision)) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A decision accepts or rejects."));
|
|
3331
|
+
if (!op.revisionIds.every((id) => Number.isInteger(id))) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "A revision id is an integer."));
|
|
3332
|
+
const present = storyIdentityKeys(document, op.story);
|
|
3333
|
+
const ids = new Set(op.revisionIds.filter((id) => present.has(slotKey({
|
|
3334
|
+
space: IDENTITY_SPACES.REVISION,
|
|
3335
|
+
id
|
|
3336
|
+
}))));
|
|
3337
|
+
if (ids.size === 0) return Result.ok({
|
|
3338
|
+
document,
|
|
3339
|
+
inverse: [],
|
|
3340
|
+
touched: {
|
|
3341
|
+
modified: [],
|
|
3342
|
+
inserted: [],
|
|
3343
|
+
removed: []
|
|
3344
|
+
}
|
|
3345
|
+
});
|
|
3346
|
+
const resolution = {
|
|
3347
|
+
ids,
|
|
3348
|
+
decision: op.decision,
|
|
3349
|
+
emptied: /* @__PURE__ */ new WeakSet()
|
|
1948
3350
|
};
|
|
3351
|
+
const paragraphs = storyParagraphs(storyBody(document, op.story));
|
|
3352
|
+
const reachable = /* @__PURE__ */ new Set([...paragraphs.flatMap(({ paragraph }) => [...reachableIds(paragraph)]), ...reachableRowIds(document, op.story)]);
|
|
3353
|
+
const unreachable = [...ids].find((id) => !reachable.has(id));
|
|
3354
|
+
if (unreachable !== void 0) return Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, `Revision ${unreachable} is not an inline change, property change, row change or paragraph mark.`));
|
|
3355
|
+
const inline = [];
|
|
3356
|
+
const joins = [];
|
|
3357
|
+
const emptiedEnds = /* @__PURE__ */ new Map();
|
|
3358
|
+
for (const { paragraph } of paragraphs) {
|
|
3359
|
+
const paraId = paragraph.paraId ?? "";
|
|
3360
|
+
const resolved = resolveList(paragraph.content, resolution);
|
|
3361
|
+
if (resolved.changed) {
|
|
3362
|
+
emptiedEnds.set(idKey(paraId), emptiedEndsOf(resolved.nodes, resolution.emptied));
|
|
3363
|
+
inline.push({
|
|
3364
|
+
type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
|
|
3365
|
+
story: op.story,
|
|
3366
|
+
blockId: paraId,
|
|
3367
|
+
expected: paragraph.content,
|
|
3368
|
+
content: asParagraphContent(resolved.nodes)
|
|
3369
|
+
});
|
|
3370
|
+
}
|
|
3371
|
+
const mark = paragraph.pPrMark;
|
|
3372
|
+
const markResolved = mark !== void 0 && ids.has(mark.info.id);
|
|
3373
|
+
const added = mark !== void 0 && markWasAdded(mark.kind);
|
|
3374
|
+
const keepsBreak = markResolved && added === (op.decision === REVISION_DECISIONS.ACCEPT);
|
|
3375
|
+
if (markResolved && !keepsBreak) joins.push({
|
|
3376
|
+
op,
|
|
3377
|
+
story: op.story,
|
|
3378
|
+
paraId,
|
|
3379
|
+
added
|
|
3380
|
+
});
|
|
3381
|
+
const review = resolveParagraphReview(paragraph, resolution, keepsBreak);
|
|
3382
|
+
if (review !== void 0) inline.push({
|
|
3383
|
+
type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
|
|
3384
|
+
story: op.story,
|
|
3385
|
+
blockId: paraId,
|
|
3386
|
+
expected: reviewFieldsOf(paragraph),
|
|
3387
|
+
review
|
|
3388
|
+
});
|
|
3389
|
+
}
|
|
3390
|
+
const staged = applyOps(document, inline);
|
|
3391
|
+
if (staged.isErr()) return Result.err(staged.error);
|
|
3392
|
+
const rows = resolveTableRows({
|
|
3393
|
+
document: staged.value.document,
|
|
3394
|
+
op,
|
|
3395
|
+
applyOps
|
|
3396
|
+
});
|
|
3397
|
+
if (rows.isErr()) return Result.err(rows.error);
|
|
3398
|
+
const removedParagraphs = new Set(rows.value.touched.removed.map(idKey));
|
|
3399
|
+
const edits = [staged.value, rows.value];
|
|
3400
|
+
let current = rows.value.document;
|
|
3401
|
+
for (const join of joins.toReversed()) {
|
|
3402
|
+
if (removedParagraphs.has(idKey(join.paraId))) continue;
|
|
3403
|
+
const planned = joinOps(current, join, emptiedEnds);
|
|
3404
|
+
if (planned.isErr()) return Result.err(planned.error);
|
|
3405
|
+
const joined = applyOps(current, planned.value);
|
|
3406
|
+
if (joined.isErr()) return Result.err(joined.error);
|
|
3407
|
+
edits.push(joined.value);
|
|
3408
|
+
current = joined.value.document;
|
|
3409
|
+
}
|
|
3410
|
+
return Result.ok(combineEdits(document, edits));
|
|
1949
3411
|
};
|
|
1950
3412
|
//#endregion
|
|
1951
3413
|
//#region src/ops/apply.ts
|
|
@@ -1973,9 +3435,19 @@ const patchRunsBetween = (items, from, to, patch, whenEmpty) => {
|
|
|
1973
3435
|
* | `joinInline` | `splitInline` |
|
|
1974
3436
|
* | `setRunProps` | `setRunProps` per stretch of prior values, joining cuts |
|
|
1975
3437
|
* | `setParagraphProps` | `setParagraphProps` with the prior values |
|
|
1976
|
-
* | `splitBlock` | `joinBlocks
|
|
1977
|
-
* | `joinBlocks` | `splitBlock` with the
|
|
3438
|
+
* | `splitBlock` | `joinBlocks`, then the kept half's review fields |
|
|
3439
|
+
* | `joinBlocks` | `splitBlock` with the retired paragraph's fields, then |
|
|
3440
|
+
* | | the survivor's review fields |
|
|
3441
|
+
* | `insertBlocks` | an anchored `replaceBlocks` |
|
|
1978
3442
|
* | `replaceBlocks` | `replaceBlocks` |
|
|
3443
|
+
* | `setParagraphReview`| `setParagraphReview` |
|
|
3444
|
+
* | `replaceInline` | `replaceInline` |
|
|
3445
|
+
* | `resolveRevision` | the inverses of the operations it expands to |
|
|
3446
|
+
*
|
|
3447
|
+
* A tracked operation (one carrying a `revision` stamp, see `review.ts`) is
|
|
3448
|
+
* undone as follows: a tracked insertion by `deleteRange`, a tracked split by
|
|
3449
|
+
* `joinBlocks`, a tracked deletion or run patch by `replaceInline`, and a
|
|
3450
|
+
* tracked paragraph patch or join by `setParagraphReview`.
|
|
1979
3451
|
*
|
|
1980
3452
|
* Each inverse carries its precondition: a deletion the slice it removes, a
|
|
1981
3453
|
* patch the values it replaces, a join the fields of the paragraph it merges
|
|
@@ -1999,6 +3471,35 @@ const refusal = (op, reason, message) => new DocumentOpRefusal({
|
|
|
1999
3471
|
opType: op.type
|
|
2000
3472
|
});
|
|
2001
3473
|
const refuse = (op, reason, message) => Result.err(refusal(op, reason, message));
|
|
3474
|
+
/**
|
|
3475
|
+
* Whether a tracked operation's stamp can name the first record it creates:
|
|
3476
|
+
* a revision id in range that no record in the package carries.
|
|
3477
|
+
*/
|
|
3478
|
+
const stampRefusal = (document, op, stamp) => {
|
|
3479
|
+
const revisionId = stamp.id;
|
|
3480
|
+
if (!Number.isInteger(revisionId) || revisionId < 0 || revisionId > 2147483647) return refusal(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, `${revisionId} cannot be a revision id.`);
|
|
3481
|
+
const key = slotKey({
|
|
3482
|
+
space: IDENTITY_SPACES.REVISION,
|
|
3483
|
+
id: stamp.id
|
|
3484
|
+
});
|
|
3485
|
+
if (packageIdentityKeys(document.package).includes(key)) return refusal(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `Revision id ${stamp.id} is already used in the package.`);
|
|
3486
|
+
};
|
|
3487
|
+
/** The replacement that gives a paragraph back the content it had. */
|
|
3488
|
+
const contentRestoring = (story, result, original) => ({
|
|
3489
|
+
type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
|
|
3490
|
+
story,
|
|
3491
|
+
blockId: result.paraId ?? original.paraId ?? "",
|
|
3492
|
+
expected: result.content,
|
|
3493
|
+
content: original.content
|
|
3494
|
+
});
|
|
3495
|
+
/** The review fields' setting that gives a paragraph back the ones it had. */
|
|
3496
|
+
const reviewRestoring = (story, result, original) => ({
|
|
3497
|
+
type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
|
|
3498
|
+
story,
|
|
3499
|
+
blockId: result.paraId ?? original.paraId ?? "",
|
|
3500
|
+
expected: reviewFieldsOf(result),
|
|
3501
|
+
review: reviewFieldsOf(original)
|
|
3502
|
+
});
|
|
2002
3503
|
/** Characters `insertText` does not carry: each is an inline atom of its own. */
|
|
2003
3504
|
const NON_TEXT_CHARACTER_PATTERN = /[\t\n\r]/u;
|
|
2004
3505
|
const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
|
|
@@ -2155,27 +3656,59 @@ const editOne = (commitOptions, inverseOf) => {
|
|
|
2155
3656
|
touched: committed.value.touched
|
|
2156
3657
|
});
|
|
2157
3658
|
};
|
|
2158
|
-
/**
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
3659
|
+
/**
|
|
3660
|
+
* Content with the leaves between two gaps recorded as a tracked change;
|
|
3661
|
+
* `undefined` when there is nothing to record.
|
|
3662
|
+
*/
|
|
3663
|
+
const wrappedContent = (op, options) => {
|
|
3664
|
+
const wrapped = wrapTracked(options);
|
|
3665
|
+
switch (wrapped.kind) {
|
|
3666
|
+
case "wrapped": return Result.ok(wrapped.content);
|
|
3667
|
+
case "unchanged": return Result.ok(void 0);
|
|
3668
|
+
case "refused": return Result.err(refusal(op, wrapped.reason, wrapped.reason === DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE ? "A tracked change cannot hold a comment boundary or reference." : "The tracked edit falls inside tracked-removed content."));
|
|
3669
|
+
default: return wrapped;
|
|
3670
|
+
}
|
|
3671
|
+
};
|
|
3672
|
+
/**
|
|
3673
|
+
* Commit an insertion, recording the one deletion that undoes it. A tracked
|
|
3674
|
+
* insertion is wrapped first; the deletion removes the wrapper with it.
|
|
3675
|
+
*/
|
|
3676
|
+
const inserted = (options) => {
|
|
3677
|
+
const { document, op, story, location, start, end, newIds, revision } = options;
|
|
3678
|
+
let { content } = options;
|
|
3679
|
+
if (revision !== void 0) {
|
|
3680
|
+
if (insertionInverse(location.paragraph.content, content, start, end) === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate.");
|
|
3681
|
+
const wrapped = wrappedContent(op, {
|
|
3682
|
+
items: content,
|
|
3683
|
+
from: start,
|
|
3684
|
+
to: end,
|
|
3685
|
+
kind: WRAP_KINDS.INSERTION,
|
|
3686
|
+
stamp: revision
|
|
3687
|
+
});
|
|
3688
|
+
if (wrapped.isErr()) return Result.err(wrapped.error);
|
|
3689
|
+
content = wrapped.value ?? content;
|
|
3690
|
+
}
|
|
3691
|
+
return editOne({
|
|
3692
|
+
document,
|
|
3693
|
+
op,
|
|
3694
|
+
story,
|
|
3695
|
+
at: location,
|
|
3696
|
+
paragraph: withContent(location.paragraph, content),
|
|
3697
|
+
newIds,
|
|
3698
|
+
inserted: recordsBetween(content, start, end)
|
|
3699
|
+
}, (result) => {
|
|
3700
|
+
const inverse = insertionInverse(location.paragraph.content, result.content, start, end);
|
|
3701
|
+
if (inverse === void 0) return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate."));
|
|
3702
|
+
const deletion = {
|
|
3703
|
+
type: DOCUMENT_OP_TYPES.DELETE_RANGE,
|
|
3704
|
+
from: positionAt(story, result, start),
|
|
3705
|
+
to: positionAt(story, result, end),
|
|
3706
|
+
expected: inverse.removed
|
|
3707
|
+
};
|
|
3708
|
+
if (inverse.join > 0) deletion.join = inverse.join;
|
|
3709
|
+
return Result.ok([deletion]);
|
|
3710
|
+
});
|
|
3711
|
+
};
|
|
2179
3712
|
const insertText = (document, op) => {
|
|
2180
3713
|
if (op.text === "" || NON_TEXT_CHARACTER_PATTERN.test(op.text) || hasIllegalXmlCharacters(op.text)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The text cannot be inserted.");
|
|
2181
3714
|
const located = locatePosition(document, op, op.at, "afterAll");
|
|
@@ -2200,7 +3733,8 @@ const insertText = (document, op) => {
|
|
|
2200
3733
|
content,
|
|
2201
3734
|
start,
|
|
2202
3735
|
end,
|
|
2203
|
-
newIds: op.newIds
|
|
3736
|
+
newIds: op.newIds,
|
|
3737
|
+
revision: op.revision
|
|
2204
3738
|
});
|
|
2205
3739
|
};
|
|
2206
3740
|
const holdsEmptyRecord = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord(childNodes(node) ?? []));
|
|
@@ -2209,7 +3743,7 @@ const insertContent = (document, op) => {
|
|
|
2209
3743
|
...op.slice,
|
|
2210
3744
|
content: structuredClone(op.slice.content)
|
|
2211
3745
|
};
|
|
2212
|
-
if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run or
|
|
3746
|
+
if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run, text node, or revision wrapper.");
|
|
2213
3747
|
if (!Number.isInteger(slice.openStart) || !Number.isInteger(slice.openEnd) || slice.openStart < 0 || slice.openEnd < 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Open depths are counts.");
|
|
2214
3748
|
if (textsIn(slice.content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The slice holds text that cannot be written.");
|
|
2215
3749
|
const incoming = paragraphIdsIn(slice.content);
|
|
@@ -2227,7 +3761,8 @@ const insertContent = (document, op) => {
|
|
|
2227
3761
|
content,
|
|
2228
3762
|
start: gap,
|
|
2229
3763
|
end: gapAfterInserted(gap, slice.content),
|
|
2230
|
-
newIds: op.newIds
|
|
3764
|
+
newIds: op.newIds,
|
|
3765
|
+
revision: op.revision
|
|
2231
3766
|
});
|
|
2232
3767
|
};
|
|
2233
3768
|
/** A merge's content, or the refusal naming why it cannot be made. */
|
|
@@ -2246,6 +3781,7 @@ const isCount = (value) => Number.isInteger(value) && value >= 0;
|
|
|
2246
3781
|
const deleteRange = (document, op) => {
|
|
2247
3782
|
const join = op.join ?? 0;
|
|
2248
3783
|
if (!isCount(join)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
|
|
3784
|
+
if (op.revision !== void 0 && join !== 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked deletion joins nothing.");
|
|
2249
3785
|
const located = locateRange(document, op, op.from, op.to);
|
|
2250
3786
|
if (located.isErr()) return Result.err(located.error);
|
|
2251
3787
|
const { story, location, from, to, empty } = located.value;
|
|
@@ -2255,6 +3791,25 @@ const deleteRange = (document, op) => {
|
|
|
2255
3791
|
const { content: remaining, removed } = deleteBetween(paragraph.content, from, to);
|
|
2256
3792
|
if (expected !== void 0 && !equalForStaleness(expected, removed)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The range of ${op.from.blockId} holds other content than expected.`);
|
|
2257
3793
|
if (removed.content.length === 0) return unchanged(document);
|
|
3794
|
+
if (op.revision !== void 0) {
|
|
3795
|
+
const wrapped = wrappedContent(op, {
|
|
3796
|
+
items: paragraph.content,
|
|
3797
|
+
from,
|
|
3798
|
+
to,
|
|
3799
|
+
kind: WRAP_KINDS.DELETION,
|
|
3800
|
+
stamp: op.revision
|
|
3801
|
+
});
|
|
3802
|
+
if (wrapped.isErr()) return Result.err(wrapped.error);
|
|
3803
|
+
if (wrapped.value === void 0) return unchanged(document);
|
|
3804
|
+
return editOne({
|
|
3805
|
+
document,
|
|
3806
|
+
op,
|
|
3807
|
+
story,
|
|
3808
|
+
at: location,
|
|
3809
|
+
paragraph: withContent(paragraph, wrapped.value),
|
|
3810
|
+
newIds: op.newIds
|
|
3811
|
+
}, (result) => Result.ok([contentRestoring(story, result, paragraph)]));
|
|
3812
|
+
}
|
|
2258
3813
|
let content = remaining;
|
|
2259
3814
|
let retired = {};
|
|
2260
3815
|
if (join > 0) {
|
|
@@ -2333,6 +3888,8 @@ const setRunProps = (document, op) => {
|
|
|
2333
3888
|
const joinStart = op.joinStart ?? 0;
|
|
2334
3889
|
const joinEnd = op.joinEnd ?? 0;
|
|
2335
3890
|
if (!isCount(joinStart) || !isCount(joinEnd)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
|
|
3891
|
+
const { revision } = op;
|
|
3892
|
+
if (revision !== void 0 && (joinStart !== 0 || joinEnd !== 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked patch joins nothing.");
|
|
2336
3893
|
const located = locateRange(document, op, op.from, op.to);
|
|
2337
3894
|
if (located.isErr()) return Result.err(located.error);
|
|
2338
3895
|
const { story, location, from, to, empty } = located.value;
|
|
@@ -2340,6 +3897,30 @@ const setRunProps = (document, op) => {
|
|
|
2340
3897
|
const { paragraph } = location;
|
|
2341
3898
|
const { expected } = op;
|
|
2342
3899
|
if (expected !== void 0 && !runsBetween(paragraph.content, from, to).every((run) => statesValues(run.formatting, expected))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The runs of ${op.from.blockId} state other values than expected.`);
|
|
3900
|
+
if (revision !== void 0) {
|
|
3901
|
+
const recordChange = (patchedRun, previous) => {
|
|
3902
|
+
if ((previous.propertyChanges?.length ?? 0) > 0) return patchedRun;
|
|
3903
|
+
const change = {
|
|
3904
|
+
type: "runPropertyChange",
|
|
3905
|
+
info: stampInfo(revision)
|
|
3906
|
+
};
|
|
3907
|
+
if (previous.formatting !== void 0) change.previousFormatting = previous.formatting;
|
|
3908
|
+
return {
|
|
3909
|
+
...patchedRun,
|
|
3910
|
+
propertyChanges: [change]
|
|
3911
|
+
};
|
|
3912
|
+
};
|
|
3913
|
+
const tracked = patchRunsBetween(paragraph.content, from, to, op.patch, op.whenEmpty, recordChange);
|
|
3914
|
+
if (tracked === void 0) return unchanged(document);
|
|
3915
|
+
return editOne({
|
|
3916
|
+
document,
|
|
3917
|
+
op,
|
|
3918
|
+
story,
|
|
3919
|
+
at: location,
|
|
3920
|
+
paragraph: withContent(paragraph, tracked.content),
|
|
3921
|
+
newIds: op.newIds
|
|
3922
|
+
}, (result) => Result.ok([contentRestoring(story, result, paragraph)]));
|
|
3923
|
+
}
|
|
2343
3924
|
const patched = patchRunsBetween(paragraph.content, from, to, op.patch, op.whenEmpty);
|
|
2344
3925
|
const patchedContent = patched?.content ?? paragraph.content;
|
|
2345
3926
|
const freshened = withFreshIds({
|
|
@@ -2414,8 +3995,22 @@ const setParagraphProps = (document, op) => {
|
|
|
2414
3995
|
if (located.isErr()) return Result.err(located.error);
|
|
2415
3996
|
const { paragraph } = located.value;
|
|
2416
3997
|
if (op.expected !== void 0 && !statesValues(paragraph.formatting, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other paragraph properties than expected.`);
|
|
3998
|
+
const { revision } = op;
|
|
3999
|
+
if (revision !== void 0 && namesMarkFormatting(op.patch)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A paragraph property change does not record the paragraph mark's run properties.");
|
|
2417
4000
|
const formatting = patchedSet(paragraph.formatting, op.patch, op.whenEmpty);
|
|
2418
4001
|
if (structurallyEqual(formatting ?? {}, paragraph.formatting ?? {})) return unchanged(document);
|
|
4002
|
+
if (revision !== void 0) {
|
|
4003
|
+
const next = withParagraphFormatting(paragraph, formatting);
|
|
4004
|
+
if ((paragraph.propertyChanges?.length ?? 0) === 0) next.propertyChanges = [paragraphPropertyChange(stampInfo(revision), paragraph.formatting)];
|
|
4005
|
+
return editOne({
|
|
4006
|
+
document,
|
|
4007
|
+
op,
|
|
4008
|
+
story: op.story,
|
|
4009
|
+
at: located.value,
|
|
4010
|
+
paragraph: next,
|
|
4011
|
+
newIds: void 0
|
|
4012
|
+
}, (result) => Result.ok([reviewRestoring(op.story, result, paragraph)]));
|
|
4013
|
+
}
|
|
2419
4014
|
return editOne({
|
|
2420
4015
|
document,
|
|
2421
4016
|
op,
|
|
@@ -2442,29 +4037,101 @@ const splitFieldsOf = (paragraph) => {
|
|
|
2442
4037
|
delete fields.pPrMark;
|
|
2443
4038
|
return fields;
|
|
2444
4039
|
};
|
|
4040
|
+
/**
|
|
4041
|
+
* The paragraph properties two paragraphs joined have: the first's paragraph
|
|
4042
|
+
* properties with the second's mark run properties, since the mark that stays
|
|
4043
|
+
* is the second's. A first paragraph that holds no content brings nothing:
|
|
4044
|
+
* the second keeps its own.
|
|
4045
|
+
*/
|
|
4046
|
+
const joinedFormatting = (first, second) => paragraphLength(first) === 0 ? second.formatting : withMarkFormatting(paragraphPropertiesOf(first.formatting), second.formatting);
|
|
4047
|
+
/** The review fields of two paragraphs once joined: the first's properties, the second's mark. */
|
|
4048
|
+
const joinedReview = (first, second) => {
|
|
4049
|
+
const review = {};
|
|
4050
|
+
const formatting = joinedFormatting(first, second);
|
|
4051
|
+
if (formatting !== void 0) review.formatting = formatting;
|
|
4052
|
+
if (second.propertyChanges !== void 0) review.propertyChanges = second.propertyChanges;
|
|
4053
|
+
if (second.pPrMark !== void 0) review.pPrMark = second.pPrMark;
|
|
4054
|
+
return review;
|
|
4055
|
+
};
|
|
4056
|
+
/** A review-field setting from `from` to `to`; none when they are the same. */
|
|
4057
|
+
const reviewSetting = (story, blockId, from, to) => structurallyEqual(from, to) ? [] : [{
|
|
4058
|
+
type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
|
|
4059
|
+
story,
|
|
4060
|
+
blockId,
|
|
4061
|
+
expected: from,
|
|
4062
|
+
review: to
|
|
4063
|
+
}];
|
|
4064
|
+
const isSplitHalf = (value) => value === SPLIT_HALVES.FIRST || value === SPLIT_HALVES.SECOND;
|
|
4065
|
+
/**
|
|
4066
|
+
* Record a split as tracked: the new mark is an insertion, and the new
|
|
4067
|
+
* paragraph records a property change from the source's properties when it
|
|
4068
|
+
* states other ones and carries no change already. Returns the refusal when
|
|
4069
|
+
* the operation states a mark or property change of its own.
|
|
4070
|
+
*/
|
|
4071
|
+
const trackSplit = ({ op, stamp, paragraph, first, made }) => {
|
|
4072
|
+
if (op.firstMark !== void 0 || (op.newParagraph?.propertyChanges?.length ?? 0) > 0) return refusal(op, DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT, "A tracked split records its own mark and property change.");
|
|
4073
|
+
first.pPrMark = {
|
|
4074
|
+
kind: "ins",
|
|
4075
|
+
info: stampInfo(stamp)
|
|
4076
|
+
};
|
|
4077
|
+
if (!sameParagraphProperties(made.formatting, paragraph.formatting) && (made.propertyChanges?.length ?? 0) === 0) made.propertyChanges = [paragraphPropertyChange(stampInfo(stamp), paragraph.formatting)];
|
|
4078
|
+
};
|
|
2445
4079
|
const splitBlock = (document, op) => {
|
|
2446
4080
|
if (!isParaId(op.newBlockId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${op.newBlockId} is not a paragraph id.`);
|
|
2447
4081
|
if (collides(countIds(packageParagraphIds(document.package)), [op.newBlockId])) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `${op.newBlockId} is already used in the package.`);
|
|
4082
|
+
if (op.newHalf !== void 0 && !isSplitHalf(op.newHalf)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
|
|
2448
4083
|
const located = locatePosition(document, op, op.at, "insertion");
|
|
2449
4084
|
if (located.isErr()) return Result.err(located.error);
|
|
2450
4085
|
const { location, gap } = located.value;
|
|
2451
4086
|
const { paragraph } = location;
|
|
4087
|
+
const newHalf = op.newHalf ?? (gap.offset === paragraphLength(paragraph) ? SPLIT_HALVES.SECOND : SPLIT_HALVES.FIRST);
|
|
4088
|
+
if (newHalf === SPLIT_HALVES.SECOND && (op.newParagraph?.propertyChanges?.length ?? 0) > 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The second half takes the paragraph's property changes with its mark.");
|
|
2452
4089
|
const cut = cutAt(paragraph.content, gap);
|
|
2453
|
-
const
|
|
2454
|
-
...paragraph,
|
|
2455
|
-
content: cut.before
|
|
2456
|
-
};
|
|
2457
|
-
delete first.sectionProperties;
|
|
2458
|
-
delete first.pPrMark;
|
|
2459
|
-
if (op.firstMark !== void 0) first.pPrMark = op.firstMark;
|
|
2460
|
-
const second = {
|
|
4090
|
+
const made = {
|
|
2461
4091
|
...op.newParagraph ?? (paragraph.formatting === void 0 ? {} : { formatting: paragraph.formatting }),
|
|
2462
4092
|
type: "paragraph",
|
|
2463
4093
|
paraId: op.newBlockId,
|
|
2464
|
-
content:
|
|
4094
|
+
content: []
|
|
2465
4095
|
};
|
|
2466
|
-
|
|
2467
|
-
|
|
4096
|
+
let first;
|
|
4097
|
+
let second;
|
|
4098
|
+
if (newHalf === SPLIT_HALVES.FIRST) {
|
|
4099
|
+
first = {
|
|
4100
|
+
...made,
|
|
4101
|
+
content: cut.before
|
|
4102
|
+
};
|
|
4103
|
+
second = {
|
|
4104
|
+
...paragraph,
|
|
4105
|
+
content: cut.after
|
|
4106
|
+
};
|
|
4107
|
+
} else {
|
|
4108
|
+
first = {
|
|
4109
|
+
...paragraph,
|
|
4110
|
+
content: cut.before
|
|
4111
|
+
};
|
|
4112
|
+
delete first.sectionProperties;
|
|
4113
|
+
delete first.pPrMark;
|
|
4114
|
+
delete first.propertyChanges;
|
|
4115
|
+
second = {
|
|
4116
|
+
...made,
|
|
4117
|
+
content: cut.after
|
|
4118
|
+
};
|
|
4119
|
+
if (paragraph.propertyChanges !== void 0) second.propertyChanges = paragraph.propertyChanges;
|
|
4120
|
+
if (paragraph.sectionProperties !== void 0) second.sectionProperties = paragraph.sectionProperties;
|
|
4121
|
+
if (paragraph.pPrMark !== void 0) second.pPrMark = paragraph.pPrMark;
|
|
4122
|
+
}
|
|
4123
|
+
if (op.firstMark !== void 0) first.pPrMark = op.firstMark;
|
|
4124
|
+
if (op.revision !== void 0) {
|
|
4125
|
+
const madeHalf = newHalf === SPLIT_HALVES.FIRST ? first : second;
|
|
4126
|
+
const tracked = trackSplit({
|
|
4127
|
+
op,
|
|
4128
|
+
stamp: op.revision,
|
|
4129
|
+
paragraph,
|
|
4130
|
+
first,
|
|
4131
|
+
made: madeHalf
|
|
4132
|
+
});
|
|
4133
|
+
if (tracked !== void 0) return Result.err(tracked);
|
|
4134
|
+
}
|
|
2468
4135
|
const committed = commit({
|
|
2469
4136
|
document,
|
|
2470
4137
|
op,
|
|
@@ -2475,17 +4142,65 @@ const splitBlock = (document, op) => {
|
|
|
2475
4142
|
newIds: op.newIds
|
|
2476
4143
|
});
|
|
2477
4144
|
if (committed.isErr()) return Result.err(committed.error);
|
|
2478
|
-
const [, placedSecond] = committed.value.paragraphs;
|
|
4145
|
+
const [placedFirst = first, placedSecond = second] = committed.value.paragraphs;
|
|
4146
|
+
const kept = newHalf === SPLIT_HALVES.FIRST ? placedSecond : placedFirst;
|
|
4147
|
+
const madePlaced = newHalf === SPLIT_HALVES.FIRST ? placedFirst : placedSecond;
|
|
4148
|
+
const keptId = paragraph.paraId ?? op.at.blockId;
|
|
2479
4149
|
return Result.ok({
|
|
2480
4150
|
document: committed.value.document,
|
|
2481
4151
|
inverse: [{
|
|
2482
4152
|
type: DOCUMENT_OP_TYPES.JOIN_BLOCKS,
|
|
2483
4153
|
story: op.at.story,
|
|
2484
|
-
blockId:
|
|
2485
|
-
nextBlockId:
|
|
4154
|
+
blockId: placedFirst.paraId ?? "",
|
|
4155
|
+
nextBlockId: placedSecond.paraId ?? "",
|
|
2486
4156
|
depth: cut.through.length,
|
|
2487
|
-
|
|
2488
|
-
|
|
4157
|
+
survivor: newHalf === SPLIT_HALVES.FIRST ? SPLIT_HALVES.SECOND : SPLIT_HALVES.FIRST,
|
|
4158
|
+
expectedRetired: splitFieldsOf(madePlaced),
|
|
4159
|
+
expectedSurvivor: reviewFieldsOf(kept)
|
|
4160
|
+
}, ...reviewSetting(op.at.story, kept.paraId ?? keptId, joinedReview(placedFirst, placedSecond), reviewFieldsOf(paragraph))],
|
|
4161
|
+
touched: committed.value.touched
|
|
4162
|
+
});
|
|
4163
|
+
};
|
|
4164
|
+
/**
|
|
4165
|
+
* Record a join as tracked: the first paragraph's mark becomes a deletion,
|
|
4166
|
+
* and the second takes the first's paragraph properties as a property
|
|
4167
|
+
* change, so accepting leaves what the direct join leaves: the second
|
|
4168
|
+
* paragraph, with the first's properties.
|
|
4169
|
+
*/
|
|
4170
|
+
const trackJoin = ({ document, op, stamp, at, leading, trailing }) => {
|
|
4171
|
+
const depth = op.depth ?? 0;
|
|
4172
|
+
if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
|
|
4173
|
+
if ((op.survivor ?? SPLIT_HALVES.SECOND) !== SPLIT_HALVES.SECOND) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Resolving a tracked join leaves the second paragraph.");
|
|
4174
|
+
if (leading.pPrMark !== void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT, `The mark of ${op.blockId} already carries a tracked change.`);
|
|
4175
|
+
const first = {
|
|
4176
|
+
...leading,
|
|
4177
|
+
pPrMark: {
|
|
4178
|
+
kind: "del",
|
|
4179
|
+
info: stampInfo(stamp)
|
|
4180
|
+
}
|
|
4181
|
+
};
|
|
4182
|
+
let second = trailing;
|
|
4183
|
+
const formatting = joinedFormatting(leading, trailing);
|
|
4184
|
+
if (!sameParagraphProperties(formatting, trailing.formatting)) {
|
|
4185
|
+
second = withParagraphFormatting(trailing, formatting);
|
|
4186
|
+
if ((trailing.propertyChanges?.length ?? 0) === 0) second.propertyChanges = [paragraphPropertyChange(stampInfo(stamp), trailing.formatting)];
|
|
4187
|
+
}
|
|
4188
|
+
const committed = commit({
|
|
4189
|
+
document,
|
|
4190
|
+
op,
|
|
4191
|
+
story: op.story,
|
|
4192
|
+
at,
|
|
4193
|
+
before: [leading, trailing],
|
|
4194
|
+
after: [first, second],
|
|
4195
|
+
newIds: op.newIds
|
|
4196
|
+
});
|
|
4197
|
+
if (committed.isErr()) return Result.err(committed.error);
|
|
4198
|
+
const [placedFirst = first, placedSecond = second] = committed.value.paragraphs;
|
|
4199
|
+
const inverse = [reviewRestoring(op.story, placedFirst, leading)];
|
|
4200
|
+
if (second !== trailing) inverse.push(reviewRestoring(op.story, placedSecond, trailing));
|
|
4201
|
+
return Result.ok({
|
|
4202
|
+
document: committed.value.document,
|
|
4203
|
+
inverse,
|
|
2489
4204
|
touched: committed.value.touched
|
|
2490
4205
|
});
|
|
2491
4206
|
};
|
|
@@ -2499,40 +4214,62 @@ const joinBlocks = (document, op) => {
|
|
|
2499
4214
|
const leading = first.value.paragraph;
|
|
2500
4215
|
const trailing = next.value.paragraph;
|
|
2501
4216
|
if (leading.sectionProperties !== void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, `${op.blockId} ends a section.`);
|
|
2502
|
-
|
|
4217
|
+
const survivorSide = op.survivor ?? SPLIT_HALVES.SECOND;
|
|
4218
|
+
if (!isSplitHalf(survivorSide)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
|
|
4219
|
+
const survivor = survivorSide === SPLIT_HALVES.SECOND ? trailing : leading;
|
|
4220
|
+
const retired = survivorSide === SPLIT_HALVES.SECOND ? leading : trailing;
|
|
4221
|
+
if (op.expectedRetired !== void 0 && !equalForStaleness({
|
|
2503
4222
|
type: "paragraph",
|
|
2504
|
-
...splitFieldsOf(
|
|
4223
|
+
...splitFieldsOf(retired)
|
|
2505
4224
|
}, {
|
|
2506
4225
|
type: "paragraph",
|
|
2507
|
-
...op.
|
|
2508
|
-
})) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${
|
|
2509
|
-
|
|
2510
|
-
if (
|
|
4226
|
+
...op.expectedRetired
|
|
4227
|
+
})) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${retired.paraId ?? ""} states other fields than expected.`);
|
|
4228
|
+
if (op.expectedSurvivor !== void 0 && !equalForStaleness(reviewFieldsOf(survivor), op.expectedSurvivor)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${survivor.paraId ?? ""} states other review fields than expected.`);
|
|
4229
|
+
if (op.revision !== void 0) return trackJoin({
|
|
4230
|
+
document,
|
|
4231
|
+
op,
|
|
4232
|
+
stamp: op.revision,
|
|
4233
|
+
at: first.value,
|
|
4234
|
+
leading,
|
|
4235
|
+
trailing
|
|
4236
|
+
});
|
|
4237
|
+
const retiredId = retired.paraId ?? "";
|
|
4238
|
+
if (!isParaId(retiredId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${retiredId} could not name the paragraph again.`);
|
|
2511
4239
|
const depth = op.depth ?? 0;
|
|
2512
4240
|
if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
|
|
2513
4241
|
const merged = joinedContent(op, joinContent(leading.content, trailing.content, depth), `between ${op.blockId} and ${op.nextBlockId}`);
|
|
2514
4242
|
if (merged.isErr()) return Result.err(merged.error);
|
|
2515
|
-
const joined = {
|
|
2516
|
-
...
|
|
4243
|
+
const joined = withReviewFields({
|
|
4244
|
+
...survivor,
|
|
2517
4245
|
content: merged.value.content
|
|
2518
|
-
};
|
|
2519
|
-
delete joined.
|
|
4246
|
+
}, joinedReview(leading, trailing));
|
|
4247
|
+
delete joined.sectionProperties;
|
|
2520
4248
|
if (trailing.sectionProperties !== void 0) joined.sectionProperties = trailing.sectionProperties;
|
|
2521
|
-
if (trailing.pPrMark !== void 0) joined.pPrMark = trailing.pPrMark;
|
|
2522
4249
|
const length = paragraphLength(leading);
|
|
4250
|
+
const newHalf = survivorSide === SPLIT_HALVES.SECOND ? SPLIT_HALVES.FIRST : SPLIT_HALVES.SECOND;
|
|
4251
|
+
const retiredFields = splitFieldsOf(retired);
|
|
4252
|
+
if (newHalf === SPLIT_HALVES.SECOND) delete retiredFields.propertyChanges;
|
|
2523
4253
|
const split = {
|
|
2524
4254
|
type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
|
|
2525
4255
|
at: {
|
|
2526
4256
|
story: op.story,
|
|
2527
|
-
blockId:
|
|
4257
|
+
blockId: survivor.paraId ?? "",
|
|
2528
4258
|
offset: length,
|
|
2529
4259
|
zeroWidthBefore: zeroWidthLeavesAt(leading.content, length).length
|
|
2530
4260
|
},
|
|
2531
|
-
newBlockId:
|
|
2532
|
-
|
|
4261
|
+
newBlockId: retiredId,
|
|
4262
|
+
newHalf,
|
|
4263
|
+
newParagraph: retiredFields
|
|
2533
4264
|
};
|
|
2534
4265
|
if (leading.pPrMark !== void 0) split.firstMark = leading.pPrMark;
|
|
2535
4266
|
if (namesIds(merged.value.retired)) split.newIds = merged.value.retired;
|
|
4267
|
+
const splitReview = reviewFieldsOf(joined);
|
|
4268
|
+
if (survivorSide === SPLIT_HALVES.FIRST) {
|
|
4269
|
+
delete splitReview.propertyChanges;
|
|
4270
|
+
delete splitReview.pPrMark;
|
|
4271
|
+
if (leading.pPrMark !== void 0) splitReview.pPrMark = leading.pPrMark;
|
|
4272
|
+
}
|
|
2536
4273
|
const committed = commit({
|
|
2537
4274
|
document,
|
|
2538
4275
|
op,
|
|
@@ -2545,7 +4282,7 @@ const joinBlocks = (document, op) => {
|
|
|
2545
4282
|
if (committed.isErr()) return Result.err(committed.error);
|
|
2546
4283
|
return Result.ok({
|
|
2547
4284
|
document: committed.value.document,
|
|
2548
|
-
inverse: [split],
|
|
4285
|
+
inverse: [split, ...reviewSetting(op.story, survivor.paraId ?? "", splitReview, reviewFieldsOf(survivor))],
|
|
2549
4286
|
touched: committed.value.touched
|
|
2550
4287
|
});
|
|
2551
4288
|
};
|
|
@@ -2575,7 +4312,7 @@ const replaceBlocks = (document, op) => {
|
|
|
2575
4312
|
if (!found.every((location, offset) => sameBlockList(location.list, start.list) && location.index === start.index + offset)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, "The replaced paragraphs are not adjacent.");
|
|
2576
4313
|
if (found.some((location, offset) => !equalForStaleness(location.paragraph, op.expected[offset]))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The paragraphs to replace have changed.");
|
|
2577
4314
|
if (op.blocks.some(({ paraId }) => paraId === void 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A replacement paragraph has no id.");
|
|
2578
|
-
if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run or
|
|
4315
|
+
if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run, text node, or revision wrapper.");
|
|
2579
4316
|
const before = found.map(({ paragraph }) => paragraph);
|
|
2580
4317
|
const kept = new Set(before.map(({ paraId }) => idKey(paraId ?? "")));
|
|
2581
4318
|
const placed = new Set(op.blocks.map(({ paraId }) => idKey(paraId ?? "")));
|
|
@@ -2604,8 +4341,72 @@ const replaceBlocks = (document, op) => {
|
|
|
2604
4341
|
touched: touchedBetween(before, op.blocks)
|
|
2605
4342
|
});
|
|
2606
4343
|
};
|
|
4344
|
+
/** Revision and control ids a paragraph's own review fields carry, as slot keys. */
|
|
4345
|
+
const reviewKeysOf = (review) => identityKeysIn({
|
|
4346
|
+
propertyChanges: review.propertyChanges,
|
|
4347
|
+
pPrMark: review.pPrMark
|
|
4348
|
+
});
|
|
4349
|
+
const setParagraphReview = (document, op) => {
|
|
4350
|
+
const located = locate(document, op, op.story, op.blockId);
|
|
4351
|
+
if (located.isErr()) return Result.err(located.error);
|
|
4352
|
+
const { paragraph } = located.value;
|
|
4353
|
+
if (!equalForStaleness(reviewFieldsOf(paragraph), op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other review fields than expected.`);
|
|
4354
|
+
const review = structuredClone(op.review);
|
|
4355
|
+
const next = withReviewFields(paragraph, review);
|
|
4356
|
+
if (structurallyEqual(next, paragraph)) return unchanged(document);
|
|
4357
|
+
if (review.pPrMark !== void 0 && !structurallyEqual(review.pPrMark, paragraph.pPrMark) && endsItsContainer(storyBody(document, op.story), located.value)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK, `${op.blockId} ends its container: there is no next paragraph its mark could join.`);
|
|
4358
|
+
const taken = identitiesOutside(document, [paragraph]);
|
|
4359
|
+
for (const key of identityKeysIn(paragraph.content)) taken.add(key);
|
|
4360
|
+
const incoming = reviewKeysOf(review);
|
|
4361
|
+
if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The review fields carry a revision id already used in the package.");
|
|
4362
|
+
return Result.ok({
|
|
4363
|
+
document: replaceParagraphs({
|
|
4364
|
+
document,
|
|
4365
|
+
story: op.story,
|
|
4366
|
+
at: located.value,
|
|
4367
|
+
count: 1,
|
|
4368
|
+
replacement: [next]
|
|
4369
|
+
}),
|
|
4370
|
+
inverse: [reviewRestoring(op.story, next, paragraph)],
|
|
4371
|
+
touched: touchedBetween([paragraph], [next])
|
|
4372
|
+
});
|
|
4373
|
+
};
|
|
4374
|
+
const replaceInline = (document, op) => {
|
|
4375
|
+
const located = locate(document, op, op.story, op.blockId);
|
|
4376
|
+
if (located.isErr()) return Result.err(located.error);
|
|
4377
|
+
const { paragraph } = located.value;
|
|
4378
|
+
if (!equalForStaleness(paragraph.content, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} holds other content than expected.`);
|
|
4379
|
+
const content = structuredClone(op.content);
|
|
4380
|
+
if (holdsEmptyRecord(content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The content holds an empty run, text node, or revision wrapper.");
|
|
4381
|
+
if (textsIn(content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The content holds text that cannot be written.");
|
|
4382
|
+
if (structurallyEqual(content, paragraph.content)) return unchanged(document);
|
|
4383
|
+
const remaining = countIds(packageParagraphIds(document.package));
|
|
4384
|
+
for (const id of paragraphIdsIn(paragraph.content)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
|
|
4385
|
+
if (collides(remaining, paragraphIdsIn(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content holds a paragraph id the package already uses.");
|
|
4386
|
+
const taken = identitiesOutside(document, [paragraph]);
|
|
4387
|
+
for (const key of reviewKeysOf(reviewFieldsOf(paragraph))) taken.add(key);
|
|
4388
|
+
const incoming = identityKeysIn(content);
|
|
4389
|
+
if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content carries a revision or content-control id already used in the package.");
|
|
4390
|
+
const next = withContent(paragraph, content);
|
|
4391
|
+
return Result.ok({
|
|
4392
|
+
document: replaceParagraphs({
|
|
4393
|
+
document,
|
|
4394
|
+
story: op.story,
|
|
4395
|
+
at: located.value,
|
|
4396
|
+
count: 1,
|
|
4397
|
+
replacement: [next]
|
|
4398
|
+
}),
|
|
4399
|
+
inverse: [contentRestoring(op.story, next, paragraph)],
|
|
4400
|
+
touched: touchedBetween([paragraph], [next])
|
|
4401
|
+
});
|
|
4402
|
+
};
|
|
2607
4403
|
const dispatch = (document, op) => {
|
|
2608
4404
|
switch (op.type) {
|
|
4405
|
+
case DOCUMENT_OP_TYPES.INSERT_BLOCKS: return insertBlocks({
|
|
4406
|
+
document,
|
|
4407
|
+
op,
|
|
4408
|
+
applyOps: applyDocumentOps
|
|
4409
|
+
});
|
|
2609
4410
|
case DOCUMENT_OP_TYPES.INSERT_TEXT: return insertText(document, op);
|
|
2610
4411
|
case DOCUMENT_OP_TYPES.INSERT_CONTENT: return insertContent(document, op);
|
|
2611
4412
|
case DOCUMENT_OP_TYPES.DELETE_RANGE: return deleteRange(document, op);
|
|
@@ -2616,68 +4417,313 @@ const dispatch = (document, op) => {
|
|
|
2616
4417
|
case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return splitBlock(document, op);
|
|
2617
4418
|
case DOCUMENT_OP_TYPES.JOIN_BLOCKS: return joinBlocks(document, op);
|
|
2618
4419
|
case DOCUMENT_OP_TYPES.REPLACE_BLOCKS: return replaceBlocks(document, op);
|
|
4420
|
+
case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW: return setParagraphReview(document, op);
|
|
4421
|
+
case DOCUMENT_OP_TYPES.REPLACE_INLINE: return replaceInline(document, op);
|
|
4422
|
+
case DOCUMENT_OP_TYPES.RESOLVE_REVISION: return resolveRevision(document, op, applyDocumentOps);
|
|
4423
|
+
case DOCUMENT_OP_TYPES.INSERT_ROW:
|
|
4424
|
+
case DOCUMENT_OP_TYPES.DELETE_ROW:
|
|
4425
|
+
case DOCUMENT_OP_TYPES.SET_TABLE_ROWS: return applyRowOp(document, op);
|
|
4426
|
+
default: return op;
|
|
4427
|
+
}
|
|
4428
|
+
};
|
|
4429
|
+
/** The stamp of a tracked operation; `undefined` for a direct one. */
|
|
4430
|
+
const stampOf = (op) => {
|
|
4431
|
+
switch (op.type) {
|
|
4432
|
+
case DOCUMENT_OP_TYPES.INSERT_BLOCKS:
|
|
4433
|
+
case DOCUMENT_OP_TYPES.INSERT_TEXT:
|
|
4434
|
+
case DOCUMENT_OP_TYPES.INSERT_CONTENT:
|
|
4435
|
+
case DOCUMENT_OP_TYPES.DELETE_RANGE:
|
|
4436
|
+
case DOCUMENT_OP_TYPES.SET_RUN_PROPS:
|
|
4437
|
+
case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
|
|
4438
|
+
case DOCUMENT_OP_TYPES.SPLIT_BLOCK:
|
|
4439
|
+
case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
|
|
4440
|
+
case DOCUMENT_OP_TYPES.INSERT_ROW:
|
|
4441
|
+
case DOCUMENT_OP_TYPES.DELETE_ROW: return op.revision;
|
|
4442
|
+
case DOCUMENT_OP_TYPES.SPLIT_INLINE:
|
|
4443
|
+
case DOCUMENT_OP_TYPES.JOIN_INLINE:
|
|
4444
|
+
case DOCUMENT_OP_TYPES.REPLACE_BLOCKS:
|
|
4445
|
+
case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
|
|
4446
|
+
case DOCUMENT_OP_TYPES.REPLACE_INLINE:
|
|
4447
|
+
case DOCUMENT_OP_TYPES.RESOLVE_REVISION:
|
|
4448
|
+
case DOCUMENT_OP_TYPES.SET_TABLE_ROWS: return;
|
|
2619
4449
|
default: return op;
|
|
2620
4450
|
}
|
|
2621
4451
|
};
|
|
4452
|
+
/** The revision ids a tracked operation's records took. */
|
|
4453
|
+
const recordedRevisions = (before, edit, stamp) => {
|
|
4454
|
+
const touched = new Set([...edit.touched.modified, ...edit.touched.inserted].map(idKey));
|
|
4455
|
+
const paragraphs = storyParagraphs(edit.document.package.document).map(({ paragraph }) => paragraph).filter(({ paraId }) => paraId !== void 0 && touched.has(idKey(paraId)));
|
|
4456
|
+
const known = new Set(packageIdentityKeys(before.package));
|
|
4457
|
+
const revisions = stampedRevisionIds(paragraphs, stamp, known);
|
|
4458
|
+
const structuralKey = slotKey({
|
|
4459
|
+
space: IDENTITY_SPACES.REVISION,
|
|
4460
|
+
id: stamp.id
|
|
4461
|
+
});
|
|
4462
|
+
if (!known.has(structuralKey) && packageIdentityKeys(edit.document.package).includes(structuralKey) && !revisions.includes(stamp.id)) revisions.unshift(stamp.id);
|
|
4463
|
+
return revisions;
|
|
4464
|
+
};
|
|
2622
4465
|
/** Apply one operation to a document that meets the seed contract. */
|
|
2623
4466
|
const applyDocumentOp = (document, op) => {
|
|
2624
4467
|
const valid = validateOpsDocument(document);
|
|
2625
|
-
if (valid.isErr()) return
|
|
4468
|
+
if (valid.isErr()) return Result.err(refusal(op, valid.error.reason, valid.error.message));
|
|
4469
|
+
const stamp = stampOf(op);
|
|
4470
|
+
const badStamp = stamp === void 0 ? void 0 : stampRefusal(document, op, stamp);
|
|
4471
|
+
if (badStamp !== void 0) return Result.err(badStamp);
|
|
2626
4472
|
const applied = dispatch(document, op);
|
|
2627
|
-
if (applied.
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
inserted: "modified",
|
|
2634
|
-
removed: "removed"
|
|
2635
|
-
},
|
|
2636
|
-
inserted: {
|
|
2637
|
-
modified: "inserted",
|
|
2638
|
-
inserted: "inserted",
|
|
2639
|
-
removed: void 0
|
|
2640
|
-
},
|
|
2641
|
-
removed: {
|
|
2642
|
-
modified: "modified",
|
|
2643
|
-
inserted: "modified",
|
|
2644
|
-
removed: "removed"
|
|
2645
|
-
}
|
|
4473
|
+
if (applied.isErr()) return Result.err(applied.error);
|
|
4474
|
+
meetsContract(applied.value.document);
|
|
4475
|
+
return Result.ok({
|
|
4476
|
+
...applied.value,
|
|
4477
|
+
revisions: stamp === void 0 ? [] : recordedRevisions(document, applied.value, stamp)
|
|
4478
|
+
});
|
|
2646
4479
|
};
|
|
2647
4480
|
/**
|
|
2648
4481
|
* Apply operations in order, atomically: the first refusal is returned and
|
|
2649
|
-
* the document is unchanged. The inverse undoes the whole list
|
|
4482
|
+
* the document is unchanged. The inverse undoes the whole list, and
|
|
4483
|
+
* `revisions` lists each operation's in turn.
|
|
2650
4484
|
*/
|
|
2651
4485
|
const applyDocumentOps = (document, ops) => {
|
|
2652
4486
|
let current = document;
|
|
2653
|
-
const
|
|
2654
|
-
const
|
|
4487
|
+
const edits = [];
|
|
4488
|
+
const revisions = [];
|
|
2655
4489
|
for (const op of ops) {
|
|
2656
4490
|
const applied = applyDocumentOp(current, op);
|
|
2657
4491
|
if (applied.isErr()) return applied;
|
|
2658
4492
|
current = applied.value.document;
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
"modified",
|
|
2662
|
-
"inserted",
|
|
2663
|
-
"removed"
|
|
2664
|
-
]) for (const id of applied.value.touched[state]) {
|
|
2665
|
-
const previous = touched.get(id);
|
|
2666
|
-
const nextState = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
|
|
2667
|
-
if (nextState === void 0) touched.delete(id);
|
|
2668
|
-
else touched.set(id, nextState);
|
|
2669
|
-
}
|
|
4493
|
+
edits.push(applied.value);
|
|
4494
|
+
revisions.push(...applied.value.revisions);
|
|
2670
4495
|
}
|
|
2671
|
-
const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
|
|
2672
4496
|
return Result.ok({
|
|
2673
|
-
document
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
4497
|
+
...combineEdits(document, edits),
|
|
4498
|
+
revisions
|
|
4499
|
+
});
|
|
4500
|
+
};
|
|
4501
|
+
//#endregion
|
|
4502
|
+
//#region src/ops/plan.ts
|
|
4503
|
+
/**
|
|
4504
|
+
* Pure planning around tracked operations: how many new revision ids an
|
|
4505
|
+
* operation takes, and the operations a tracked deletion of a range is made
|
|
4506
|
+
* of once the author's own insertions and comment anchors are accounted for.
|
|
4507
|
+
*/
|
|
4508
|
+
/** The ids of one space among slot keys. */
|
|
4509
|
+
const idsIn = (keys, space) => {
|
|
4510
|
+
const prefix = `${space}:`;
|
|
4511
|
+
return keys.flatMap((key) => key.startsWith(prefix) ? [Number(key.slice(prefix.length))] : []);
|
|
4512
|
+
};
|
|
4513
|
+
/** The ids a package uses in one space. */
|
|
4514
|
+
const usedIds = (document, space) => new Set(idsIn(packageIdentityKeys(document.package), space));
|
|
4515
|
+
/** The same operation with other new ids; one that takes none is returned as it is. */
|
|
4516
|
+
const withNewIds = (op, newIds) => {
|
|
4517
|
+
switch (op.type) {
|
|
4518
|
+
case DOCUMENT_OP_TYPES.INSERT_BLOCKS:
|
|
4519
|
+
case DOCUMENT_OP_TYPES.INSERT_TEXT:
|
|
4520
|
+
case DOCUMENT_OP_TYPES.INSERT_CONTENT:
|
|
4521
|
+
case DOCUMENT_OP_TYPES.DELETE_RANGE:
|
|
4522
|
+
case DOCUMENT_OP_TYPES.SPLIT_INLINE:
|
|
4523
|
+
case DOCUMENT_OP_TYPES.SET_RUN_PROPS:
|
|
4524
|
+
case DOCUMENT_OP_TYPES.SPLIT_BLOCK:
|
|
4525
|
+
case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
|
|
4526
|
+
case DOCUMENT_OP_TYPES.INSERT_ROW:
|
|
4527
|
+
case DOCUMENT_OP_TYPES.DELETE_ROW: return {
|
|
4528
|
+
...op,
|
|
4529
|
+
newIds
|
|
4530
|
+
};
|
|
4531
|
+
case DOCUMENT_OP_TYPES.JOIN_INLINE:
|
|
4532
|
+
case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
|
|
4533
|
+
case DOCUMENT_OP_TYPES.REPLACE_BLOCKS:
|
|
4534
|
+
case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
|
|
4535
|
+
case DOCUMENT_OP_TYPES.REPLACE_INLINE:
|
|
4536
|
+
case DOCUMENT_OP_TYPES.RESOLVE_REVISION:
|
|
4537
|
+
case DOCUMENT_OP_TYPES.SET_TABLE_ROWS: return op;
|
|
4538
|
+
default: return op;
|
|
4539
|
+
}
|
|
4540
|
+
};
|
|
4541
|
+
/** The largest id count {@link revisionIdDemand} searches before giving up. */
|
|
4542
|
+
const MAX_DEMAND = 65536;
|
|
4543
|
+
/**
|
|
4544
|
+
* How many `newIds.revision` entries an operation takes on a document,
|
|
4545
|
+
* besides its stamp's id: the length of the shortest list of unused ids it
|
|
4546
|
+
* applies with. Content-control ids are supplied freely while counting. The
|
|
4547
|
+
* refusal is the one the operation meets whatever ids it is given.
|
|
4548
|
+
*/
|
|
4549
|
+
const revisionIdDemand = (document, op) => {
|
|
4550
|
+
const largest = (ids, floor) => {
|
|
4551
|
+
let out = floor;
|
|
4552
|
+
for (const id of ids) out = Math.max(out, id);
|
|
4553
|
+
return out;
|
|
4554
|
+
};
|
|
4555
|
+
const carried = identityKeysIn(op);
|
|
4556
|
+
const first = largest(/* @__PURE__ */ new Set([...usedIds(document, IDENTITY_SPACES.REVISION), ...idsIn(carried, IDENTITY_SPACES.REVISION)]), stampOf(op)?.id ?? 0) + 1;
|
|
4557
|
+
const pool = (count) => Array.from({ length: count }, (_, index) => first + index);
|
|
4558
|
+
const firstControl = largest(/* @__PURE__ */ new Set([...usedIds(document, IDENTITY_SPACES.CONTROL), ...idsIn(carried, IDENTITY_SPACES.CONTROL)]), 0) + 1;
|
|
4559
|
+
const control = Array.from({ length: 64 }, (_, index) => firstControl + index);
|
|
4560
|
+
const attempt = (count) => applyDocumentOp(document, withNewIds(op, {
|
|
4561
|
+
revision: pool(count),
|
|
4562
|
+
control
|
|
4563
|
+
}));
|
|
4564
|
+
const needsMore = (count) => {
|
|
4565
|
+
const applied = attempt(count);
|
|
4566
|
+
if (applied.isOk()) return false;
|
|
4567
|
+
return applied.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS ? true : applied.error;
|
|
4568
|
+
};
|
|
4569
|
+
const none = needsMore(0);
|
|
4570
|
+
if (none !== true) return none === false ? Result.ok(0) : Result.err(none);
|
|
4571
|
+
let low = 0;
|
|
4572
|
+
let high = 1;
|
|
4573
|
+
for (;;) {
|
|
4574
|
+
const outcome = needsMore(high);
|
|
4575
|
+
if (outcome === false) break;
|
|
4576
|
+
if (outcome !== true) return Result.err(outcome);
|
|
4577
|
+
if (high >= MAX_DEMAND || first + high > 2147483647) return Result.err(new DocumentOpRefusal({
|
|
4578
|
+
message: "The operation takes more new ids than a package can hold.",
|
|
4579
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
|
|
4580
|
+
opType: op.type
|
|
4581
|
+
}));
|
|
4582
|
+
low = high;
|
|
4583
|
+
high *= 2;
|
|
4584
|
+
}
|
|
4585
|
+
while (high - low > 1) {
|
|
4586
|
+
const middle = Math.floor((low + high) / 2);
|
|
4587
|
+
if (needsMore(middle) === false) high = middle;
|
|
4588
|
+
else low = middle;
|
|
4589
|
+
}
|
|
4590
|
+
return Result.ok(high);
|
|
4591
|
+
};
|
|
4592
|
+
const COMMENT_ANCHORS = /* @__PURE__ */ new Set([
|
|
4593
|
+
"commentRangeStart",
|
|
4594
|
+
"commentRangeEnd",
|
|
4595
|
+
"commentReference"
|
|
4596
|
+
]);
|
|
4597
|
+
const leafPlan = ({ node, ancestors }, author) => {
|
|
4598
|
+
if (ancestors.some(isRemovedRevisionNode)) return "untouched";
|
|
4599
|
+
if (COMMENT_ANCHORS.has(node.type)) return "anchor";
|
|
4600
|
+
return ancestors.some((ancestor) => ancestor.type === "insertion" && isTrackedWrapper(ancestor) && ancestor.info.author === author) ? "direct" : "tracked";
|
|
4601
|
+
};
|
|
4602
|
+
const laterGap = (left, right) => compareGaps(left, right) >= 0 ? left : right;
|
|
4603
|
+
const earlierGap = (left, right) => compareGaps(left, right) <= 0 ? left : right;
|
|
4604
|
+
/**
|
|
4605
|
+
* The stretches of a range to delete directly and with tracking, in document
|
|
4606
|
+
* order. A comment anchor ends a stretch; a tracked stretch runs across
|
|
4607
|
+
* deleted content, which it leaves alone, and one holding nothing else is
|
|
4608
|
+
* dropped.
|
|
4609
|
+
*/
|
|
4610
|
+
const segmentsOf = (spans, from, to, author) => {
|
|
4611
|
+
const out = [];
|
|
4612
|
+
let open;
|
|
4613
|
+
for (const span of spans) {
|
|
4614
|
+
const start = laterGap(span.before, from);
|
|
4615
|
+
const end = earlierGap(span.after, to);
|
|
4616
|
+
if (compareGaps(start, end) >= 0) continue;
|
|
4617
|
+
const plan = leafPlan(span, author);
|
|
4618
|
+
if (plan === "anchor") {
|
|
4619
|
+
open = void 0;
|
|
4620
|
+
continue;
|
|
2679
4621
|
}
|
|
4622
|
+
const segmentPlan = plan === "untouched" ? "tracked" : plan;
|
|
4623
|
+
const records = plan !== "untouched";
|
|
4624
|
+
if (open !== void 0 && open.plan === segmentPlan && compareGaps(open.to, start) === 0) {
|
|
4625
|
+
open.to = end;
|
|
4626
|
+
open.records ||= records;
|
|
4627
|
+
continue;
|
|
4628
|
+
}
|
|
4629
|
+
open = {
|
|
4630
|
+
plan: segmentPlan,
|
|
4631
|
+
from: start,
|
|
4632
|
+
to: end,
|
|
4633
|
+
records
|
|
4634
|
+
};
|
|
4635
|
+
out.push(open);
|
|
4636
|
+
}
|
|
4637
|
+
return out.filter(({ records }) => records);
|
|
4638
|
+
};
|
|
4639
|
+
const positionOf = (at, gap) => ({
|
|
4640
|
+
story: at.story,
|
|
4641
|
+
blockId: at.blockId,
|
|
4642
|
+
offset: gap.offset,
|
|
4643
|
+
zeroWidthBefore: gap.zeroWidthBefore
|
|
4644
|
+
});
|
|
4645
|
+
const outOfIds = () => Result.err(new DocumentOpRefusal({
|
|
4646
|
+
message: "The planned deletions need more new revision ids.",
|
|
4647
|
+
reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
|
|
4648
|
+
opType: DOCUMENT_OP_TYPES.DELETE_RANGE
|
|
4649
|
+
}));
|
|
4650
|
+
/**
|
|
4651
|
+
* The operations a tracked deletion of a range is made of, to apply in
|
|
4652
|
+
* order as one batch: a direct `deleteRange` for each stretch of the author's
|
|
4653
|
+
* own insertions (retracting a suggestion removes it), and a tracked one for
|
|
4654
|
+
* each other stretch, split around comment boundaries and references, which
|
|
4655
|
+
* no tracked change can hold and which therefore stay. Stretches go from the
|
|
4656
|
+
* last to the first, so each position still names what it named in the
|
|
4657
|
+
* input. The positions default their `zeroWidthBefore` as `deleteRange` does.
|
|
4658
|
+
*
|
|
4659
|
+
* The first tracked deletion carries the stamp's id. Each later one takes the
|
|
4660
|
+
* next id of `newIds.revision` the package does not use for its stamp, then
|
|
4661
|
+
* the ones it needs for the records it cuts.
|
|
4662
|
+
*/
|
|
4663
|
+
const planTrackedDeletion = (document, options) => {
|
|
4664
|
+
const { from, to, revision, newIds } = options;
|
|
4665
|
+
const check = applyDocumentOp(document, {
|
|
4666
|
+
type: DOCUMENT_OP_TYPES.DELETE_RANGE,
|
|
4667
|
+
from,
|
|
4668
|
+
to
|
|
2680
4669
|
});
|
|
4670
|
+
if (check.isErr()) return Result.err(check.error);
|
|
4671
|
+
const location = storyParagraphs(storyBody(document, from.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(from.blockId));
|
|
4672
|
+
if (location === void 0) return Result.ok([]);
|
|
4673
|
+
const { content } = location.paragraph;
|
|
4674
|
+
const start = {
|
|
4675
|
+
offset: from.offset,
|
|
4676
|
+
zeroWidthBefore: from.zeroWidthBefore ?? zeroWidthLeavesAt(content, from.offset).length
|
|
4677
|
+
};
|
|
4678
|
+
const end = {
|
|
4679
|
+
offset: to.offset,
|
|
4680
|
+
zeroWidthBefore: to.zeroWidthBefore ?? 0
|
|
4681
|
+
};
|
|
4682
|
+
const segments = segmentsOf(leafSpans(content), start, end, revision.author);
|
|
4683
|
+
const used = usedIds(document, IDENTITY_SPACES.REVISION);
|
|
4684
|
+
const pool = (newIds?.revision ?? []).filter((id) => !used.has(id) && id !== revision.id);
|
|
4685
|
+
let taken = 0;
|
|
4686
|
+
const take = (count) => {
|
|
4687
|
+
if (taken + count > pool.length) return void 0;
|
|
4688
|
+
const ids = pool.slice(taken, taken + count);
|
|
4689
|
+
taken += count;
|
|
4690
|
+
return ids;
|
|
4691
|
+
};
|
|
4692
|
+
const ops = [];
|
|
4693
|
+
let current = document;
|
|
4694
|
+
let stampUsed = false;
|
|
4695
|
+
for (const segment of segments.toReversed()) {
|
|
4696
|
+
let op = {
|
|
4697
|
+
type: DOCUMENT_OP_TYPES.DELETE_RANGE,
|
|
4698
|
+
from: positionOf(from, segment.from),
|
|
4699
|
+
to: positionOf(from, segment.to)
|
|
4700
|
+
};
|
|
4701
|
+
if (segment.plan === "tracked") {
|
|
4702
|
+
const stampId = stampUsed ? take(1)?.[0] : revision.id;
|
|
4703
|
+
if (stampId === void 0) return outOfIds();
|
|
4704
|
+
stampUsed = true;
|
|
4705
|
+
op = {
|
|
4706
|
+
...op,
|
|
4707
|
+
revision: {
|
|
4708
|
+
...revision,
|
|
4709
|
+
id: stampId
|
|
4710
|
+
}
|
|
4711
|
+
};
|
|
4712
|
+
const demand = revisionIdDemand(current, op);
|
|
4713
|
+
if (demand.isErr()) return Result.err(demand.error);
|
|
4714
|
+
const ids = take(demand.value);
|
|
4715
|
+
if (ids === void 0) return outOfIds();
|
|
4716
|
+
if (ids.length > 0) op = {
|
|
4717
|
+
...op,
|
|
4718
|
+
newIds: { revision: ids }
|
|
4719
|
+
};
|
|
4720
|
+
}
|
|
4721
|
+
const applied = applyDocumentOp(current, op);
|
|
4722
|
+
if (applied.isErr()) return Result.err(applied.error);
|
|
4723
|
+
current = applied.value.document;
|
|
4724
|
+
ops.push(op);
|
|
4725
|
+
}
|
|
4726
|
+
return Result.ok(ops);
|
|
2681
4727
|
};
|
|
2682
4728
|
//#endregion
|
|
2683
|
-
export { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, toOpEnvelope, validateOpsDocument };
|
|
4729
|
+
export { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, REVISION_DECISIONS, SPLIT_HALVES, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, planTrackedDeletion, revisionIdDemand, toOpEnvelope, validateOpsDocument };
|