@folijs/agent 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +124 -21
  3. package/dist/changes.d.ts +23 -0
  4. package/dist/changes.d.ts.map +1 -0
  5. package/dist/changes.js +136 -0
  6. package/dist/changes.js.map +1 -0
  7. package/dist/formatting.d.ts +24 -0
  8. package/dist/formatting.d.ts.map +1 -0
  9. package/dist/formatting.js +106 -0
  10. package/dist/formatting.js.map +1 -0
  11. package/dist/handles.js +32 -12
  12. package/dist/handles.js.map +1 -1
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/inserts.d.ts +42 -0
  18. package/dist/inserts.d.ts.map +1 -0
  19. package/dist/inserts.js +242 -0
  20. package/dist/inserts.js.map +1 -0
  21. package/dist/operations.d.ts.map +1 -1
  22. package/dist/operations.js +52 -27
  23. package/dist/operations.js.map +1 -1
  24. package/dist/paragraphs.d.ts +16 -0
  25. package/dist/paragraphs.d.ts.map +1 -0
  26. package/dist/paragraphs.js +146 -0
  27. package/dist/paragraphs.js.map +1 -0
  28. package/dist/read.d.ts +15 -1
  29. package/dist/read.d.ts.map +1 -1
  30. package/dist/read.js +138 -6
  31. package/dist/read.js.map +1 -1
  32. package/dist/schema.d.ts +25 -0
  33. package/dist/schema.d.ts.map +1 -0
  34. package/dist/schema.js +51 -0
  35. package/dist/schema.js.map +1 -0
  36. package/dist/session.d.ts +79 -2
  37. package/dist/session.d.ts.map +1 -1
  38. package/dist/session.js +141 -16
  39. package/dist/session.js.map +1 -1
  40. package/dist/stories.d.ts +2 -0
  41. package/dist/stories.d.ts.map +1 -0
  42. package/dist/stories.js +80 -0
  43. package/dist/stories.js.map +1 -0
  44. package/dist/tables.d.ts +21 -0
  45. package/dist/tables.d.ts.map +1 -0
  46. package/dist/tables.js +485 -0
  47. package/dist/tables.js.map +1 -0
  48. package/dist/tools.d.ts +89 -0
  49. package/dist/tools.d.ts.map +1 -0
  50. package/dist/tools.js +717 -0
  51. package/dist/tools.js.map +1 -0
  52. package/package.json +4 -4
  53. package/src/changes.ts +193 -0
  54. package/src/formatting.ts +149 -0
  55. package/src/handles.ts +40 -13
  56. package/src/index.ts +23 -0
  57. package/src/inserts.ts +339 -0
  58. package/src/operations.ts +71 -34
  59. package/src/paragraphs.ts +188 -0
  60. package/src/read.ts +141 -9
  61. package/src/schema.ts +74 -0
  62. package/src/session.ts +247 -18
  63. package/src/stories.ts +92 -0
  64. package/src/tables.ts +664 -0
  65. package/src/tools.ts +925 -0
package/src/session.ts CHANGED
@@ -9,11 +9,15 @@ import {
9
9
  type Node,
10
10
  Slice,
11
11
  type Step,
12
+ tableStyles,
12
13
  trackState,
13
14
  untracked,
14
15
  } from "@folijs/core";
15
16
  import { withEnvelope, withTrackState, wordContext } from "@folijs/core/internal";
17
+ import { type ChangeInfo, listChanges, type ResolveOptions, resolveChanges } from "./changes.js";
18
+ import { type FormatOptions, formatText, type TextFormat } from "./formatting.js";
16
19
  import { Handles } from "./handles.js";
20
+ import { type InsertItem, type InsertItemOptions, insertItem } from "./inserts.js";
17
21
  import {
18
22
  type Changed,
19
23
  type CommentOptions,
@@ -29,8 +33,28 @@ import {
29
33
  setStyle,
30
34
  styles,
31
35
  } from "./operations.js";
32
- import { type Block, formatBlocks, readBlocks } from "./read.js";
33
- import { type Result, refuse } from "./result.js";
36
+ import { formatParagraphs, type ParagraphFormat } from "./paragraphs.js";
37
+ import {
38
+ type Block,
39
+ formatBlocks,
40
+ paragraphFormatting,
41
+ readBlocks,
42
+ runFormatting,
43
+ } from "./read.js";
44
+ import { type Refusal, type Result, refuse } from "./result.js";
45
+ import { type StoryKind, storyUses } from "./stories.js";
46
+ import {
47
+ type CellText,
48
+ deleteRows,
49
+ type InsertTableOptions,
50
+ insertRows,
51
+ insertTable,
52
+ type ShadeOptions,
53
+ setCells,
54
+ setHeaderRows,
55
+ setTableStyle,
56
+ shadeCells,
57
+ } from "./tables.js";
34
58
  import {
35
59
  type Control,
36
60
  controls,
@@ -45,6 +69,11 @@ export interface SessionOptions {
45
69
  author: string;
46
70
  /** The app's custom node and mark types, as `createEditor` takes them. */
47
71
  extensions?: readonly Extension[];
72
+ /**
73
+ * The session may list, accept and reject the document's tracked changes, its own and
74
+ * others' (23.8). Off by default: an agent's edits are proposals for a person to decide.
75
+ */
76
+ review?: boolean;
48
77
  }
49
78
 
50
79
  export interface ReadOptions {
@@ -52,6 +81,14 @@ export interface ReadOptions {
52
81
  from?: string;
53
82
  /** At most this many blocks. Default: all of them. */
54
83
  limit?: number;
84
+ /** Also each paragraph's text formatting of its own (bold, font, size…): `Block.formatting`. */
85
+ formatting?: boolean;
86
+ /**
87
+ * Also the headers and footers, after the body (in a read in parts, after its last part),
88
+ * each under a line saying where it is used; their blocks' handles are `h1`, `f1`… and
89
+ * `Block.story` names them (23.7).
90
+ */
91
+ headers?: boolean;
55
92
  }
56
93
 
57
94
  export interface ReadResult {
@@ -71,11 +108,13 @@ export interface Session {
71
108
  */
72
109
  readonly editor: Editor;
73
110
  readonly author: string;
111
+ /** Whether the session reviews changes (`SessionOptions.review`). */
112
+ readonly reviewing: boolean;
74
113
  /** The document as it is now, to save or to export (`exportDocx` of `@folijs/docx`). */
75
114
  document(): FoliDocument;
76
115
  /**
77
- * The body as it would be with every tracked change accepted, a block per line. Headers,
78
- * footers and notes are not read. Refused when `from` names no block.
116
+ * The body as it would be with every tracked change accepted, a block per line. With
117
+ * `headers`, the headers and footers after it; the text of notes is not read. Refused when `from` names no block.
79
118
  */
80
119
  read(options?: ReadOptions): Result<ReadResult>;
81
120
  /** One block by its handle. */
@@ -148,6 +187,69 @@ export interface Session {
148
187
  * need a layout and are left), and fills its merge fields from `data`. A tracked change.
149
188
  */
150
189
  updateFields(options?: UpdateFieldsOptions): Result<FieldsReport & { text: string }>;
190
+ /**
191
+ * Inserts a table next to a block (after it by default), its cells' texts given row by row
192
+ * (rows shorter than the longest get empty cells), in Word's Table Grid style unless `style`
193
+ * names another; `header` makes its first row a header row. Returns the table's blocks.
194
+ */
195
+ insertTable(
196
+ handle: string,
197
+ cells: readonly (readonly string[])[],
198
+ options?: InsertTableOptions,
199
+ ): Result<Changed>;
200
+ /**
201
+ * Inserts rows after (or before) row `row` of a table, made like it, with these cells' texts.
202
+ * A table is named by its handle or by a paragraph's in one of its cells; rows and columns
203
+ * are numbered as `read` prints them (`r1 c1`). Returns the table's blocks.
204
+ */
205
+ insertRows(
206
+ handle: string,
207
+ row: number,
208
+ cells: readonly (readonly string[])[],
209
+ where?: "after" | "before",
210
+ ): Result<Changed>;
211
+ /** Deletes a table's rows (`rows`: how many); every row deletes the table. */
212
+ deleteRows(handle: string, rows: readonly number[]): Result<Changed & { rows: number }>;
213
+ /** Sets cells' whole text (a merged cell's is its top cell's). Returns the table's blocks. */
214
+ setCells(handle: string, cells: readonly CellText[]): Result<Changed>;
215
+ /** The table styles there are, by the names `setTableStyle` takes. */
216
+ tableStyles(): string[];
217
+ /** Gives a table a table style by name (capitals do not count), or none (null). */
218
+ setTableStyle(handle: string, style: string | null): Result<Changed>;
219
+ /** Shades a table's cells (`RRGGBB`; null takes it off): all, a row's, a column's or one. */
220
+ shadeCells(handle: string, fill: string | null, options?: ShadeOptions): Result<Changed>;
221
+ /** Makes the first `count` rows a table's header rows, repeated on each page; 0: none. */
222
+ setHeaderRows(handle: string, count: number): Result<Changed>;
223
+ /**
224
+ * Formats a paragraph's text, or `on` text in it (once, or every place with `all`): bold,
225
+ * italic, underline, strike, font, size, color, highlight, a link. What `format` leaves out
226
+ * stays. A tracked formatting change; a link, the text deleted and inserted again with it.
227
+ */
228
+ formatText(handle: string, format: TextFormat, options?: FormatOptions): Result<Changed>;
229
+ /** The body's tracked changes, a line each: `[c12] inserted, Bob (2026-11-20), in [b7]: "…"`. */
230
+ changes(): Result<{ changes: ChangeInfo[]; text: string }>;
231
+ /** Accepts changes by id, or "all" (every story too; `author`: only theirs). */
232
+ acceptChanges(
233
+ ids: readonly number[] | "all",
234
+ options?: ResolveOptions | null,
235
+ ): Result<{ text: string }>;
236
+ /** Rejects changes by id, or "all", as `acceptChanges` accepts them. */
237
+ rejectChanges(
238
+ ids: readonly number[] | "all",
239
+ options?: ResolveOptions | null,
240
+ ): Result<{ text: string }>;
241
+ /**
242
+ * Formats paragraphs (one handle, or several: those next to each other become one list):
243
+ * alignment, line spacing, space before and after, indentation (a list level in a list),
244
+ * list numbering. What `format` leaves out stays. Tracked formatting changes.
245
+ */
246
+ formatParagraphs(handles: string | readonly string[], format: ParagraphFormat): Result<Changed>;
247
+ /**
248
+ * Inserts a picture or a horizontal line as a paragraph of its own after (or before) a
249
+ * paragraph, a page or section break at its end (or start), a footnote or endnote at its end
250
+ * or after `on` text in it. Tracked as insertions. Returns the blocks it changed or made.
251
+ */
252
+ insertItem(handle: string, item: InsertItem, options?: InsertItemOptions): Result<Changed>;
151
253
  /**
152
254
  * Marks the document as it is now, to come back to: `rollback` takes back every edit made
153
255
  * since, the session's own and those made through `editor`, as if none had been (no tracked
@@ -170,7 +272,7 @@ export interface Checkpoint {
170
272
  * Throws on a document that does not validate, and on an empty `author`.
171
273
  */
172
274
  export function openSession(document: EditorDocument, options: SessionOptions): Session {
173
- const { author, extensions } = options;
275
+ const { author, extensions, review = false } = options;
174
276
  if (!author.trim()) throw new TypeError("openSession: `author` must name who edits");
175
277
  const editor = createEditor({
176
278
  document,
@@ -190,9 +292,68 @@ export function openSession(document: EditorDocument, options: SessionOptions):
190
292
 
191
293
  const context: Context = { editor, handles, author };
192
294
 
295
+ /** Headers' and footers' handles: `h1`…, `f1`…, each kind counted across its stories. */
296
+ const counters = { header: { n: 0 }, footer: { n: 0 } };
297
+ /** Each header's and footer's editor and handles, made when it is first read. */
298
+ const stories = new Map<string, Context & { id: string }>();
299
+ const storyContext = (id: string, kind: StoryKind): (Context & { id: string }) | null => {
300
+ let found = stories.get(id);
301
+ // The body's document replaced (`setDocument`): core made the story's editor anew.
302
+ if (found && editor.story(id) !== found.editor) {
303
+ stories.delete(id);
304
+ found = undefined;
305
+ }
306
+ if (!found) {
307
+ const story = editor.story(id);
308
+ if (!story) return null;
309
+ const prefix = kind === "header" ? "h" : "f";
310
+ found = {
311
+ id,
312
+ story: id,
313
+ editor: story,
314
+ handles: new Handles(story, prefix, counters[kind], { body: editor, id }),
315
+ author,
316
+ };
317
+ stories.set(id, found);
318
+ }
319
+ return found;
320
+ };
321
+ // `setDocument` on the body tells without a transaction: every story's handles go with it.
322
+ let lastBody = editor.state.doc;
323
+ editor.subscribe((state, transactions) => {
324
+ if (!transactions.length && state.doc !== lastBody) stories.clear();
325
+ lastBody = state.doc;
326
+ });
327
+ /** The context a handle's block is in: a header's or a footer's, else the body's. */
328
+ const contextOf = (handle: unknown): Context & { id?: string } => {
329
+ const first = Array.isArray(handle) ? handle[0] : handle;
330
+ if (typeof first === "string" && /^[hf][1-9]\d*$/.test(first))
331
+ for (const story of stories.values()) if (story.handles.issued(first)) return story;
332
+ return context;
333
+ };
334
+ /** Handles of several blocks: all in one story, or why not. */
335
+ const oneStory = (list: unknown): Refusal | null => {
336
+ if (!Array.isArray(list) || list.length < 2) return null;
337
+ const first = contextOf(list[0]);
338
+ return list.every((h) => contextOf(h) === first)
339
+ ? null
340
+ : refuse(
341
+ "invalid",
342
+ "These blocks are in different stories (the body, a header, a footer): one call for each.",
343
+ );
344
+ };
345
+ const NO_REVIEW = refuse(
346
+ "refused",
347
+ "This session does not review changes: a person accepts or rejects them in Word.",
348
+ );
349
+ const NO_COMMENT = refuse(
350
+ "invalid",
351
+ "Word keeps no comments in headers and footers: comment a paragraph of the body.",
352
+ );
353
+
193
354
  const read = (options: ReadOptions = {}): Result<ReadResult> => {
194
355
  // A model's tool call may send null for an object left out.
195
- const { from, limit } = options ?? {};
356
+ const { from, limit, formatting, headers } = options ?? {};
196
357
  if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
197
358
  return refuse("invalid", "limit must be a whole number above 0.");
198
359
  const all = readBlocks(editor.state, handles);
@@ -203,20 +364,47 @@ export function openSession(document: EditorDocument, options: SessionOptions):
203
364
  start = all.findIndex((block) => block.handle === from);
204
365
  }
205
366
  const blocks = all.slice(start, limit === undefined ? undefined : start + limit);
367
+ const formatted = (list: Block[], where: Context) => {
368
+ if (formatting !== true) return;
369
+ for (const block of list) {
370
+ const node =
371
+ block.kind === "paragraph" ? where.handles.resolve(block.handle)?.node : undefined;
372
+ const own = node
373
+ ? [paragraphFormatting(node), runFormatting(node)].filter(Boolean).join("; ")
374
+ : "";
375
+ if (own) block.formatting = own;
376
+ }
377
+ };
378
+ formatted(blocks, context);
206
379
  const next = all[start + blocks.length]?.handle ?? null;
207
- return { ok: true, text: formatBlocks(blocks), blocks, next };
380
+ let text = formatBlocks(blocks);
381
+ if (headers === true && next === null)
382
+ for (const use of storyUses(editor.state)) {
383
+ const story = storyContext(use.id, use.kind);
384
+ if (!story) continue;
385
+ const own = readBlocks(story.editor.state, story.handles).map((b) => ({
386
+ ...b,
387
+ story: { id: use.id, kind: use.kind },
388
+ }));
389
+ formatted(own, story);
390
+ blocks.push(...own);
391
+ text += `\n${use.label}:${own.length ? `\n${formatBlocks(own)}` : " empty"}`;
392
+ }
393
+ return { ok: true, text, blocks, next };
208
394
  };
209
395
 
210
396
  const block = (handle: string): Result<{ block: Block; text: string }> => {
211
- const target = resolve(context, handle);
397
+ const where = contextOf(handle);
398
+ const target = resolve(where, handle);
212
399
  if ("ok" in target) return target;
213
- const { blocks, text } = changed(context, [handle]);
400
+ const { blocks, text } = changed(where, [handle]);
214
401
  return { ok: true, block: blocks[0] as Block, text };
215
402
  };
216
403
 
217
404
  const checkpoint = (): Checkpoint => {
218
405
  const start = editor.state.doc;
219
406
  const ends = handles.snapshot();
407
+ const storyEnds = [...stories.values()].map((s) => [s.handles, s.handles.snapshot()] as const);
220
408
  // What the document holds besides its body (styles, numbering…), and undo's own state: a
221
409
  // rollback puts both back as they are now. The history plugin is found by its key's name
222
410
  // (core does not export the key): its state, given back to it, is taken as it is.
@@ -273,34 +461,75 @@ export function openSession(document: EditorDocument, options: SessionOptions):
273
461
  if (!editor.state.doc.eq(start))
274
462
  throw new Error("checkpoint: the rollback did not give the document back");
275
463
  handles.restore(ends);
464
+ for (const [own, snapshot] of storyEnds) own.restore(snapshot);
276
465
  },
277
466
  };
278
467
  };
279
468
 
469
+ /** An operation of several edits, all or none: a refusal takes back what it did before it. */
470
+ const whole = <T>(operation: () => Result<T>): Result<T> => {
471
+ const point = checkpoint();
472
+ let result: Result<T>;
473
+ try {
474
+ result = operation();
475
+ } catch (error) {
476
+ point.release();
477
+ throw error;
478
+ }
479
+ if (result.ok) point.release();
480
+ else point.rollback();
481
+ return result;
482
+ };
483
+
280
484
  return {
281
485
  checkpoint,
282
486
  editor,
283
487
  author,
488
+ reviewing: review,
489
+ changes: () => (review ? { ok: true, ...listChanges(context) } : NO_REVIEW),
490
+ acceptChanges: (ids, options) =>
491
+ review ? resolveChanges(context, ids, true, options) : NO_REVIEW,
492
+ rejectChanges: (ids, options) =>
493
+ review ? resolveChanges(context, ids, false, options) : NO_REVIEW,
284
494
  document: () => editor.getDocument(),
285
495
  read,
286
496
  block,
287
497
  replaceText: (handle, find, replacement, options) =>
288
- replaceText(context, handle, find, replacement, options),
289
- insertAfter: (handle, paragraphs) => insert(context, handle, paragraphs, "after"),
290
- insertBefore: (handle, paragraphs) => insert(context, handle, paragraphs, "before"),
291
- deleteBlock: (handle) => deleteBlock(context, handle),
498
+ replaceText(contextOf(handle), handle, find, replacement, options),
499
+ insertAfter: (handle, paragraphs) => insert(contextOf(handle), handle, paragraphs, "after"),
500
+ insertBefore: (handle, paragraphs) => insert(contextOf(handle), handle, paragraphs, "before"),
501
+ deleteBlock: (handle) => deleteBlock(contextOf(handle), handle),
292
502
  target: (handle) => {
293
- const found = resolve(context, handle);
503
+ const where = contextOf(handle);
504
+ const found = resolve(where, handle);
294
505
  if ("ok" in found) return found;
295
- // Its content: a paragraph's text, a table's cells.
506
+ // Its content: a paragraph's text, a table's cells; in its story, for a header's.
296
507
  const { pos, node } = found;
297
- return { ok: true, target: { story: null, from: pos + 1, to: pos + node.nodeSize - 1 } };
508
+ const story = where.id ?? null;
509
+ return { ok: true, target: { story, from: pos + 1, to: pos + node.nodeSize - 1 } };
298
510
  },
299
511
  styles: () => styles(context),
300
- setStyle: (handle, style) => setStyle(context, handle, style),
301
- comment: (handle, text, options) => comment(context, handle, text, options),
512
+ setStyle: (handle, style) => setStyle(contextOf(handle), handle, style),
513
+ comment: (handle, text, options) =>
514
+ contextOf(handle) === context ? comment(context, handle, text, options) : NO_COMMENT,
302
515
  controls: () => controls(context),
303
516
  fillControl: (name, value) => fillControl(context, name, value),
304
517
  updateFields: (options) => updateFields(context, options),
518
+ insertTable: (handle, cells, options) =>
519
+ whole(() => insertTable(contextOf(handle), handle, cells, options)),
520
+ insertRows: (handle, row, cells, where) =>
521
+ whole(() => insertRows(contextOf(handle), handle, row, cells, where)),
522
+ deleteRows: (handle, rows) => whole(() => deleteRows(contextOf(handle), handle, rows)),
523
+ setCells: (handle, cells) => whole(() => setCells(contextOf(handle), handle, cells)),
524
+ tableStyles: () => tableStyles(editor.state),
525
+ setTableStyle: (handle, style) => setTableStyle(contextOf(handle), handle, style),
526
+ shadeCells: (handle, fill, options) => shadeCells(contextOf(handle), handle, fill, options),
527
+ setHeaderRows: (handle, count) => setHeaderRows(contextOf(handle), handle, count),
528
+ insertItem: (handle, item, options) =>
529
+ whole(() => insertItem(contextOf(handle), handle, item, options)),
530
+ formatParagraphs: (handles, format) =>
531
+ oneStory(handles) ?? whole(() => formatParagraphs(contextOf(handles), handles, format)),
532
+ formatText: (handle, format, options) =>
533
+ whole(() => formatText(contextOf(handle), handle, format, options)),
305
534
  };
306
535
  }
package/src/stories.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Headers and footers (23.7): which there are, and where each is used, as `read` names them.
3
+ * Their blocks have handles of their own (`h1`, `f1`…) and the session's operations edit them
4
+ * through the story's editor, as the body's through the body's.
5
+ */
6
+ import type { EditorState, SectionJSON } from "@folijs/core";
7
+ import { wordContext } from "@folijs/core/internal";
8
+
9
+ /** @internal */
10
+ export type StoryKind = "header" | "footer";
11
+ type Slot = "default" | "first" | "even";
12
+ const SLOTS: readonly Slot[] = ["default", "first", "even"];
13
+ const WHICH: Record<Slot, string> = {
14
+ default: "",
15
+ first: "first page",
16
+ even: "even pages",
17
+ };
18
+
19
+ /** @internal A header or footer, and the sections that use it. */
20
+ export interface StoryUse {
21
+ id: string;
22
+ kind: StoryKind;
23
+ /** In words, for a read: "header of sections 1–2, first page". */
24
+ label: string;
25
+ }
26
+
27
+ /** The document's sections in order: each paragraph that ends one, then the last. */
28
+ function sections(state: EditorState): SectionJSON[] {
29
+ const out: SectionJSON[] = [];
30
+ state.doc.forEach((node) => {
31
+ const section = node.attrs.section as SectionJSON | null | undefined;
32
+ if (node.type.name === "paragraph" && section) out.push(section);
33
+ });
34
+ const last = wordContext(state)?.envelope.section;
35
+ if (last) out.push(last);
36
+ return out;
37
+ }
38
+
39
+ const range = (numbers: number[]) => {
40
+ const parts: string[] = [];
41
+ for (let i = 0; i < numbers.length; i++) {
42
+ let j = i;
43
+ while (j + 1 < numbers.length && (numbers[j + 1] as number) === (numbers[j] as number) + 1) j++;
44
+ parts.push(j > i ? `${numbers[i]}–${numbers[j]}` : String(numbers[i]));
45
+ i = j;
46
+ }
47
+ return parts.join(", ");
48
+ };
49
+
50
+ /**
51
+ * @internal
52
+ * The headers and footers, in the order the sections first use them (a section without its own
53
+ * goes on with the one before's, as in Word); those no section uses last.
54
+ */
55
+ export function storyUses(state: EditorState): StoryUse[] {
56
+ const stories = wordContext(state)?.stories;
57
+ if (!stories) return [];
58
+ const uses = new Map<string, { kind: StoryKind; slots: Map<Slot, number[]> }>();
59
+ // As Word shows them: a first page's own only with the section's title page on, even pages'
60
+ // only with the document's even-and-odd setting.
61
+ const evenAndOdd = wordContext(state)?.envelope.settings?.evenAndOddHeaders === true;
62
+ const kinds: StoryKind[] = ["header", "footer"];
63
+ const current: Record<StoryKind, Partial<Record<Slot, string>>> = { header: {}, footer: {} };
64
+ sections(state).forEach((section, i) => {
65
+ for (const kind of kinds) {
66
+ const own = section[kind === "header" ? "headers" : "footers"];
67
+ if (own) current[kind] = { ...current[kind], ...own };
68
+ for (const slot of SLOTS) {
69
+ if (slot === "first" && section.titlePage !== true) continue;
70
+ if (slot === "even" && !evenAndOdd) continue;
71
+ const id = current[kind][slot];
72
+ if (!id || stories.get(id)?.kind !== kind) continue;
73
+ const use = uses.get(id) ?? { kind, slots: new Map() };
74
+ use.slots.set(slot, [...(use.slots.get(slot) ?? []), i + 1]);
75
+ uses.set(id, use);
76
+ }
77
+ }
78
+ });
79
+ const out: StoryUse[] = [];
80
+ for (const [id, { kind, slots }] of uses) {
81
+ const where = [...slots].map(([slot, numbers]) => {
82
+ const which = WHICH[slot];
83
+ const of = `${numbers.length > 1 ? "sections" : "section"} ${range(numbers)}`;
84
+ return which ? `${of}, ${which}` : of;
85
+ });
86
+ out.push({ id, kind, label: `${kind} of ${where.join("; ")}` });
87
+ }
88
+ for (const [id, story] of stories)
89
+ if ((story.kind === "header" || story.kind === "footer") && !uses.has(id))
90
+ out.push({ id, kind: story.kind, label: `${story.kind} not shown (no section uses it)` });
91
+ return out;
92
+ }