docxkeun 0.1.3 → 0.2.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 (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +137 -16
  3. package/dist/api/editor.d.ts +172 -5
  4. package/dist/api/editor.js +814 -24
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +5 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +390 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/charts/color.d.ts +45 -0
  18. package/dist/charts/color.js +322 -0
  19. package/dist/charts/format.d.ts +12 -0
  20. package/dist/charts/format.js +459 -0
  21. package/dist/charts/index.d.ts +11 -0
  22. package/dist/charts/index.js +8 -0
  23. package/dist/charts/model.d.ts +225 -0
  24. package/dist/charts/model.js +758 -0
  25. package/dist/charts/outline.d.ts +17 -0
  26. package/dist/charts/outline.js +214 -0
  27. package/dist/charts/render.d.ts +20 -0
  28. package/dist/charts/render.js +1772 -0
  29. package/dist/drawing/arrows.d.ts +37 -0
  30. package/dist/drawing/arrows.js +99 -0
  31. package/dist/drawing/formula.d.ts +40 -0
  32. package/dist/drawing/formula.js +159 -0
  33. package/dist/drawing/geometry.d.ts +61 -0
  34. package/dist/drawing/geometry.js +286 -0
  35. package/dist/drawing/index.d.ts +12 -0
  36. package/dist/drawing/index.js +8 -0
  37. package/dist/drawing/presets.d.ts +72 -0
  38. package/dist/drawing/presets.js +2874 -0
  39. package/dist/fonts/shaping/apply.d.ts +94 -0
  40. package/dist/fonts/shaping/apply.js +349 -0
  41. package/dist/fonts/shaping/arabic.d.ts +28 -0
  42. package/dist/fonts/shaping/arabic.js +235 -0
  43. package/dist/fonts/shaping/buffer.d.ts +53 -0
  44. package/dist/fonts/shaping/buffer.js +95 -0
  45. package/dist/fonts/shaping/gdef.d.ts +30 -0
  46. package/dist/fonts/shaping/gdef.js +66 -0
  47. package/dist/fonts/shaping/gpos.d.ts +86 -0
  48. package/dist/fonts/shaping/gpos.js +428 -0
  49. package/dist/fonts/shaping/gsub.d.ts +65 -0
  50. package/dist/fonts/shaping/gsub.js +313 -0
  51. package/dist/fonts/shaping/index.d.ts +32 -0
  52. package/dist/fonts/shaping/index.js +402 -0
  53. package/dist/fonts/shaping/indic.d.ts +6 -0
  54. package/dist/fonts/shaping/indic.js +805 -0
  55. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  56. package/dist/fonts/shaping/layout-common.js +349 -0
  57. package/dist/fonts/shaping/plan.d.ts +87 -0
  58. package/dist/fonts/shaping/plan.js +152 -0
  59. package/dist/fonts/shaping/scripts.d.ts +26 -0
  60. package/dist/fonts/shaping/scripts.js +160 -0
  61. package/dist/fonts/shaping/shaper.d.ts +23 -0
  62. package/dist/fonts/shaping/shaper.js +5 -0
  63. package/dist/fonts/shaping/unicode.d.ts +34 -0
  64. package/dist/fonts/shaping/unicode.js +138 -0
  65. package/dist/images/bmp.d.ts +9 -0
  66. package/dist/images/bmp.js +234 -0
  67. package/dist/images/gif.d.ts +9 -0
  68. package/dist/images/gif.js +215 -0
  69. package/dist/images/index.d.ts +18 -0
  70. package/dist/images/index.js +63 -0
  71. package/dist/images/png-encode.d.ts +4 -0
  72. package/dist/images/png-encode.js +73 -0
  73. package/dist/images/size.d.ts +10 -0
  74. package/dist/images/size.js +83 -0
  75. package/dist/images/tiff.d.ts +14 -0
  76. package/dist/images/tiff.js +407 -0
  77. package/dist/index.d.ts +7 -2
  78. package/dist/index.js +5 -0
  79. package/dist/layout/bidi.d.ts +18 -0
  80. package/dist/layout/bidi.js +71 -0
  81. package/dist/layout/blocks.d.ts +20 -3
  82. package/dist/layout/blocks.js +88 -58
  83. package/dist/layout/cache.d.ts +31 -0
  84. package/dist/layout/cache.js +38 -0
  85. package/dist/layout/drawing.d.ts +30 -0
  86. package/dist/layout/drawing.js +120 -0
  87. package/dist/layout/engine.d.ts +3 -0
  88. package/dist/layout/engine.js +218 -11
  89. package/dist/layout/index.d.ts +1 -0
  90. package/dist/layout/index.js +1 -0
  91. package/dist/layout/lines.d.ts +63 -5
  92. package/dist/layout/lines.js +245 -20
  93. package/dist/layout/paint.d.ts +25 -3
  94. package/dist/layout/paint.js +26 -10
  95. package/dist/layout/shapes.d.ts +7 -0
  96. package/dist/layout/shapes.js +338 -0
  97. package/dist/layout/style.d.ts +4 -0
  98. package/dist/layout/style.js +2 -0
  99. package/dist/layout/types.d.ts +89 -2
  100. package/dist/math/boxes.d.ts +88 -0
  101. package/dist/math/boxes.js +166 -0
  102. package/dist/math/index.d.ts +29 -0
  103. package/dist/math/index.js +44 -0
  104. package/dist/math/layout.d.ts +13 -0
  105. package/dist/math/layout.js +771 -0
  106. package/dist/math/linear.d.ts +3 -0
  107. package/dist/math/linear.js +152 -0
  108. package/dist/math/omml.d.ts +15 -0
  109. package/dist/math/omml.js +57 -0
  110. package/dist/math/paths.d.ts +61 -0
  111. package/dist/math/paths.js +450 -0
  112. package/dist/math/symbols.d.ts +49 -0
  113. package/dist/math/symbols.js +269 -0
  114. package/dist/math/text.d.ts +53 -0
  115. package/dist/math/text.js +316 -0
  116. package/dist/metafile/canvas.d.ts +80 -0
  117. package/dist/metafile/canvas.js +515 -0
  118. package/dist/metafile/dib.d.ts +27 -0
  119. package/dist/metafile/dib.js +300 -0
  120. package/dist/metafile/emf.d.ts +31 -0
  121. package/dist/metafile/emf.js +591 -0
  122. package/dist/metafile/geometry.d.ts +49 -0
  123. package/dist/metafile/geometry.js +85 -0
  124. package/dist/metafile/index.d.ts +27 -0
  125. package/dist/metafile/index.js +34 -0
  126. package/dist/metafile/reader.d.ts +28 -0
  127. package/dist/metafile/reader.js +59 -0
  128. package/dist/metafile/state.d.ts +118 -0
  129. package/dist/metafile/state.js +172 -0
  130. package/dist/metafile/text.d.ts +17 -0
  131. package/dist/metafile/text.js +130 -0
  132. package/dist/metafile/wmf.d.ts +33 -0
  133. package/dist/metafile/wmf.js +395 -0
  134. package/dist/model/content.d.ts +92 -7
  135. package/dist/model/content.js +251 -17
  136. package/dist/model/document.d.ts +34 -1
  137. package/dist/model/document.js +80 -1
  138. package/dist/model/fields.d.ts +4 -0
  139. package/dist/model/fields.js +10 -0
  140. package/dist/model/numbering.d.ts +2 -0
  141. package/dist/model/numbering.js +22 -0
  142. package/dist/model/props.d.ts +2 -0
  143. package/dist/model/props.js +3 -0
  144. package/dist/opc/index.d.ts +1 -1
  145. package/dist/opc/package.d.ts +34 -0
  146. package/dist/opc/package.js +58 -4
  147. package/dist/pdf/export.js +97 -6
  148. package/dist/pdf/images.d.ts +7 -0
  149. package/dist/pdf/images.js +39 -2
  150. package/dist/render/activity.d.ts +138 -0
  151. package/dist/render/activity.js +794 -0
  152. package/dist/render/clipboard.d.ts +29 -0
  153. package/dist/render/clipboard.js +401 -0
  154. package/dist/render/comments.d.ts +166 -0
  155. package/dist/render/comments.js +779 -0
  156. package/dist/render/context-menu.d.ts +124 -0
  157. package/dist/render/context-menu.js +525 -0
  158. package/dist/render/editing.d.ts +146 -5
  159. package/dist/render/editing.js +678 -53
  160. package/dist/render/index.d.ts +12 -0
  161. package/dist/render/index.js +11 -0
  162. package/dist/render/navigation-panel.d.ts +76 -0
  163. package/dist/render/navigation-panel.js +431 -0
  164. package/dist/render/selection.js +5 -0
  165. package/dist/render/svg.d.ts +4 -6
  166. package/dist/render/svg.js +69 -7
  167. package/dist/render/toolbar.d.ts +83 -0
  168. package/dist/render/toolbar.js +505 -0
  169. package/dist/render/ui/comment-layout.d.ts +39 -0
  170. package/dist/render/ui/comment-layout.js +79 -0
  171. package/dist/render/ui/icons.d.ts +6 -0
  172. package/dist/render/ui/icons.js +38 -0
  173. package/dist/render/ui/menu.d.ts +38 -0
  174. package/dist/render/ui/menu.js +274 -0
  175. package/dist/render/ui/nav-model.d.ts +11 -0
  176. package/dist/render/ui/nav-model.js +34 -0
  177. package/dist/render/ui/overflow.d.ts +5 -0
  178. package/dist/render/ui/overflow.js +18 -0
  179. package/dist/render/ui/popover.d.ts +18 -0
  180. package/dist/render/ui/popover.js +109 -0
  181. package/dist/render/ui/theme.d.ts +2 -0
  182. package/dist/render/ui/theme.js +29 -0
  183. package/dist/render/undo.d.ts +76 -0
  184. package/dist/render/undo.js +144 -0
  185. package/dist/render/viewer.d.ts +100 -7
  186. package/dist/render/viewer.js +302 -92
  187. package/dist/security/policy.d.ts +3 -0
  188. package/dist/security/policy.js +6 -2
  189. package/dist/security/protection.d.ts +1 -0
  190. package/dist/security/protection.js +1 -1
  191. package/dist/text/bidi-data.d.ts +53 -0
  192. package/dist/text/bidi-data.js +318 -0
  193. package/dist/text/bidi.d.ts +37 -0
  194. package/dist/text/bidi.js +508 -0
  195. package/dist/xml/ns.d.ts +5 -0
  196. package/dist/xml/ns.js +7 -0
  197. package/package.json +9 -2
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Headers and footers: creating, replacing and removing them, per section and per kind of page
3
+ * (default, first, even), with page-number fields and left / centre / right parts.
4
+ *
5
+ * In Word a section's w:sectPr points at header and footer parts (w:headerReference /
6
+ * w:footerReference by type); a "first" header needs w:titlePg in the section, and "even" headers
7
+ * need w:evenAndOddHeaders in settings. A section without its own reference shows the previous
8
+ * section's header.
9
+ */
10
+ import type { DocxDocument } from '../model/document.js';
11
+ import { type XmlElement } from '../xml/index.js';
12
+ export type HeaderFooterKind = 'header' | 'footer';
13
+ export type HeaderFooterType = 'default' | 'first' | 'even';
14
+ export interface HeaderFooterOptions {
15
+ /**
16
+ * Which pages: 'default' (every page, or the odd ones when even pages have their own), 'first'
17
+ * (the section's first page) or 'even'. Default 'default'.
18
+ */
19
+ type?: HeaderFooterType;
20
+ /** Section number from 1 (default: every section). */
21
+ section?: number;
22
+ /** Paragraph alignment (default: the Header/Footer style's, else left). */
23
+ align?: 'left' | 'center' | 'right';
24
+ }
25
+ export interface HeaderFooterInfo {
26
+ kind: HeaderFooterKind;
27
+ type: HeaderFooterType;
28
+ /** Sections (from 1) that use it. */
29
+ sections: number[];
30
+ part: string;
31
+ /** Its text, with page fields as {PAGE}, {NUMPAGES}, {SECTIONPAGES}. */
32
+ text: string;
33
+ }
34
+ /** Child order of w:sectPr (ECMA-376 CT_SectPr). */
35
+ export declare const SECTPR_ORDER: string[];
36
+ /** The sections' w:sectPr elements in order: paragraph-level ones, then the body's last one. */
37
+ export declare function sectionProperties(body: XmlElement): XmlElement[];
38
+ export declare function referencesOf(sectPr: XmlElement, kind: HeaderFooterKind): XmlElement[];
39
+ /** Text width of a section (page width minus margins), in twips. */
40
+ export declare function textWidth(sectPr: XmlElement | undefined): number;
41
+ /**
42
+ * Paragraphs for header or footer text: lines become paragraphs, a tab moves to the centre and then
43
+ * the right edge ("Left\tCentre\tRight"), and {PAGE}, {NUMPAGES} and {SECTIONPAGES} become fields.
44
+ */
45
+ export declare function headerParagraphs(doc: DocxDocument, kind: HeaderFooterKind, text: string, align: HeaderFooterOptions['align'], width: number): XmlElement[];
46
+ /** Header or footer paragraphs back to text, with page fields as {PAGE}. */
47
+ export declare function headerText(root: XmlElement): string;
48
+ /** Whether a section still has a first-page header or footer. */
49
+ export declare function hasFirstPage(sectPr: XmlElement): boolean;
50
+ /** Whether any section has an even-page header or footer. */
51
+ export declare function hasEvenPages(sectPrs: XmlElement[]): boolean;
@@ -0,0 +1,133 @@
1
+ import { attr, el, elements, findAll, firstChild, insertOrdered, removeChildren } from '../xml/index.js';
2
+ /** Child order of w:sectPr (ECMA-376 CT_SectPr). */
3
+ export const SECTPR_ORDER = [
4
+ 'w:headerReference',
5
+ 'w:footerReference',
6
+ 'w:footnotePr',
7
+ 'w:endnotePr',
8
+ 'w:type',
9
+ 'w:pgSz',
10
+ 'w:pgMar',
11
+ 'w:paperSrc',
12
+ 'w:pgBorders',
13
+ 'w:lnNumType',
14
+ 'w:pgNumType',
15
+ 'w:cols',
16
+ 'w:formProt',
17
+ 'w:vAlign',
18
+ 'w:noEndnote',
19
+ 'w:titlePg',
20
+ 'w:textDirection',
21
+ 'w:bidi',
22
+ 'w:rtlGutter',
23
+ 'w:docGrid',
24
+ 'w:printerSettings',
25
+ 'w:sectPrChange',
26
+ ];
27
+ /** The sections' w:sectPr elements in order: paragraph-level ones, then the body's last one. */
28
+ export function sectionProperties(body) {
29
+ const out = [];
30
+ const walk = (node) => {
31
+ for (const c of elements(node)) {
32
+ // Not the old properties kept by a tracked change (w:sectPrChange, w:pPrChange).
33
+ if (c.name === 'w:sectPrChange' || c.name === 'w:pPrChange')
34
+ continue;
35
+ if (c.name === 'w:sectPr') {
36
+ if (node.name === 'w:pPr' || node === body)
37
+ out.push(c);
38
+ continue;
39
+ }
40
+ walk(c);
41
+ }
42
+ };
43
+ walk(body);
44
+ // The body's own sectPr is its last child; paragraph ones come in document order before it.
45
+ const last = out.findIndex((s) => elements(body).includes(s));
46
+ if (last >= 0 && last !== out.length - 1)
47
+ out.push(...out.splice(last, 1));
48
+ return out;
49
+ }
50
+ const REF = { header: 'w:headerReference', footer: 'w:footerReference' };
51
+ export function referencesOf(sectPr, kind) {
52
+ return elements(sectPr, REF[kind]);
53
+ }
54
+ /** Text width of a section (page width minus margins), in twips. */
55
+ export function textWidth(sectPr) {
56
+ const w = Number(attr(firstChild(sectPr, 'w:pgSz'), 'w:w') ?? 12240);
57
+ const mar = firstChild(sectPr, 'w:pgMar');
58
+ const left = Number(attr(mar, 'w:left') ?? 1440);
59
+ const right = Number(attr(mar, 'w:right') ?? 1440);
60
+ const gutter = Number(attr(mar, 'w:gutter') ?? 0);
61
+ return Math.max(1440, w - left - right - gutter);
62
+ }
63
+ const FIELDS = new Set(['PAGE', 'NUMPAGES', 'SECTIONPAGES']);
64
+ /**
65
+ * Paragraphs for header or footer text: lines become paragraphs, a tab moves to the centre and then
66
+ * the right edge ("Left\tCentre\tRight"), and {PAGE}, {NUMPAGES} and {SECTIONPAGES} become fields.
67
+ */
68
+ export function headerParagraphs(doc, kind, text, align, width) {
69
+ const styleId = kind === 'header' ? 'Header' : 'Footer';
70
+ const hasStyle = !!doc.styles.get(styleId);
71
+ return text.split(/\r?\n/).map((line) => {
72
+ const pPr = [];
73
+ if (hasStyle)
74
+ pPr.push(el('w:pStyle', { 'w:val': styleId }));
75
+ if (line.includes('\t') && !hasStyle) {
76
+ pPr.push(el('w:tabs', {}, [el('w:tab', { 'w:val': 'center', 'w:pos': String(Math.round(width / 2)) }), el('w:tab', { 'w:val': 'right', 'w:pos': String(width) })]));
77
+ }
78
+ if (align)
79
+ pPr.push(el('w:jc', { 'w:val': align }));
80
+ const content = [];
81
+ for (const piece of line.split(/(\t|\{(?:PAGE|NUMPAGES|SECTIONPAGES)\})/)) {
82
+ if (!piece)
83
+ continue;
84
+ if (piece === '\t')
85
+ content.push(el('w:r', {}, [el('w:tab')]));
86
+ else if (piece.startsWith('{') && FIELDS.has(piece.slice(1, -1))) {
87
+ content.push(el('w:fldSimple', { 'w:instr': ` ${piece.slice(1, -1)} ` }, [el('w:r', {}, [el('w:t', {}, [{ type: 'text', value: '1' }])])]));
88
+ }
89
+ else {
90
+ const t = el('w:t', /^\s|\s$/.test(piece) ? { 'xml:space': 'preserve' } : {}, [{ type: 'text', value: piece }]);
91
+ content.push(el('w:r', {}, [t]));
92
+ }
93
+ }
94
+ return el('w:p', {}, [...(pPr.length ? [el('w:pPr', {}, pPr)] : []), ...content]);
95
+ });
96
+ }
97
+ /** Header or footer paragraphs back to text, with page fields as {PAGE}. */
98
+ export function headerText(root) {
99
+ const lines = [];
100
+ for (const p of findAll(root, 'w:p')) {
101
+ let s = '';
102
+ const walk = (n) => {
103
+ for (const c of n.children) {
104
+ if (c.type !== 'element')
105
+ continue;
106
+ if (c.name === 'w:delText' || c.name === 'w:del')
107
+ continue;
108
+ if (c.name === 'w:fldSimple') {
109
+ const instr = (attr(c, 'w:instr') ?? '').trim().split(/\s+/)[0]?.toUpperCase() ?? '';
110
+ s += FIELDS.has(instr) ? `{${instr}}` : '';
111
+ continue;
112
+ }
113
+ if (c.name === 'w:t')
114
+ s += c.children.map((t) => (t.type === 'text' ? t.value : '')).join('');
115
+ else if (c.name === 'w:tab' && n.name === 'w:r')
116
+ s += '\t';
117
+ else
118
+ walk(c);
119
+ }
120
+ };
121
+ walk(p);
122
+ lines.push(s);
123
+ }
124
+ return lines.join('\n');
125
+ }
126
+ /** Whether a section still has a first-page header or footer. */
127
+ export function hasFirstPage(sectPr) {
128
+ return [...referencesOf(sectPr, 'header'), ...referencesOf(sectPr, 'footer')].some((r) => attr(r, 'w:type') === 'first');
129
+ }
130
+ /** Whether any section has an even-page header or footer. */
131
+ export function hasEvenPages(sectPrs) {
132
+ return sectPrs.some((sp) => [...referencesOf(sp, 'header'), ...referencesOf(sp, 'footer')].some((r) => attr(r, 'w:type') === 'even'));
133
+ }
@@ -1,3 +1,7 @@
1
- export { DocxEditor, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG, type EditAction, type EditGuard, type TextFormat, type CommentInput, type Match, type LockMode, type LockedRegion } from './editor.js';
1
+ export { DocxEditor, OBJECT_CHAR, paragraphText, paragraphsOf, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG, type EditAction, type EditGuard, type TextFormat, type CommentInput, type Match, type LockMode, type LockedRegion, type SetListOptions, type EditorOptions, type ParagraphFormat, documentTracksChanges } from './editor.js';
2
+ export { listRevisions, acceptRevisions, rejectRevisions, type Revision, type RevisionKind, type RevisionFilter } from './revisions.js';
3
+ export { LIST_FORMATS, type ListFormat, type ListItem } from './lists.js';
2
4
  export { EditError, TreeIndex, type DocPosition, type DocRange } from './positions.js';
3
5
  export { ensurePart, randomHexId } from './parts.js';
6
+ export { selectionInfoFor, describeSelection, type SelectionInfo, type SelectedParagraph, type TextSpot } from './selection.js';
7
+ export type { HeaderFooterInfo, HeaderFooterKind, HeaderFooterOptions, HeaderFooterType } from './headers.js';
package/dist/api/index.js CHANGED
@@ -1,3 +1,6 @@
1
- export { DocxEditor, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG } from './editor.js';
1
+ export { DocxEditor, OBJECT_CHAR, paragraphText, paragraphsOf, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG, documentTracksChanges } from './editor.js';
2
+ export { listRevisions, acceptRevisions, rejectRevisions } from './revisions.js';
3
+ export { LIST_FORMATS } from './lists.js';
2
4
  export { EditError, TreeIndex } from './positions.js';
3
5
  export { ensurePart, randomHexId } from './parts.js';
6
+ export { selectionInfoFor, describeSelection } from './selection.js';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * List editing: the labels list paragraphs show ("1.", "a)", "•"), and changing a list's format,
3
+ * level or start number. A changed list gets its own definition in numbering.xml, copied from the
4
+ * list it was in, so its indentation, tabs and label fonts stay as they were.
5
+ */
6
+ import type { DocParagraph } from '../model/content.js';
7
+ import type { DocxDocument } from '../model/document.js';
8
+ import { type XmlElement } from '../xml/index.js';
9
+ /** List formats docxkeun can apply: bullets, or numbers shown as 1. 1) a. A. i. I. */
10
+ export type ListFormat = 'bullet' | 'decimal' | 'decimalParen' | 'lowerLetter' | 'upperLetter' | 'lowerRoman' | 'upperRoman';
11
+ export declare const LIST_FORMATS: readonly ListFormat[];
12
+ export interface ListItem {
13
+ numId: string;
14
+ /** List level, 0-based (Word's w:ilvl). */
15
+ level: number;
16
+ /** Word's number format for that level: 'bullet', 'decimal', 'lowerLetter', ... */
17
+ format: string;
18
+ /** The label as Word shows it, e.g. "1.", "b)", "iv.", "•". */
19
+ label: string;
20
+ }
21
+ /** Labels of the list paragraphs among `paragraphs` (in document order, as layout numbers them). */
22
+ export declare function listItems(doc: DocxDocument, paragraphs: DocParagraph[]): Map<XmlElement, ListItem>;
23
+ export interface NewListOptions {
24
+ /** A format for the levels in `levels`, or 'keep' to keep the base list's formats (to restart numbering). */
25
+ format: ListFormat | 'keep';
26
+ /** Levels the list paragraphs use. */
27
+ levels: Set<number>;
28
+ /** First number for those levels. */
29
+ start?: number;
30
+ /** The list to copy indentation and label formatting from. */
31
+ base?: {
32
+ numId: string;
33
+ abstractId: string | undefined;
34
+ };
35
+ }
36
+ /** Add a list definition (abstractNum + num) to numbering.xml and return its numId. */
37
+ export declare function createList(doc: DocxDocument, options: NewListOptions): Promise<string>;
@@ -0,0 +1,132 @@
1
+ import { normaliseBullet, NumberingCounter } from '../model/numbering.js';
2
+ import { attr, cloneElement, el, elements, ensureChild, firstChild, insertOrdered, removeChildren } from '../xml/index.js';
3
+ import { ensurePart, randomHexId } from './parts.js';
4
+ export const LIST_FORMATS = ['bullet', 'decimal', 'decimalParen', 'lowerLetter', 'upperLetter', 'lowerRoman', 'upperRoman'];
5
+ /** Child order of w:lvl. */
6
+ const LVL_ORDER = ['w:start', 'w:numFmt', 'w:lvlRestart', 'w:pStyle', 'w:isLgl', 'w:suff', 'w:lvlText', 'w:lvlPicBulletId', 'w:legacy', 'w:lvlJc', 'w:pPr', 'w:rPr'];
7
+ const RPR_FONTS = ['w:rStyle', 'w:rFonts'];
8
+ /** Bullets per level (repeating): a round bullet, an open circle and a small square. */
9
+ const BULLETS = [{ text: '•' }, { text: 'o', font: 'Courier New' }, { text: '▪', font: 'Arial' }];
10
+ /** Word's default numbering for the levels a change does not pick a format for. */
11
+ const NUMBER_CYCLE = ['decimal', 'lowerLetter', 'lowerRoman'];
12
+ /** Labels of the list paragraphs among `paragraphs` (in document order, as layout numbers them). */
13
+ export function listItems(doc, paragraphs) {
14
+ const counter = new NumberingCounter(doc.numbering, (s) => doc.styles.get(s)?.pPr.numId);
15
+ const out = new Map();
16
+ for (const p of paragraphs) {
17
+ if (!p.numbering)
18
+ continue;
19
+ const next = counter.next(p.numbering.numId, p.numbering.ilvl);
20
+ if (!next)
21
+ continue;
22
+ out.set(p.el, { numId: p.numbering.numId, level: p.numbering.ilvl, format: next.level.format, label: normaliseBullet(next.label) });
23
+ }
24
+ return out;
25
+ }
26
+ function val(node) {
27
+ return attr(node, 'w:val');
28
+ }
29
+ function setVal(lvl, name, value) {
30
+ removeChildren(lvl, name);
31
+ insertOrdered(lvl, el(name, { 'w:val': value }), LVL_ORDER);
32
+ }
33
+ function defaultLevel(ilvl) {
34
+ const left = 720 * (ilvl + 1);
35
+ return el('w:lvl', { 'w:ilvl': String(ilvl) }, [
36
+ el('w:start', { 'w:val': '1' }),
37
+ el('w:numFmt', { 'w:val': NUMBER_CYCLE[ilvl % 3] }),
38
+ el('w:lvlText', { 'w:val': `%${ilvl + 1}.` }),
39
+ el('w:lvlJc', { 'w:val': ilvl % 3 === 2 ? 'right' : 'left' }),
40
+ el('w:pPr', {}, [el('w:ind', { 'w:left': String(left), 'w:hanging': ilvl % 3 === 2 ? '180' : '360' })]),
41
+ ]);
42
+ }
43
+ /** Give a level a new format. Numbers keep the level's own label font; bullets get theirs. */
44
+ function applyFormat(lvl, format, ilvl) {
45
+ const wasBullet = val(firstChild(lvl, 'w:numFmt')) === 'bullet';
46
+ removeChildren(lvl, 'w:lvlPicBulletId');
47
+ const rPr = firstChild(lvl, 'w:rPr');
48
+ if (format === 'bullet') {
49
+ const bullet = BULLETS[ilvl % BULLETS.length];
50
+ setVal(lvl, 'w:numFmt', 'bullet');
51
+ setVal(lvl, 'w:lvlText', bullet.text);
52
+ const target = rPr ?? ensureChild(lvl, 'w:rPr', LVL_ORDER);
53
+ removeChildren(target, 'w:rFonts');
54
+ if (bullet.font)
55
+ insertOrdered(target, el('w:rFonts', { 'w:ascii': bullet.font, 'w:hAnsi': bullet.font, 'w:hint': 'default' }), RPR_FONTS);
56
+ if (val(firstChild(lvl, 'w:lvlJc')) === 'right')
57
+ setVal(lvl, 'w:lvlJc', 'left');
58
+ return;
59
+ }
60
+ setVal(lvl, 'w:numFmt', format === 'decimalParen' ? 'decimal' : format);
61
+ setVal(lvl, 'w:lvlText', `%${ilvl + 1}${format === 'decimalParen' ? ')' : '.'}`);
62
+ // A bullet's symbol font (Symbol, Wingdings, Courier New) would turn digits into symbols.
63
+ if (wasBullet && rPr)
64
+ removeChildren(rPr, 'w:rFonts');
65
+ }
66
+ function familyOf(format) {
67
+ return format === 'bullet' ? 'bullet' : format === 'none' ? 'none' : 'number';
68
+ }
69
+ function maxId(nodes, name) {
70
+ return nodes.reduce((m, n) => Math.max(m, Number.parseInt(attr(n, name) ?? '', 10) || 0), 0);
71
+ }
72
+ /** The w:lvl elements a num uses: its abstract definition's, with lvlOverride levels on top. */
73
+ function levelsOf(numbering, numId, abstractId) {
74
+ const out = new Map();
75
+ const abs = elements(numbering, 'w:abstractNum').find((a) => attr(a, 'w:abstractNumId') === abstractId);
76
+ for (const l of abs ? elements(abs, 'w:lvl') : [])
77
+ out.set(Number(attr(l, 'w:ilvl') ?? 0), l);
78
+ const num = elements(numbering, 'w:num').find((n) => attr(n, 'w:numId') === numId);
79
+ for (const o of num ? elements(num, 'w:lvlOverride') : []) {
80
+ const lvl = firstChild(o, 'w:lvl');
81
+ if (lvl)
82
+ out.set(Number(attr(o, 'w:ilvl') ?? 0), lvl);
83
+ }
84
+ return out;
85
+ }
86
+ /** Add a list definition (abstractNum + num) to numbering.xml and return its numId. */
87
+ export async function createList(doc, options) {
88
+ const part = await ensurePart(doc, 'numbering');
89
+ const root = part.xml.root;
90
+ const base = options.base ? levelsOf(root, options.base.numId, options.base.abstractId) : new Map();
91
+ const wanted = options.format === 'keep' ? undefined : familyOf(options.format);
92
+ const levels = [];
93
+ for (let i = 0; i < 9; i++) {
94
+ const from = base.get(i);
95
+ const lvl = from ? cloneElement(from) : defaultLevel(i);
96
+ lvl.attrs['w:ilvl'] = String(i);
97
+ if (options.format !== 'keep' && options.levels.has(i))
98
+ applyFormat(lvl, options.format, i);
99
+ else if (wanted && familyOf(val(firstChild(lvl, 'w:numFmt'))) !== wanted)
100
+ applyFormat(lvl, wanted === 'bullet' ? 'bullet' : NUMBER_CYCLE[i % 3], i);
101
+ if (options.start !== undefined && options.levels.has(i))
102
+ setVal(lvl, 'w:start', String(options.start));
103
+ levels.push(lvl);
104
+ }
105
+ const abstracts = elements(root, 'w:abstractNum');
106
+ const nums = elements(root, 'w:num');
107
+ const abstractId = String(maxId(abstracts, 'w:abstractNumId') + 1);
108
+ const numId = String(maxId(nums, 'w:numId') + 1);
109
+ const abstractNum = el('w:abstractNum', { 'w:abstractNumId': abstractId }, [
110
+ el('w:nsid', { 'w:val': randomHexId() }),
111
+ el('w:multiLevelType', { 'w:val': 'hybridMultilevel' }),
112
+ ...levels,
113
+ ]);
114
+ const num = el('w:num', { 'w:numId': numId }, [el('w:abstractNumId', { 'w:val': abstractId })]);
115
+ // numbering.xml order: numPicBullet*, abstractNum*, num*, numIdMacAtCleanup?
116
+ const children = root.children;
117
+ const lastOf = (name) => {
118
+ for (let i = children.length - 1; i >= 0; i--) {
119
+ const c = children[i];
120
+ if (c.type === 'element' && c.name === name)
121
+ return i;
122
+ }
123
+ return -1;
124
+ };
125
+ const afterAbstracts = Math.max(lastOf('w:abstractNum'), lastOf('w:numPicBullet')) + 1;
126
+ children.splice(afterAbstracts, 0, abstractNum);
127
+ const lastNum = lastOf('w:num');
128
+ const cleanup = lastOf('w:numIdMacAtCleanup');
129
+ children.splice(lastNum >= 0 ? lastNum + 1 : cleanup >= 0 ? cleanup : children.length, 0, num);
130
+ doc.touch(part.name);
131
+ return numId;
132
+ }
package/dist/api/parts.js CHANGED
@@ -10,6 +10,7 @@ export const PART_SPECS = {
10
10
  people: { name: 'word/people.xml', rel: REL.people, contentType: CONTENT_TYPE.people, root: 'w15:people' },
11
11
  settings: { name: 'word/settings.xml', rel: REL.settings, contentType: CONTENT_TYPE.settings, root: 'w:settings' },
12
12
  styles: { name: 'word/styles.xml', rel: REL.styles, contentType: CONTENT_TYPE.styles, root: 'w:styles' },
13
+ numbering: { name: 'word/numbering.xml', rel: REL.numbering, contentType: CONTENT_TYPE.numbering, root: 'w:numbering' },
13
14
  };
14
15
  /** Namespace declarations put on the roots of parts docxkeun creates. */
15
16
  export const ROOT_NAMESPACES = {
@@ -188,6 +188,7 @@ export const RPR_ORDER = [
188
188
  'w:eastAsianLayout',
189
189
  'w:specVanish',
190
190
  'w:oMath',
191
+ 'w:rPrChange',
191
192
  ];
192
193
  export const PPR_ORDER = [
193
194
  'w:pStyle',
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Tracked changes (revisions), the way Word stores them:
3
+ * - inserted runs inside `w:ins`, deleted runs inside `w:del` (their `w:t` become `w:delText`);
4
+ * - a paragraph mark inserted or deleted as `w:pPr/w:rPr/w:ins|w:del`;
5
+ * - formatting changes as `w:rPrChange` / `w:pPrChange` holding the old properties;
6
+ * - moves as `w:moveFrom` / `w:moveTo` (treated as a deletion and an insertion).
7
+ * This module records changes for the editor, lists them, and accepts or rejects them.
8
+ */
9
+ import { type XmlElement } from '../xml/index.js';
10
+ export interface RevisionAuthor {
11
+ author: string;
12
+ /** ISO date without milliseconds, as Word writes it. */
13
+ date: string;
14
+ }
15
+ export type RevisionKind = 'insert' | 'delete' | 'move-from' | 'move-to' | 'format' | 'paragraph-format' | 'paragraph-insert' | 'paragraph-delete' | 'row-insert' | 'row-delete' | 'property';
16
+ export interface Revision {
17
+ id: string;
18
+ kind: RevisionKind;
19
+ author: string;
20
+ date?: string;
21
+ /** Text the revision covers (inserted or deleted text; empty for formatting). */
22
+ text: string;
23
+ /** The paragraph it is in (or the first one it touches). */
24
+ paragraph?: XmlElement;
25
+ /** The element that carries the revision (w:ins, w:del, w:rPrChange, …). */
26
+ el: XmlElement;
27
+ }
28
+ export interface RevisionFilter {
29
+ ids?: string[];
30
+ author?: string;
31
+ }
32
+ export declare function revisionStamp(author: string, now?: Date): RevisionAuthor;
33
+ /** The next free revision id (ids are shared by all revision elements in a part). */
34
+ export declare function nextRevisionId(root: XmlElement): () => string;
35
+ /** Run properties of a new run must not carry another run's revision record. */
36
+ export declare function cleanRunProps(run: XmlElement): void;
37
+ /** Wrap runs (already in the tree, adjacent siblings) in one w:ins. */
38
+ export declare function wrapInserted(parent: XmlElement, runs: XmlElement[], id: string, who: RevisionAuthor): XmlElement;
39
+ /** A new w:ins element holding runs (not yet in the tree). */
40
+ export declare function insertedRuns(runs: XmlElement[], id: string, who: RevisionAuthor): XmlElement;
41
+ /** The w:ins / w:del / w:moveFrom / w:moveTo a run sits directly in, if any. */
42
+ export declare function runRevision(run: XmlElement, parentOf: (n: XmlElement) => XmlElement | undefined): XmlElement | undefined;
43
+ /**
44
+ * Mark a run as deleted by `who`. A run the same author inserted is removed outright (as Word does
45
+ * when you delete your own insertion); a run that is already deleted is left alone.
46
+ */
47
+ export declare function deleteRun(run: XmlElement, parentOf: (n: XmlElement) => XmlElement | undefined, nextId: () => string, who: RevisionAuthor): void;
48
+ /** How a paragraph's mark (its end) is tracked: inserted, deleted, or not at all. */
49
+ export declare function paragraphMarkRevision(p: XmlElement): {
50
+ kind: 'ins' | 'del';
51
+ el: XmlElement;
52
+ } | undefined;
53
+ export declare function markParagraph(p: XmlElement, kind: 'ins' | 'del', id: string, who: RevisionAuthor): void;
54
+ /** Record the run's current formatting before it changes (once: the oldest state is what counts). */
55
+ export declare function recordRunFormat(run: XmlElement, id: string, who: RevisionAuthor): void;
56
+ /** Record a paragraph's current properties before they change. */
57
+ export declare function recordParagraphFormat(p: XmlElement, id: string, who: RevisionAuthor, order: readonly string[]): void;
58
+ /** Every revision in a part, in document order. */
59
+ export declare function listRevisions(root: XmlElement): Revision[];
60
+ export declare function acceptRevisions(root: XmlElement, filter?: RevisionFilter): number;
61
+ export declare function rejectRevisions(root: XmlElement, filter?: RevisionFilter): number;