@folijs/agent 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,496 @@
1
+ import {
2
+ addComment,
3
+ controlIsReadOnly,
4
+ controlProperties,
5
+ controlsIn,
6
+ deleteTable,
7
+ type Editor,
8
+ findAll,
9
+ type Node,
10
+ paragraphStyles,
11
+ type ReplaceRefusal,
12
+ replace,
13
+ setParagraphStyle,
14
+ untracked,
15
+ } from "@folijs/core";
16
+ import { wordContext } from "@folijs/core/internal";
17
+ import type { Handles } from "./handles.js";
18
+ import { type Block, formatBlocks, oneLine, readBlocks } from "./read.js";
19
+ import { type Refusal, type Result, refuse } from "./result.js";
20
+
21
+ /** A paragraph to insert: its text ("\n" or ↵ a line break, a tab a tab), in `style` if given. */
22
+ export type NewParagraph = string | { text: string; style?: string };
23
+
24
+ /** What an operation changed: the blocks as they are now, and as `read` would show them. */
25
+ export interface Changed {
26
+ blocks: Block[];
27
+ text: string;
28
+ }
29
+
30
+ export interface ReplaceOptions {
31
+ /** Replace every place `find` is in the block. Default: refuse when there are several. */
32
+ all?: boolean;
33
+ }
34
+
35
+ /** @internal What the operations work on. */
36
+ export interface Context {
37
+ editor: Editor;
38
+ handles: Handles;
39
+ author: string;
40
+ }
41
+
42
+ type Attrs = Record<string, unknown>;
43
+
44
+ /** A paragraph's attributes that are its mark's own: a new paragraph does not take them. */
45
+ const MARK_ONLY = { section: null, revision: null, formatChange: null, attributes: null };
46
+
47
+ const WHY: Record<ReplaceRefusal, string> = {
48
+ locked: "it is in a locked content control",
49
+ control: "the content control there does not take it",
50
+ field: "it runs over the edge of a field's result",
51
+ "field-code": "it is in a field's code",
52
+ deleted: "it is in text already deleted",
53
+ stale: "the text is no longer there",
54
+ refused: "the change could not be recorded as a tracked change",
55
+ };
56
+
57
+ /** Text as a model writes it, as the document takes it: ↵ is a line break, no control characters. */
58
+ const typed = (text: string) =>
59
+ text
60
+ .replace(/\r\n?/g, "\n")
61
+ .replaceAll("↵", "\n")
62
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what goes
63
+ .replace(/[\u0000-\u0008\u000B-\u001F]/g, "");
64
+
65
+ const quote = (text: string, most = 80) =>
66
+ JSON.stringify(text.length > most ? `${text.slice(0, most - 3)}…` : text);
67
+
68
+ /** @internal Why `handle` names no block now, or the block. */
69
+ export function resolve(context: Context, handle: string): Refusal | { pos: number; node: Node } {
70
+ if (typeof handle !== "string")
71
+ return refuse("invalid", "A block is named by its handle, a string as read gives it: b7.");
72
+ const found = context.handles.resolve(handle);
73
+ if (found) {
74
+ if (readBlocks(context.editor.state, context.handles).some((b) => b.handle === handle))
75
+ return found;
76
+ return refuse("gone", `Block ${handle} was deleted as a tracked change: it is not read.`);
77
+ }
78
+ return context.handles.issued(handle)
79
+ ? refuse(
80
+ "gone",
81
+ `Block ${handle} is no longer in the document. Read again for the blocks there are.`,
82
+ )
83
+ : refuse("unknown-handle", `There is no block ${handle}. Handles come from read: [b1], [b2]…`);
84
+ }
85
+
86
+ /** @internal The blocks with these handles as they read now, in document order. */
87
+ export function changed(context: Context, handles: readonly string[]): Changed {
88
+ const wanted = new Set(handles);
89
+ const blocks = readBlocks(context.editor.state, context.handles).filter((b) =>
90
+ wanted.has(b.handle),
91
+ );
92
+ return { blocks, text: formatBlocks(blocks) };
93
+ }
94
+
95
+ /** @internal The id of the paragraph style a model named (by its name or id), or the refusal. */
96
+ export function styleId(context: Context, name: string): string | Refusal {
97
+ // By the names a read shows them under: on one line.
98
+ const styles = paragraphStyles(context.editor.state).map((s) => ({
99
+ id: s.id,
100
+ name: oneLine(s.name),
101
+ }));
102
+ if (typeof name !== "string") return refuse("invalid", "A style is named by its name, a string.");
103
+ const wanted = oneLine(name).trim().toLowerCase();
104
+ const style =
105
+ styles.find((s) => s.name.toLowerCase() === wanted) ??
106
+ styles.find((s) => s.id.toLowerCase() === wanted);
107
+ if (style) return style.id;
108
+ return refuse(
109
+ "unknown-style",
110
+ `There is no paragraph style ${quote(name)}. The styles are: ${styles.map((s) => s.name).join(", ")}.`,
111
+ );
112
+ }
113
+
114
+ /** The content controls `node` at `pos` is in or holds that may not be edited, by name. */
115
+ function lockedControls(context: Context, pos: number, node: Node): string[] {
116
+ const { state } = context.editor;
117
+ const ids = new Set<string>((node.attrs.controls as string[] | null) ?? []);
118
+ const end = pos + node.nodeSize;
119
+ for (const range of controlsIn(state.doc))
120
+ if (range.from < end && pos < range.to) ids.add(range.id);
121
+ const names: string[] = [];
122
+ for (const id of ids) {
123
+ const control = controlProperties(state, id);
124
+ if (control && controlIsReadOnly(control)) names.push(control.alias ?? control.tag ?? id);
125
+ }
126
+ return names;
127
+ }
128
+
129
+ /** @internal */
130
+ export function replaceText(
131
+ context: Context,
132
+ handle: string,
133
+ find: string,
134
+ replacement: string,
135
+ options: ReplaceOptions = {},
136
+ ): Result<Changed & { replaced: number; refused: number }> {
137
+ const { editor } = context;
138
+ const target = resolve(context, handle);
139
+ if ("ok" in target) return target;
140
+ if (target.node.type.name !== "paragraph")
141
+ return refuse(
142
+ "not-a-paragraph",
143
+ `Block ${handle} is not a paragraph: text is replaced in paragraphs (a table's are its cells' blocks).`,
144
+ );
145
+ if (typeof find !== "string" || typeof replacement !== "string")
146
+ return refuse("invalid", 'find and replacement must be strings (replacement "" deletes).');
147
+ const query = typed(find);
148
+ const text = typed(replacement);
149
+ if (!query) return refuse("invalid", "find must be the text to replace, as read shows it.");
150
+ const from = target.pos;
151
+ const to = target.pos + target.node.nodeSize;
152
+ const matches = findAll(editor, query, { matchCase: true }).filter(
153
+ (m) => m.story === null && m.from >= from && m.to <= to,
154
+ );
155
+ if (!matches.length) {
156
+ const now = changed(context, [handle]).blocks[0]?.text ?? "";
157
+ const brackets = /\[[^\]]+\]/.test(query)
158
+ ? " What read shows in brackets ([picture], [empty: …]) is not text: leave it out of find."
159
+ : "";
160
+ return refuse(
161
+ "no-match",
162
+ `${quote(query)} is not in block ${handle}. Capitals and spaces count.${brackets} Its text is: ${quote(now, 2000)}`,
163
+ );
164
+ }
165
+ if (matches.length > 1 && !options?.all)
166
+ return refuse(
167
+ "several-matches",
168
+ `${quote(query)} is in block ${handle} ${matches.length} times. Give a longer find that is there once, or all: true to replace every one.`,
169
+ );
170
+ // Nothing to record: the text is what it would become.
171
+ if (query === text) return { ok: true, replaced: 0, refused: 0, ...changed(context, [handle]) };
172
+ let replaced = 0;
173
+ let refused = 0;
174
+ let why: ReplaceRefusal | undefined;
175
+ // Last first: a replacement moves what comes after it.
176
+ for (const match of matches.reverse()) {
177
+ const report = replace(editor, match, text, { matchCase: true });
178
+ replaced += report.replaced;
179
+ refused += report.refused.length;
180
+ why ??= report.refused[0]?.reason;
181
+ }
182
+ const reason = why ? WHY[why] : "the document refused the change";
183
+ if (!replaced)
184
+ return refuse(
185
+ why === "locked" || why === "control" ? "read-only" : "refused",
186
+ `${quote(query)} in block ${handle} was not replaced: ${reason}.`,
187
+ );
188
+ const result = changed(context, [handle]);
189
+ if (refused) result.text += `\n${refused} of ${matches.length} not replaced: ${reason}.`;
190
+ return { ok: true, replaced, refused, ...result };
191
+ }
192
+
193
+ /** A new paragraph's content: its text, line breaks and tabs. */
194
+ function inline(editor: Editor, text: string): Node[] {
195
+ const { schema } = editor.state;
196
+ const nodes: Node[] = [];
197
+ for (const part of typed(text).split(/(\n|\t)/)) {
198
+ if (part === "\n") nodes.push(schema.node("hardBreak"));
199
+ else if (part === "\t") nodes.push(schema.node("tab"));
200
+ else if (part) nodes.push(schema.text(part));
201
+ }
202
+ return nodes;
203
+ }
204
+
205
+ /**
206
+ * The attributes of a paragraph put next to `node`, as Enter gives in Word (core's
207
+ * `splitAttrs`): the paragraph's own properties and controls, without its mark's own. After a
208
+ * paragraph whose style names another as the next (a heading: Normal), that style, without the
209
+ * direct formatting.
210
+ */
211
+ function attrsLike(context: Context, node: Node, side: "before" | "after"): Attrs | null {
212
+ if (node.type.name !== "paragraph") return null;
213
+ const attrs = node.attrs as Attrs;
214
+ if (side === "after") {
215
+ const styles = wordContext(context.editor.state)?.envelope.styles ?? [];
216
+ const paragraph = styles.filter((s) => s.type === "paragraph");
217
+ const id =
218
+ (attrs.style as string | null) ?? paragraph.filter((s) => s.isDefault).at(-1)?.id ?? null;
219
+ const next = paragraph.find((s) => s.id === id)?.next;
220
+ // One the document does not have as a paragraph style is no next style: Word stays in this one.
221
+ if (next !== undefined && next !== id && paragraph.some((s) => s.id === next))
222
+ return { controls: attrs.controls ?? null, style: next };
223
+ }
224
+ return { ...attrs, ...MARK_ONLY };
225
+ }
226
+
227
+ /** @internal Inserts paragraphs before or after the block `handle`. */
228
+ export function insert(
229
+ context: Context,
230
+ handle: string,
231
+ paragraphs: NewParagraph | readonly NewParagraph[],
232
+ side: "before" | "after",
233
+ ): Result<Changed> {
234
+ const { editor, handles } = context;
235
+ const target = resolve(context, handle);
236
+ if ("ok" in target) return target;
237
+ // One paragraph given bare is one paragraph.
238
+ const list: readonly unknown[] = Array.isArray(paragraphs) ? paragraphs : [paragraphs];
239
+ if (!list.length) return refuse("invalid", "Give at least one paragraph to insert.");
240
+ const like = attrsLike(context, target.node, side);
241
+ // A new paragraph next to one in a control is in that control: not when it is locked.
242
+ for (const id of (like?.controls as string[] | null | undefined) ?? []) {
243
+ const control = controlProperties(editor.state, id);
244
+ if (control && controlIsReadOnly(control))
245
+ return refuse(
246
+ "read-only",
247
+ `Block ${handle} is in the locked content control ${quote(control.alias ?? control.tag ?? id)}: nothing is inserted there.`,
248
+ );
249
+ }
250
+ const known = new Set(wordContext(editor.state)?.envelope.styles.map((s) => s.id));
251
+ const { schema } = editor.state;
252
+ const nodes: Node[] = [];
253
+ /** Styles Word has built in that the document has not yet: put on once the paragraph is there. */
254
+ const later: { index: number; id: string }[] = [];
255
+ for (const [index, paragraph] of list.entries()) {
256
+ const given = typeof paragraph === "string" ? { text: paragraph } : paragraph;
257
+ const { text, style } = (given ?? {}) as { text?: unknown; style?: unknown };
258
+ if (typeof text !== "string")
259
+ return refuse(
260
+ "invalid",
261
+ 'A paragraph to insert is its text, or { "text": …, "style": … } with the text a string.',
262
+ );
263
+ let attrs = like;
264
+ if (style !== undefined) {
265
+ const id = styleId(context, style as string);
266
+ if (typeof id !== "string") return id;
267
+ // In a style of its own: none of the neighbour's numbering or indents.
268
+ attrs = { controls: like?.controls ?? null, ...(known.has(id) ? { style: id } : {}) };
269
+ if (!known.has(id)) later.push({ index, id });
270
+ }
271
+ nodes.push(schema.node("paragraph", attrs, inline(editor, text)));
272
+ }
273
+ const at = side === "after" ? target.pos + target.node.nodeSize : target.pos;
274
+ const before = editor.state.doc;
275
+ editor.dispatch(editor.state.tr.insert(at, nodes));
276
+ if (editor.state.doc === before)
277
+ return refuse("refused", `Nothing could be inserted ${side} block ${handle}.`);
278
+ const made: string[] = [];
279
+ let pos = at;
280
+ for (const [index] of nodes.entries()) {
281
+ const style = later.find((l) => l.index === index);
282
+ if (style) {
283
+ // shortcut: a second change and undo step; only for a built-in style the document lacks.
284
+ editor.select(pos + 1);
285
+ editor.run(setParagraphStyle(style.id));
286
+ }
287
+ const node = editor.state.doc.nodeAt(pos);
288
+ if (!node) break;
289
+ made.push(handles.at(pos, node));
290
+ pos += node.nodeSize;
291
+ }
292
+ return { ok: true, ...changed(context, made) };
293
+ }
294
+
295
+ /** Why a paragraph must stay where it is, or null when it may go whole. */
296
+ function mustStay(node: Node, previous: Node | null, next: Node | null): string | null {
297
+ if (node.attrs.section) return "it ends a section, and its section break stays with it";
298
+ if (!next) return "a paragraph must end the document, and a table's cell";
299
+ if (next.type.name !== "paragraph")
300
+ return previous?.type.name === "table" && next.type.name === "table"
301
+ ? "a paragraph must stand between two tables"
302
+ : "the block after it is not a paragraph it can join";
303
+ return null;
304
+ }
305
+
306
+ /** Whether a paragraph has anything left to delete: content not deleted already. */
307
+ /** Whether all of the paragraph's content is `author`'s own tracked insertion. */
308
+ function ownText(node: Node, author: string): boolean {
309
+ let own = true;
310
+ node.forEach((child) => {
311
+ own &&= child.marks.some((m) => m.type.name === "insertion" && m.attrs.author === author);
312
+ });
313
+ return own;
314
+ }
315
+
316
+ const hasContent = (node: Node) => {
317
+ let live = false;
318
+ node.forEach((child) => {
319
+ live ||= !child.marks.some((m) => m.type.name === "deletion");
320
+ });
321
+ return live;
322
+ };
323
+
324
+ /** @internal */
325
+ export function deleteBlock(context: Context, handle: string): Result<{ text: string }> {
326
+ const { editor, author } = context;
327
+ const target = resolve(context, handle);
328
+ if ("ok" in target) return target;
329
+ const { node, pos } = target;
330
+ const name = node.type.name;
331
+ if (name !== "table" && name !== "paragraph")
332
+ return refuse(
333
+ "read-only",
334
+ `Block ${handle} is content Foli does not edit: it cannot be deleted.`,
335
+ );
336
+ const locked = lockedControls(context, pos, node);
337
+ if (locked.length)
338
+ return refuse(
339
+ "read-only",
340
+ `Block ${handle} is in or holds the locked content control ${quote(locked[0] as string)}: it cannot be deleted.`,
341
+ );
342
+ const before = editor.state.doc;
343
+ if (name === "table") {
344
+ // The caret in a paragraph of the table's own first cell (a cell ends with one), not in a
345
+ // table nested there: `deleteTable` takes the innermost table around the caret.
346
+ const cell = node.child(0).child(0);
347
+ const last = cell.child(cell.childCount - 1);
348
+ editor.select(pos + 2 + cell.content.size - last.nodeSize + 2);
349
+ editor.run(deleteTable);
350
+ if (editor.state.doc === before || changed(context, [handle]).blocks.length)
351
+ return refuse("refused", `Table ${handle} was not deleted: the document refused the change.`);
352
+ return { ok: true, text: `Deleted table ${handle} with its cells.` };
353
+ }
354
+ // Word's rules: a cell and the body end with a paragraph, two tables never touch, and a
355
+ // paragraph mark that cannot join a paragraph after it stays when its deletion is accepted.
356
+ // Where the paragraph must stay, only its content goes.
357
+ const $pos = editor.state.doc.resolve(pos);
358
+ const index = $pos.index();
359
+ const parent = $pos.parent;
360
+ const next = index + 1 < parent.childCount ? parent.child(index + 1) : null;
361
+ const previous = index > 0 ? parent.child(index - 1) : null;
362
+ const stays = mustStay(node, previous, next);
363
+ const own = (node.attrs.revision as { insertion?: { author?: string } } | null)?.insertion;
364
+ if (
365
+ stays &&
366
+ !node.attrs.section &&
367
+ own?.author === author &&
368
+ ownText(node, author) &&
369
+ previous?.type.name === "paragraph"
370
+ ) {
371
+ // The session's own paragraph, never accepted: it goes for real, as its text would.
372
+ editor.dispatch(editor.state.tr.delete(pos, pos + node.nodeSize).setMeta(untracked, true));
373
+ if (editor.state.doc !== before) return { ok: true, text: `Deleted block ${handle}.` };
374
+ }
375
+ if (stays && !hasContent(node))
376
+ return refuse(
377
+ "refused",
378
+ `Block ${handle} was not deleted: it is already empty, and it stays because ${stays}.`,
379
+ );
380
+ const tr = editor.state.tr;
381
+ editor.dispatch(
382
+ stays ? tr.delete(pos + 1, pos + node.nodeSize - 1) : tr.delete(pos, pos + node.nodeSize),
383
+ );
384
+ if (editor.state.doc === before)
385
+ return refuse("refused", `Block ${handle} was not deleted: the document refused the change.`);
386
+ const left = changed(context, [handle]);
387
+ if (left.blocks.length)
388
+ return {
389
+ ok: true,
390
+ text: `Block ${handle} was emptied but stays: ${stays ?? "its paragraph mark could not be deleted"}.\n${left.text}`,
391
+ };
392
+ return { ok: true, text: `Deleted block ${handle}.` };
393
+ }
394
+
395
+ /** @internal The paragraph `handle` names, or why an operation on a paragraph cannot go on. */
396
+ function paragraphAt(
397
+ context: Context,
398
+ handle: string,
399
+ what: string,
400
+ ): Refusal | { pos: number; node: Node } {
401
+ const target = resolve(context, handle);
402
+ if ("ok" in target || target.node.type.name === "paragraph") return target;
403
+ return refuse(
404
+ "not-a-paragraph",
405
+ `Block ${handle} is not a paragraph: ${what} (a table's are its cells' blocks).`,
406
+ );
407
+ }
408
+
409
+ /** @internal The paragraph styles there are to name, as `read` names them. */
410
+ export function styles(context: Context): string[] {
411
+ return paragraphStyles(context.editor.state).map((style) => oneLine(style.name));
412
+ }
413
+
414
+ /** @internal */
415
+ export function setStyle(context: Context, handle: string, style: string): Result<Changed> {
416
+ const { editor } = context;
417
+ const target = paragraphAt(context, handle, "a style is set on paragraphs");
418
+ if ("ok" in target) return target;
419
+ const id = styleId(context, style);
420
+ if (typeof id !== "string") return id;
421
+ const resolver = wordContext(editor.state)?.resolver;
422
+ const now = resolver?.paragraph(target.node.attrs as Record<string, unknown>).paragraph.style;
423
+ if (now !== id) {
424
+ const before = editor.state.doc;
425
+ editor.select(target.pos + 1);
426
+ editor.run(setParagraphStyle(id));
427
+ // The command says yes before the document's rules have their say (a locked control).
428
+ if (editor.state.doc === before) {
429
+ const locked = lockedControls(context, target.pos, target.node)[0];
430
+ return locked
431
+ ? refuse(
432
+ "read-only",
433
+ `Block ${handle} is in the locked content control ${quote(locked)}: its style cannot be changed.`,
434
+ )
435
+ : refuse("refused", `The style of block ${handle} could not be changed.`);
436
+ }
437
+ }
438
+ return { ok: true, ...changed(context, [handle]) };
439
+ }
440
+
441
+ export interface CommentOptions {
442
+ /** Text in the block to anchor the comment to, as `read` shows it. Default: the whole block. */
443
+ on?: string;
444
+ }
445
+
446
+ /** @internal */
447
+ export function comment(
448
+ context: Context,
449
+ handle: string,
450
+ text: string,
451
+ options: CommentOptions = {},
452
+ ): Result<Changed & { comment: number }> {
453
+ const { editor } = context;
454
+ const target = paragraphAt(context, handle, "a comment is anchored in a paragraph");
455
+ if ("ok" in target) return target;
456
+ const content = typeof text === "string" ? typed(text).trim() : "";
457
+ if (!content) return refuse("invalid", "A comment needs its text, a string.");
458
+ let from = target.pos + 1;
459
+ let to = target.pos + target.node.nodeSize - 1;
460
+ const on = options?.on;
461
+ if (on !== undefined) {
462
+ const query = typeof on === "string" ? typed(on) : "";
463
+ if (!query) return refuse("invalid", "on must be text of the block, as read shows it.");
464
+ const matches = findAll(editor, query, { matchCase: true }).filter(
465
+ (m) => m.story === null && m.from >= from && m.to <= to,
466
+ );
467
+ const match = matches[0];
468
+ if (!match || matches.length > 1) {
469
+ const now = changed(context, [handle]).blocks[0]?.text ?? "";
470
+ return match
471
+ ? refuse(
472
+ "several-matches",
473
+ `${quote(query)} is in block ${handle} ${matches.length} times. Give a longer text that is there once.`,
474
+ )
475
+ : refuse(
476
+ "no-match",
477
+ `${quote(query)} is not in block ${handle}. Capitals and spaces count. Its text is: ${quote(now, 2000)}`,
478
+ );
479
+ }
480
+ ({ from, to } = match);
481
+ }
482
+ const ids = () => new Set(wordContext(editor.state)?.envelope.comments.map((c) => c.id));
483
+ const before = ids();
484
+ editor.select(from, to);
485
+ // Word shows a comment's initials beside it: the author's, as Word makes them.
486
+ const initials = context.author
487
+ .split(/\s+/)
488
+ .map((word) => [...word][0] ?? "") // by code point: no half of a surrogate pair
489
+ .slice(0, 9)
490
+ .join("");
491
+ if (!editor.run(addComment(content, { initials })))
492
+ return refuse("refused", `Block ${handle} could not be commented.`);
493
+ const made = [...ids()].find((id) => !before.has(id));
494
+ if (made === undefined) return refuse("refused", `Block ${handle} could not be commented.`);
495
+ return { ok: true, comment: made, ...changed(context, [handle]) };
496
+ }