From 3539c06e923864d1b349b6b95c2c3b8e6d5fa26c Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 14 Feb 2026 03:54:25 +0000 Subject: [PATCH] docs: Improve inline docs and docs website (#3353) * docs: Improve inline docs and docs website * Fix lint * Fix spelling --- .cspell.json | 22 +- .github/copilot-instructions.md | 32 ++ .github/workflows/npm-publish.yml | 2 +- .prettierrc.yml | 3 +- CLAUDE.md | 25 + demo/10-my-cv.ts | 6 - docs/README.md | 38 +- docs/_coverpage.md | 6 +- docs/_sidebar.md | 89 ++-- docs/contribution-guidelines.md | 12 +- docs/index.html | 2 +- docs/quickstart.md | 191 +++++++ docs/troubleshooting.md | 415 +++++++++++++++ docs/usage/bookmarks.md | 188 +++++++ docs/usage/bullet-points.md | 230 ++++++++- docs/usage/change-tracking.md | 12 +- docs/usage/checkboxes.md | 168 ++++++ docs/usage/columns.md | 223 ++++++++ docs/usage/comments.md | 228 ++++++++- docs/usage/convenience-functions.md | 169 +++++- docs/usage/document.md | 121 ++++- docs/usage/fields.md | 24 +- docs/usage/fonts.md | 239 +++++++++ docs/usage/headers-and-footers.md | 432 ++++++++++++++-- docs/usage/hyperlinks.md | 4 + docs/usage/images.md | 44 +- docs/usage/line-numbers.md | 178 +++++++ docs/usage/numbering.md | 4 +- docs/usage/packers.md | 2 +- docs/usage/page-layout.md | 264 ++++++++++ docs/usage/page-numbers.md | 25 +- docs/usage/paragraph.md | 2 +- docs/usage/patcher.md | 7 +- docs/usage/sections.md | 225 ++++++-- docs/usage/styling-with-js.md | 78 +-- docs/usage/styling-with-xml.md | 5 +- docs/usage/symbols.md | 5 +- docs/usage/table-of-contents.md | 8 +- docs/usage/tables.md | 64 +-- docs/usage/templates.md | 283 ++++++++++ docs/usage/text-box.md | 202 +++++++- package.json | 2 +- src/export/formatter.ts | 27 + src/export/index.ts | 5 + src/export/packer/image-replacer.ts | 34 ++ src/export/packer/next-compiler.ts | 70 +++ src/export/packer/numbering-replacer.ts | 28 + src/export/packer/packer.ts | 91 +++- .../app-properties-attributes.ts | 17 + src/file/app-properties/app-properties.ts | 42 ++ src/file/border/border.ts | 77 ++- src/file/border/index.ts | 5 + src/file/checkbox/checkbox-symbol.ts | 49 +- src/file/checkbox/checkbox-util.ts | 70 ++- src/file/checkbox/checkbox.ts | 29 +- src/file/checkbox/index.ts | 5 + .../content-types/content-types-attributes.ts | 13 + src/file/content-types/content-types.ts | 17 + .../default/default-attributes.ts | 15 + src/file/content-types/default/default.ts | 16 + .../override/override-attributes.ts | 15 + src/file/content-types/override/override.ts | 22 + src/file/core-properties/index.ts | 5 + src/file/core-properties/properties.ts | 111 +++- .../custom-properties-attributes.ts | 17 + .../custom-properties/custom-properties.ts | 34 ++ .../custom-property-attributes.ts | 23 +- src/file/custom-properties/custom-property.ts | 51 +- src/file/custom-properties/index.ts | 5 + src/file/document-wrapper.ts | 34 ++ src/file/document/body/body.ts | 64 ++- src/file/document/body/index.ts | 5 + .../document/body/section-properties/index.ts | 5 + .../section-properties/properties/column.ts | 47 +- .../section-properties/properties/columns.ts | 73 ++- .../section-properties/properties/index.ts | 5 + .../properties/page-borders.ts | 149 ++++-- .../properties/page-margin.ts | 65 ++- .../properties/page-number.ts | 85 ++- .../properties/page-text-direction.ts | 34 ++ .../properties/section-type.ts | 70 ++- .../section-properties/section-properties.ts | 90 ++++ src/file/document/document-attributes.ts | 39 ++ .../document-background.ts | 120 +++-- .../document/document-background/index.ts | 5 + src/file/document/document.ts | 30 ++ src/file/document/index.ts | 5 + src/file/drawing/anchor/anchor-attributes.ts | 26 + src/file/drawing/anchor/index.ts | 5 + .../doc-properties/doc-properties-children.ts | 52 ++ .../drawing/effect-extent/effect-extent.ts | 34 +- src/file/drawing/extent/extent.ts | 36 +- .../drawing/floating/horizontal-position.ts | 45 +- src/file/drawing/floating/index.ts | 5 + .../drawing/floating/vertical-position.ts | 45 +- .../graphic-frame-lock-attributes.ts | 8 + .../graphic-frame-locks.ts | 29 ++ src/file/drawing/index.ts | 5 + .../graphic-data/graphic-data-attribute.ts | 18 + .../graphic/graphic-data/graphic-data.ts | 38 ++ .../inline/graphic/graphic-data/index.ts | 5 + .../graphic-data/pic/blip/blip-extentions.ts | 48 ++ .../graphic-data/pic/blip/blip-fill.ts | 36 ++ .../graphic/graphic-data/pic/blip/blip.ts | 58 +++ .../graphic-data/pic/blip/source-rectangle.ts | 32 ++ .../graphic/graphic-data/pic/blip/stretch.ts | 50 ++ .../inline/graphic/graphic-data/pic/index.ts | 5 + .../child-non-visual-pic-properties.ts | 35 ++ .../pic-locks/pic-locks-attributes.ts | 18 + .../pic-locks/pic-locks.ts | 44 ++ .../non-visual-pic-properties.ts | 34 ++ .../non-visual-properties-attributes.ts | 18 + .../non-visual-properties.ts | 51 +- .../graphic-data/pic/pic-attributes.ts | 15 + .../inline/graphic/graphic-data/pic/pic.ts | 38 ++ .../form/extents/extents-attributes.ts | 22 + .../shape-properties/form/extents/extents.ts | 31 ++ .../pic/shape-properties/form/form.ts | 49 ++ .../pic/shape-properties/form/index.ts | 5 + .../form/offset/off-attributes.ts | 22 + .../pic/shape-properties/form/offset/off.ts | 30 ++ .../pic/shape-properties/outline/no-fill.ts | 22 + .../pic/shape-properties/outline/outline.ts | 109 +++- .../pic/shape-properties/outline/rgb-color.ts | 33 ++ .../shape-properties/outline/scheme-color.ts | 57 +++ .../shape-properties/outline/solid-fill.ts | 51 ++ .../adjustment-values/adjustment-values.ts | 33 +- .../preset-geometry-attributes.ts | 20 + .../preset-geometry/preset-geometry.ts | 35 +- .../shape-properties-attributes.ts | 20 + .../pic/shape-properties/shape-properties.ts | 53 ++ src/file/drawing/inline/graphic/graphic.ts | 20 + src/file/drawing/inline/graphic/index.ts | 5 + src/file/drawing/inline/index.ts | 5 + src/file/drawing/text-wrap/index.ts | 5 + src/file/file.ts | 81 ++- src/file/fonts/create-regular-font.ts | 34 ++ src/file/fonts/font-wrapper.ts | 25 + src/file/fonts/font.ts | 139 +++-- src/file/fonts/index.ts | 5 + src/file/fonts/obfuscate-ttf-to-odttf.ts | 36 ++ src/file/footer-wrapper.ts | 35 ++ src/file/footer/footer-attributes.ts | 49 +- src/file/footer/footer.ts | 34 +- src/file/footer/index.ts | 5 + src/file/footnotes-wrapper.ts | 23 + .../footnotes/footnote/footnote-attributes.ts | 18 + src/file/footnotes/footnote/footnote.ts | 19 + src/file/footnotes/footnote/index.ts | 10 + .../run/continuation-seperator-run.ts | 18 + .../footnote/run/continuation-seperator.ts | 23 + .../footnotes/footnote/run/footnote-ref.ts | 24 + src/file/footnotes/footnote/run/index.ts | 10 + .../footnotes/footnote/run/reference-run.ts | 57 +++ .../footnotes/footnote/run/seperator-run.ts | 17 + src/file/footnotes/footnote/run/seperator.ts | 23 + src/file/footnotes/footnotes-attributes.ts | 34 ++ src/file/footnotes/footnotes.ts | 58 +++ src/file/footnotes/index.ts | 11 + src/file/header-wrapper.ts | 35 ++ src/file/header.ts | 47 ++ src/file/header/header-attributes.ts | 60 ++- src/file/header/header.ts | 31 +- src/file/header/index.ts | 5 + src/file/index.ts | 12 + src/file/media/data.ts | 38 +- src/file/media/index.ts | 5 + src/file/media/media.ts | 35 +- src/file/numbering/abstract-numbering.ts | 84 ++- src/file/numbering/index.ts | 5 + src/file/numbering/level.ts | 356 +++++++++---- src/file/numbering/multi-level-type.ts | 60 ++- src/file/numbering/num.ts | 145 +++++- src/file/numbering/numbering.ts | 81 +++ src/file/paragraph/formatting/alignment.ts | 20 + src/file/paragraph/formatting/border.ts | 55 ++ src/file/paragraph/formatting/break.ts | 37 +- src/file/paragraph/formatting/index.ts | 5 + src/file/paragraph/formatting/spacing.ts | 40 ++ src/file/paragraph/formatting/style.ts | 24 + src/file/paragraph/formatting/tab-stop.ts | 39 ++ .../paragraph/formatting/unordered-list.ts | 47 ++ src/file/paragraph/frame/frame-properties.ts | 223 +++++++- src/file/paragraph/frame/index.ts | 5 + src/file/paragraph/index.ts | 5 + .../paragraph/links/bookmark-attributes.ts | 65 +++ src/file/paragraph/links/bookmark.ts | 71 ++- .../paragraph/links/hyperlink-attributes.ts | 35 ++ src/file/paragraph/links/hyperlink.ts | 102 +++- src/file/paragraph/links/index.ts | 5 + src/file/paragraph/links/numbered-item-ref.ts | 28 +- src/file/paragraph/links/outline-level.ts | 34 +- .../links/pageref-field-instruction.ts | 31 ++ src/file/paragraph/links/pageref.ts | 38 +- src/file/paragraph/math/bar/index.ts | 5 + src/file/paragraph/math/bar/math-bar-pos.ts | 33 +- .../paragraph/math/bar/math-bar-properties.ts | 28 +- src/file/paragraph/math/brackets/index.ts | 5 + .../math/brackets/math-beginning-character.ts | 33 +- .../math/brackets/math-bracket-properties.ts | 45 +- .../math/brackets/math-ending-char.ts | 33 +- src/file/paragraph/math/fraction/index.ts | 5 + src/file/paragraph/math/function/index.ts | 5 + .../math/function/math-function-name.ts | 31 +- .../math/function/math-function-properties.ts | 29 +- src/file/paragraph/math/index.ts | 5 + src/file/paragraph/math/n-ary/index.ts | 5 + .../math/n-ary/math-accent-character.ts | 33 +- .../math/n-ary/math-limit-location.ts | 34 +- .../paragraph/math/n-ary/math-limit-lower.ts | 45 +- .../paragraph/math/n-ary/math-limit-upper.ts | 45 +- src/file/paragraph/math/n-ary/math-limit.ts | 31 +- .../math/n-ary/math-n-ary-properties.ts | 39 +- .../math/n-ary/math-sub-script-hide.ts | 25 +- .../paragraph/math/n-ary/math-sub-script.ts | 33 +- .../math/n-ary/math-super-script-hide.ts | 25 +- .../paragraph/math/n-ary/math-super-script.ts | 33 +- src/file/paragraph/math/radical/index.ts | 5 + .../math/radical/math-degree-hide.ts | 30 +- .../paragraph/math/radical/math-degree.ts | 31 +- .../math/radical/math-radical-properties.ts | 30 +- src/file/paragraph/math/script/index.ts | 5 + .../math/script/pre-sub-super-script/index.ts | 5 + ...re-sub-super-script-function-properties.ts | 26 +- .../math-pre-sub-super-script-function.ts | 49 +- .../paragraph/math/script/sub-script/index.ts | 5 + .../math-sub-script-function-properties.ts | 26 +- .../math/script/sub-super-script/index.ts | 5 + ...th-sub-super-script-function-properties.ts | 27 +- .../math/script/super-script/index.ts | 5 + .../math-super-script-function-properties.ts | 26 +- src/file/paragraph/properties.ts | 124 +++++ src/file/paragraph/run/break.ts | 83 ++- src/file/paragraph/run/comment-run.ts | 169 ++++++ src/file/paragraph/run/emphasis-mark.ts | 69 +++ src/file/paragraph/run/empty-children.ts | 136 ++++- src/file/paragraph/run/field.ts | 91 ++++ src/file/paragraph/run/formatting.ts | 122 ++++- src/file/paragraph/run/index.ts | 5 + src/file/paragraph/run/language.ts | 61 ++- src/file/paragraph/run/page-number.ts | 43 ++ src/file/paragraph/run/positional-tab.ts | 134 ++++- src/file/paragraph/run/run-fonts.ts | 66 +++ src/file/paragraph/run/script.ts | 57 +++ .../run/sequential-identifier-instruction.ts | 28 +- .../paragraph/run/sequential-identifier.ts | 40 ++ src/file/paragraph/run/simple-field.ts | 60 ++- src/file/paragraph/run/text-attributes.ts | 21 + src/file/paragraph/run/underline.ts | 91 ++++ src/file/relationships/attributes.ts | 13 + src/file/relationships/index.ts | 5 + .../relationship/relationship-attributes.ts | 18 + .../relationship/relationship.ts | 27 + src/file/relationships/relationships.ts | 23 + .../compatibility-setting.ts | 52 +- src/file/settings/compatibility.ts | 59 ++- src/file/settings/index.ts | 5 + src/file/settings/settings.ts | 43 ++ src/file/shading/index.ts | 5 + src/file/shared/index.ts | 5 + src/file/shared/number-format.ts | 109 ++-- src/file/shared/space-type.ts | 23 + src/file/styles/defaults/document-defaults.ts | 47 ++ src/file/styles/defaults/index.ts | 7 + .../styles/defaults/paragraph-properties.ts | 25 + src/file/styles/defaults/run-properties.ts | 26 + src/file/styles/external-styles-factory.ts | 51 +- src/file/styles/factory.ts | 63 +++ src/file/styles/index.ts | 5 + src/file/styles/latent-styles/exceptions.ts | 49 ++ src/file/styles/latent-styles/index.ts | 7 + .../styles/latent-styles/latent-styles.ts | 42 ++ src/file/styles/sample/default-style.ts | 39 ++ src/file/styles/sample/index.ts | 5 + src/file/styles/style/character-style.ts | 55 ++ src/file/styles/style/components.ts | 52 +- src/file/styles/style/default-styles.ts | 105 ++++ src/file/styles/style/index.ts | 9 + src/file/styles/style/paragraph-style.ts | 64 +++ src/file/styles/style/style.ts | 93 ++++ src/file/styles/styles.ts | 32 +- .../table-of-contents/field-instruction.ts | 38 +- src/file/table-of-contents/index.ts | 10 + src/file/table-of-contents/sdt-content.ts | 32 ++ src/file/table-of-contents/sdt-properties.ts | 50 +- .../table-of-contents-properties.ts | 31 +- src/file/table/index.ts | 5 + src/file/table/table-cell-spacing.ts | 62 ++- src/file/table/table-cell/index.ts | 5 + .../table/table-cell/table-cell-components.ts | 163 +++++- .../table/table-cell/table-cell-properties.ts | 54 +- src/file/table/table-properties/index.ts | 5 + .../table-properties/table-cell-margin.ts | 80 ++- .../table-float-properties.ts | 87 +++- src/file/table/table-row/index.ts | 5 + src/file/table/table-row/table-row-height.ts | 65 ++- .../table/table-row/table-row-properties.ts | 18 + src/file/table/table-row/table-row.ts | 7 + src/file/textbox/index.ts | 5 + src/file/textbox/pict-element/pict-element.ts | 48 ++ src/file/textbox/shape/shape.ts | 87 +++- .../textbox/texbox-content/textbox-content.ts | 31 ++ src/file/textbox/textbox.ts | 54 +- src/file/textbox/types.ts | 17 + src/file/textbox/vml-textbox/vml-texbox.ts | 62 ++- src/file/track-revision/index.ts | 10 + .../deleted-page-number.ts | 93 ++++ .../deleted-text-run.ts | 71 +++ .../track-revision-components/deleted-text.ts | 35 ++ .../inserted-text-run.ts | 53 ++ src/file/track-revision/track-revision.ts | 39 +- src/file/vertical-align/index.ts | 5 + src/file/xml-components/attributes.ts | 48 +- src/file/xml-components/base.ts | 57 +++ src/file/xml-components/default-attributes.ts | 86 ++++ .../xml-components/imported-xml-component.ts | 95 +++- src/file/xml-components/index.ts | 8 + .../initializable-xml-component.ts | 38 ++ src/file/xml-components/simple-elements.ts | 258 ++++++++-- src/file/xml-components/xml-component.ts | 125 ++++- src/file/xml-components/xmlable-object.ts | 29 ++ src/index.ts | 34 ++ src/patcher/content-types-manager.ts | 22 + src/patcher/from-docx.ts | 101 ++++ src/patcher/index.ts | 5 + src/patcher/paragraph-split-inject.ts | 42 ++ src/patcher/paragraph-token-replacer.ts | 34 ++ src/patcher/patch-detector.ts | 42 +- src/patcher/relationship-manager.ts | 49 ++ src/patcher/replacer.ts | 25 + src/patcher/run-renderer.ts | 50 ++ src/patcher/traverser.ts | 45 ++ src/patcher/util.ts | 68 +++ src/tests/utility.ts | 14 + src/util/convenience-functions.ts | 149 +++++- src/util/index.ts | 8 + src/util/output-type.ts | 50 +- src/util/types.ts | 34 +- src/util/values.ts | 484 +++++++++++++----- 339 files changed, 15680 insertions(+), 1343 deletions(-) create mode 100644 .github/copilot-instructions.md create mode 100644 CLAUDE.md create mode 100644 docs/quickstart.md create mode 100644 docs/troubleshooting.md create mode 100644 docs/usage/bookmarks.md create mode 100644 docs/usage/checkboxes.md create mode 100644 docs/usage/columns.md create mode 100644 docs/usage/fonts.md create mode 100644 docs/usage/line-numbers.md create mode 100644 docs/usage/page-layout.md create mode 100644 docs/usage/templates.md diff --git a/.cspell.json b/.cspell.json index 207be63bb5..a84d7bd6b0 100644 --- a/.cspell.json +++ b/.cspell.json @@ -4,7 +4,13 @@ "version": "0.2", // language - current active spelling language "language": "en_US", - "dictionaries": ["en_US", "typescript", "softwareTerms", "fonts", "npm"], + "dictionaries": [ + "en_US", + "typescript", + "softwareTerms", + "fonts", + "npm" + ], // words - list of words to be always considered correct "words": [ "Abjad", @@ -14,6 +20,7 @@ "chosung", "clippy", "datas", + "DCMI", "dcmitype", "dcterms", "docsify", @@ -55,19 +62,28 @@ "/[^\\s]{40,}/", "//", "/[A-Z_]+ = \".+\"/", + "/[a-zA-Z0-9]+:[a-zA-Z0-9]+/gi", "/XmlAttributeComponent<{[^}]+}>/g", "/xmlKeys = {[^}]+}/g", "/\\.to\\.deep\\.equal\\({[^)]+}\\)/g", "\\.to\\.include\\.members\\(\\[[^\\]]+]\\)", "/new [a-zA-Z]+\\({[^£]+}\\)/g", "//", "/ skill.name).join(", ") + ".")], }); } - // tslint:disable-next-line:no-any public createAchievementsList(achievements: any[]): Paragraph[] { return achievements.map( (achievement) => @@ -341,7 +336,6 @@ class DocumentCreator { return text.split("\n\n"); } - // tslint:disable-next-line:no-any public createPositionDateText(startDate: any, endDate: any, isCurrent: boolean): string { const startDateText = this.getMonthFromInt(startDate.month) + ". " + startDate.year; const endDateText = isCurrent ? "Present" : `${this.getMonthFromInt(endDate.month)}. ${endDate.year}`; diff --git a/docs/README.md b/docs/README.md index fcb0c05978..1ff6f987cf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,4 +1,26 @@ -# Welcome +# Welcome to docx + +## What is docx? + +**docx** is a TypeScript/JavaScript library for generating Word documents (.docx files) programmatically. It provides a declarative API that works seamlessly in both Node.js and browser environments. + +## Why docx? + +- **Declarative API** - Define what you want (objects/config), not how to build it step-by-step +- **TypeScript First** - Full type definitions with IntelliSense support +- **Universal** - Works in Node.js, browsers, and serverless environments +- **No Dependencies** - Zero external runtime dependencies +- **Full Featured** - Tables, images, headers, footers, styles, and more + +## Quick Navigation + +| I want to... | Go to... | +| ------------------------- | --------------------------------------------------------------- | +| Get started quickly | [Quickstart Guide](quickstart.md) | +| Learn a specific feature | [Usage Guides](#usage-guides) | +| See working examples | [Demo Files](https://github.com/dolanmiu/docx/tree/master/demo) | +| Browse the API | [API Documentation](https://docx.js.org/api/) | +| Modify existing documents | [Patcher](usage/patcher.md) | ## Installation @@ -15,7 +37,7 @@ const docx = require("docx"); ```ts import * as docx from "docx"; // or -import { ... } from "docx"; +import { Document, Packer, Paragraph, TextRun } from "docx"; ``` ## Basic Usage @@ -24,22 +46,15 @@ import { ... } from "docx"; import * as fs from "fs"; import { Document, Packer, Paragraph, TextRun } from "docx"; -// Documents contain sections, you can have multiple sections per document, go here to learn more about sections -// This simple example will only contain one section const doc = new Document({ sections: [ { - properties: {}, children: [ new Paragraph({ children: [ new TextRun("Hello World"), new TextRun({ - text: "Foo Bar", - bold: true, - }), - new TextRun({ - text: "\tGithub is the best", + text: " - Bold text", bold: true, }), ], @@ -49,12 +64,9 @@ const doc = new Document({ ], }); -// Used to export the file into a .docx file Packer.toBuffer(doc).then((buffer) => { fs.writeFileSync("My Document.docx", buffer); }); - -// Done! A file called 'My Document.docx' will be in your file system. ```

diff --git a/docs/_coverpage.md b/docs/_coverpage.md index 6c479e32a7..5709c6fbe0 100644 --- a/docs/_coverpage.md +++ b/docs/_coverpage.md @@ -2,9 +2,9 @@ > Easily generate and modify .docx files with JS/TS. Works for Node and on the Browser. :100: -- Simple, declarative API -- 80+ usage examples -- Battle tested, mature, 100% coverage (yes, every line is tested) +- Simple, declarative API +- 80+ usage examples +- Battle tested, mature, 100% coverage (yes, every line is tested) [GitHub](https://github.com/dolanmiu/docx) [Get Started](#Welcome) diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 048b62397c..922abcf05c 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -1,49 +1,60 @@ -- [Getting Started](/) +- Getting Started + - [Home](/) + - [Quickstart Guide](quickstart.md) -- Examples +- Examples + - [Demos](https://github.com/dolanmiu/docx/tree/master/demo) - - [Demos](https://github.com/dolanmiu/docx/tree/master/demo) +- API + - [Documentation](https://docx.js.org/api/) -- API +- Core Concepts + - [Document](usage/document.md) + - [Sections](usage/sections.md) + - [Convenience Functions](usage/convenience-functions.md) - - [Documentation](https://docx.js.org/api/) +- Content Elements + - [Paragraph](usage/paragraph.md) + - [Text Frames](usage/text-frames.md) + - [Symbols](usage/symbols.md) + - [Text](usage/text.md) + - [Images](usage/images.md) + - [Tables](usage/tables.md) + - [Bullet Points](usage/bullet-points.md) + - [Numbering](usage/numbering.md) + - [Hyperlinks](usage/hyperlinks.md) + - [Bookmarks](usage/bookmarks.md) + - [Checkboxes](usage/checkboxes.md) + - [Text Box](usage/text-box.md) -- Usage +- Page Layout + - [Page Layout](usage/page-layout.md) + - [Headers & Footers](usage/headers-and-footers.md) + - [Page Numbers](usage/page-numbers.md) + - [Columns](usage/columns.md) + - [Line Numbers](usage/line-numbers.md) - - [Document](usage/document.md) - - [Sections](usage/sections.md) - - [Paragraph](usage/paragraph.md) - - [Text Frames](usage/text-frames.md) - - [Symbols](usage/symbols.md) - - [Text](usage/text.md) - - [Images](usage/images.md) - - [Headers & Footers](usage/headers-and-footers.md) - - [Bullet Points](usage/bullet-points.md) - - [Hyperlinks](usage/hyperlinks.md) - - [Numbering](usage/numbering.md) - - [Tables](usage/tables.md) - - [Tabs](usage/tabs.md) - - [Table of Contents](usage/table-of-contents.md) - - [Page Numbers](usage/page-numbers.md) - - [Change Tracking](usage/change-tracking.md) - - [Math](usage/math.md) - - [Comments](usage/comments.md) - - [Footnotes](usage/footnotes.md) - - [Fields](usage/fields.md) - - Styling - - [Styling with JS](usage/styling-with-js.md) - - [Styling with XML](usage/styling-with-xml.md) +- Advanced Features + - [Table of Contents](usage/table-of-contents.md) + - [Tabs](usage/tabs.md) + - [Change Tracking](usage/change-tracking.md) + - [Math](usage/math.md) + - [Comments](usage/comments.md) + - [Footnotes](usage/footnotes.md) + - [Fields](usage/fields.md) + - [Fonts](usage/fonts.md) + - Styling + - [Styling with JS](usage/styling-with-js.md) + - [Styling with XML](usage/styling-with-xml.md) -- Exporting +- Exporting + - [Packers](usage/packers.md) - - [Packers](usage/packers.md) +- Templates & Patching + - [Patcher](usage/patcher.md) + - [Templates](usage/templates.md) -- Modifying Existing Documents +- Practical Guides + - [Troubleshooting](troubleshooting.md) - - [Patcher](usage/patcher.md) - -- Utility - - - [Convenience functions](usage/convenience-functions.md) - -- [Contribution Guidelines](contribution-guidelines.md) +- [Contribution Guidelines](contribution-guidelines.md) diff --git a/docs/contribution-guidelines.md b/docs/contribution-guidelines.md index dc61cf370a..a9cb2588f6 100644 --- a/docs/contribution-guidelines.md +++ b/docs/contribution-guidelines.md @@ -6,9 +6,7 @@ // http://officeopenxml.com/WPdocument.php ``` - - - It can be a link to `officeopenxml.com` or `datypic.com` etc. + It can be a link to `officeopenxml.com` etc. It could also be a reference to the official ECMA-376 standard: https://www.ecma-international.org/publications-and-standards/standards/ecma-376/ - Include a portion of the schema as a comment for cross reference. For example: @@ -113,10 +111,10 @@ Using `type` aliases in TypeScript offers several advantages over `interfaces`: - **Flexibility with Complex Types**: `type` supports defining unions, intersections, and other complex type constructs that `interfaces` cannot handle. For example: - ```typescript - type StringOrNumber = string | number; - type Combined = TypeA & TypeB; - ``` + ```typescript + type StringOrNumber = string | number; + type Combined = TypeA & TypeB; + ``` - **Support for Primitive Types**: `type` can alias primitive types (e.g., `type ID = string`), while `interfaces` are limited to object shapes. - **Tuple and Array Types**: `type` allows defining tuples and specific array types easily (e.g., `type Point = [number, number]`), which `interfaces` cannot represent. diff --git a/docs/index.html b/docs/index.html index c1c0b79fc2..5fe1e682fa 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ - + diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000000..abe3c1b04e --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,191 @@ +# Quickstart Guide + +Get up and running with docx in under 5 minutes. + +**In this guide:** + +- Install docx +- Create your first document +- Add text, tables, and images +- Export in multiple formats + +## Installation + +```terminal +npm install --save docx +``` + +## Your First Document + +Create a "Hello World" document in just a few lines: + +```ts +import { Document, Packer, Paragraph, TextRun } from "docx"; +import * as fs from "fs"; + +const doc = new Document({ + sections: [ + { + // Documents are organized into sections + children: [ + new Paragraph({ + children: [new TextRun("Hello World!")], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); +``` + +That's it! Run this code to create your first Word document. + +## Adding Common Elements + +### Bold and Styled Text + +```ts +new Paragraph({ + children: [ + new TextRun("Normal text, "), + new TextRun({ + text: "bold text, ", + bold: true, + }), + new TextRun({ + text: "italic text", + italics: true, + }), + ], +}); +``` + +See the [Text guide](usage/text.md) for all formatting options. + +### Headings + +```ts +import { HeadingLevel } from "docx"; + +new Paragraph({ + text: "My Heading", + heading: HeadingLevel.HEADING_1, +}); +``` + +### Bullet Points + +```ts +[ + new Paragraph({ + text: "First item", + bullet: { level: 0 }, + }), + new Paragraph({ + text: "Second item", + bullet: { level: 0 }, + }), + new Paragraph({ + text: "Nested item", + bullet: { level: 1 }, + }), +]; +``` + +See the [Bullet Points guide](usage/bullet-points.md) for more options. + +### Tables + +```ts +import { Table, TableRow, TableCell } from "docx"; + +new Table({ + rows: [ + new TableRow({ + children: [new TableCell({ children: [new Paragraph("Cell 1")] }), new TableCell({ children: [new Paragraph("Cell 2")] })], + }), + ], +}); +``` + +See the [Tables guide](usage/tables.md) for advanced table features. + +### Images + +```ts +import { ImageRun } from "docx"; + +new Paragraph({ + children: [ + new ImageRun({ + type: "png", + data: fs.readFileSync("./image.png"), + transformation: { + width: 200, + height: 200, + }, + }), + ], +}); +``` + +See the [Images guide](usage/images.md) for positioning and wrapping options. + +## Export Options + +### Node.js - Save to File + +```ts +import * as fs from "fs"; + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("document.docx", buffer); +}); +``` + +### Node.js - Stream + +```ts +import * as fs from "fs"; + +Packer.toStream(doc).then((stream) => { + stream.pipe(fs.createWriteStream("document.docx")); +}); +``` + +### Browser - Download + +```ts +import { saveAs } from "file-saver"; + +Packer.toBlob(doc).then((blob) => { + saveAs(blob, "document.docx"); +}); +``` + +### Base64 String + +```ts +Packer.toBase64String(doc).then((base64) => { + console.log(base64); +}); +``` + +See the [Packers guide](usage/packers.md) for all export options. + +## Next Steps + +Now that you've created your first document, explore these guides: + +- **[Document](usage/document.md)** - Document properties and settings +- **[Sections](usage/sections.md)** - Page layouts and breaks +- **[Paragraph](usage/paragraph.md)** - Text formatting and alignment +- **[Tables](usage/tables.md)** - Complex table layouts +- **[Images](usage/images.md)** - Image positioning and wrapping +- **[Headers & Footers](usage/headers-and-footers.md)** - Page headers and footers +- **[Styling](usage/styling-with-js.md)** - Reusable styles + +?> Check out the [demo folder](https://github.com/dolanmiu/docx/tree/master/demo) for 90+ working examples covering every feature. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000000..83d3831a36 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,415 @@ +# Troubleshooting + +This guide covers common issues and their solutions when working with docx. + +## Quick Index + +| Symptom | Go to | +| ------------------------ | ------------------------------------------ | +| File corrupt/won't open | [Document Won't Open](#document-wont-open) | +| Images appear blank | [Images Not Showing](#images-not-showing) | +| Buffer not defined error | [Browser Issues](#browser-issues) | +| Table cells misaligned | [Table Issues](#table-issues) | +| Styles not applying | [Styling Issues](#styling-issues) | +| Memory errors | [Memory Issues](#memory-issues) | + +## Document Won't Open + +### "The file is corrupt and cannot be opened" + +**Cause:** The document was not written correctly, often due to not waiting for the document to finish generating. + +**Solutions:** + +1. Ensure you're using `await` or `.then()` with `Packer` methods: + +```ts +// Correct - using await +const buffer = await Packer.toBuffer(doc); +fs.writeFileSync("document.docx", buffer); + +// Correct - using .then() +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("document.docx", buffer); +}); + +// Wrong - missing await +const buffer = Packer.toBuffer(doc); // Returns a Promise, not a buffer! +fs.writeFileSync("document.docx", buffer); +``` + +2. In Express.js, ensure the response completes: + +```ts +app.get("/download", async (req, res) => { + const doc = new Document({ + /* ... */ + }); + const buffer = await Packer.toBuffer(doc); + + res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + res.setHeader("Content-Disposition", "attachment; filename=document.docx"); + res.send(buffer); +}); +``` + +### "We're sorry. We can't open document.docx" + +**Cause:** Invalid XML structure in the document. + +**Solutions:** + +1. Check for invalid characters in text content: + +```ts +// Remove control characters +const cleanText = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, ""); +new TextRun(cleanText); +``` + +2. Ensure all required properties are provided: + +```ts +// ImageRun requires type, data, and transformation +new ImageRun({ + type: "png", + data: buffer, + transformation: { width: 100, height: 100 }, // Required! +}); +``` + +## Images Not Showing + +### Image appears as blank or broken + +**Cause:** Incorrect image data or type. + +**Solutions:** + +1. Verify the image type matches the file: + +```ts +// Match type to actual file format +new ImageRun({ + type: "png", // Must match the actual image format + data: fs.readFileSync("image.png"), + transformation: { width: 100, height: 100 }, +}); +``` + +2. In browsers, ensure proper data conversion: + +```ts +// Convert fetch response to ArrayBuffer +const response = await fetch(imageUrl); +const arrayBuffer = await response.arrayBuffer(); +const buffer = Buffer.from(arrayBuffer); + +new ImageRun({ + type: "png", + data: buffer, + transformation: { width: 100, height: 100 }, +}); +``` + +3. Check image dimensions are specified: + +```ts +// Both width and height are required +transformation: { + width: 100, // Required + height: 100, // Required +} +``` + +## Browser Issues + +### "Buffer is not defined" + +**Cause:** Node.js `Buffer` is not available in browsers. + +**Solutions:** + +1. Use a polyfill (a library that provides missing browser functionality) like `buffer`: + +```ts +import { Buffer } from "buffer"; +window.Buffer = Buffer; +``` + +2. Or configure your bundler (Webpack/Vite) to include polyfills + +3. For Vite, use `vite-plugin-node-polyfills` + +### Blob download not working + +**Cause:** Incorrect blob handling. + +**Solution:** + +```ts +import { saveAs } from "file-saver"; + +Packer.toBlob(doc).then((blob) => { + saveAs(blob, "document.docx"); +}); +``` + +## Table Issues + +### Table cells not aligning + +**Cause:** Missing or inconsistent column widths. + +**Solution:** + +```ts +new Table({ + width: { size: 100, type: WidthType.PERCENTAGE }, + rows: [ + new TableRow({ + children: [ + new TableCell({ + width: { size: 50, type: WidthType.PERCENTAGE }, + children: [new Paragraph("Cell 1")], + }), + new TableCell({ + width: { size: 50, type: WidthType.PERCENTAGE }, + children: [new Paragraph("Cell 2")], + }), + ], + }), + ], +}); +``` + +### Merged cells not working + +**Cause:** Incorrect merge configuration. + +**Solution:** + +```ts +// Horizontal merge +new TableCell({ + columnSpan: 2, // Span 2 columns + children: [new Paragraph("Merged horizontally")], +}), + +// Vertical merge +new TableCell({ + rowSpan: 2, // Span 2 rows + children: [new Paragraph("Merged vertically")], +}), +``` + +## Styling Issues + +### Styles not applying + +**Cause:** Style not defined in the document styles. + +**Solution:** + +```ts +const doc = new Document({ + styles: { + paragraphStyles: [ + { + id: "MyStyle", + name: "My Custom Style", + basedOn: "Normal", + next: "Normal", + run: { + bold: true, + color: "FF0000", + }, + }, + ], + }, + sections: [ + { + children: [ + new Paragraph({ + text: "Styled text", + style: "MyStyle", // Reference by id + }), + ], + }, + ], +}); +``` + +### Font not displaying + +**Cause:** Font not available on the target system. + +**Solution:** Embed the font: + +```ts +import { CharacterSet, Document } from "docx"; + +const doc = new Document({ + fonts: [ + { + name: "CustomFont", + data: fs.readFileSync("./font.ttf"), + characterSet: CharacterSet.ANSI, + }, + ], + // ... +}); +``` + +## Headers and Footers + +### Header/footer not appearing on all pages + +**Cause:** Multiple sections with different headers. + +**Solution:** + +```ts +// Apply headers to each section +sections: [ + { + headers: { default: myHeader }, + footers: { default: myFooter }, + children: [ + /* ... */ + ], + }, + { + // New section inherits headers unless overridden + headers: { default: myHeader }, // Repeat if needed + footers: { default: myFooter }, + children: [ + /* ... */ + ], + }, +]; +``` + +### Different first page header not working + +**Cause:** Missing `titlePage` property. + +**Solution:** + +```ts +sections: [ + { + properties: { + titlePage: true, // Required for different first page + }, + headers: { + default: normalHeader, + first: firstPageHeader, // Only shows with titlePage: true + }, + children: [ + /* ... */ + ], + }, +]; +``` + +## Page Numbers + +### Page numbers not updating + +**Cause:** Page numbers are fields that update when the document opens. + +**Note:** This is expected behavior. Page numbers will update when opened in Word. + +### Page X of Y not working + +**Solution:** + +```ts +import { PageNumber, NumberFormat } from "docx"; + +new Paragraph({ + children: [ + new TextRun("Page "), + new TextRun({ + children: [PageNumber.CURRENT], + }), + new TextRun(" of "), + new TextRun({ + children: [PageNumber.TOTAL_PAGES], + }), + ], +}); +``` + +## Table of Contents + +### TOC shows "Update this table" + +**Cause:** TOC fields need updating in Word. + +**Solution:** + +1. Set `updateFields: true` in document features: + +```ts +const doc = new Document({ + features: { + updateFields: true, + }, + // ... +}); +``` + +2. When opening in Word, right-click the TOC and select "Update Field" + +## Memory Issues + +### "JavaScript heap out of memory" + +**Cause:** Processing very large documents or many images. + +**Solutions:** + +1. Increase Node.js memory: + +```bash +node --max-old-space-size=4096 script.js +``` + +2. Process images before embedding: + +```ts +// Resize images before adding to document +const sharp = require("sharp"); +const resized = await sharp(imagePath).resize(800, 600).toBuffer(); +``` + +3. Generate documents in batches + +## TypeScript Errors + +### "Property does not exist on type" + +**Cause:** Using incorrect property names or types. + +**Solution:** Check the API documentation or TypeScript definitions: + +```ts +// Use IntelliSense to see available options +new Paragraph({ + // Ctrl+Space in VS Code to see options +}); +``` + +## Getting Help + +If you can't find a solution here: + +1. Check the [Demo files](https://github.com/dolanmiu/docx/tree/master/demo) for working examples +2. Search [GitHub Issues](https://github.com/dolanmiu/docx/issues) for similar problems +3. Open a new issue with: + - docx version number + - Node.js version + - Minimal reproducible code example + - Expected vs actual behavior diff --git a/docs/usage/bookmarks.md b/docs/usage/bookmarks.md new file mode 100644 index 0000000000..4d9aff4da2 --- /dev/null +++ b/docs/usage/bookmarks.md @@ -0,0 +1,188 @@ +# Bookmarks + +!> Bookmarks require an understanding of [Paragraphs](usage/paragraph.md) and [Hyperlinks](usage/hyperlinks.md). + +Bookmarks allow you to create anchors within a document that can be referenced by internal hyperlinks, enabling navigation within the same document. + +## Creating Bookmarks + +A bookmark is an anchor point in your document with a unique identifier. Create one using the `Bookmark` component: + +```ts +import { Bookmark, Paragraph, TextRun, HeadingLevel } from "docx"; + +const bookmarkedHeading = new Paragraph({ + heading: HeadingLevel.HEADING_1, + children: [ + new Bookmark({ + id: "chapter1", + children: [new TextRun("Chapter 1: Introduction")], + }), + ], +}); +``` + +### Bookmark Options + +| Property | Type | Notes | Description | +| -------- | ----------- | -------- | ---------------------------------- | +| id | `string` | Required | Unique identifier for the anchor | +| children | `TextRun[]` | Required | Content to display at the bookmark | + +## Internal Hyperlinks + +Use `InternalHyperlink` to create clickable links that navigate to bookmarks: + +```ts +import { InternalHyperlink, Paragraph, TextRun } from "docx"; + +const linkToChapter = new Paragraph({ + children: [ + new InternalHyperlink({ + children: [ + new TextRun({ + text: "Go to Chapter 1", + style: "Hyperlink", + }), + ], + anchor: "chapter1", + }), + ], +}); +``` + +?> Use `style: "Hyperlink"` on your TextRun to apply the default hyperlink styling (blue text, underlined). + +## Page References + +Get the page number where a bookmark appears using `PageReference`: + +```ts +import { PageReference, Paragraph, TextRun } from "docx"; + +const pageRef = new Paragraph({ + children: [new TextRun("See Chapter 1 on page "), new PageReference("chapter1")], +}); +``` + +This creates dynamic text like "See Chapter 1 on page 5" that updates automatically. + +## Complete Example + +Here's a full example with a table of contents linking to bookmarked sections: + +```ts +import { Bookmark, Document, HeadingLevel, InternalHyperlink, Packer, PageBreak, PageReference, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + // Table of Contents + new Paragraph({ + text: "Table of Contents", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + children: [ + new InternalHyperlink({ + children: [new TextRun({ text: "Chapter 1", style: "Hyperlink" })], + anchor: "chapter1", + }), + new TextRun(" - page "), + new PageReference("chapter1"), + ], + }), + new Paragraph({ + children: [ + new InternalHyperlink({ + children: [new TextRun({ text: "Chapter 2", style: "Hyperlink" })], + anchor: "chapter2", + }), + new TextRun(" - page "), + new PageReference("chapter2"), + ], + }), + + // Page break to Chapter 1 + new Paragraph({ children: [new PageBreak()] }), + + // Chapter 1 + new Paragraph({ + heading: HeadingLevel.HEADING_1, + children: [ + new Bookmark({ + id: "chapter1", + children: [new TextRun("Chapter 1: Getting Started")], + }), + ], + }), + new Paragraph("Content of chapter 1..."), + + // Page break to Chapter 2 + new Paragraph({ children: [new PageBreak()] }), + + // Chapter 2 + new Paragraph({ + heading: HeadingLevel.HEADING_1, + children: [ + new Bookmark({ + id: "chapter2", + children: [new TextRun("Chapter 2: Advanced Topics")], + }), + ], + }), + new Paragraph("Content of chapter 2..."), + ], + }, + ], +}); +``` + +## Using in Headers and Footers + +Bookmarks and internal hyperlinks work in headers and footers too: + +```ts +import { Footer, InternalHyperlink, Paragraph, TextRun } from "docx"; + +const footer = new Footer({ + children: [ + new Paragraph({ + children: [ + new InternalHyperlink({ + children: [new TextRun({ text: "Back to Top", style: "Hyperlink" })], + anchor: "documentStart", + }), + ], + }), + ], +}); +``` + +## Styling Internal Hyperlinks + +You can apply custom formatting to internal hyperlinks: + +```ts +new InternalHyperlink({ + children: [ + new TextRun({ + text: "Bold ", + bold: true, + style: "Hyperlink", + }), + new TextRun({ + text: "Link", + style: "Hyperlink", + }), + ], + anchor: "myBookmark", +}); +``` + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/21-bookmarks.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/21-bookmarks.ts_ diff --git a/docs/usage/bullet-points.md b/docs/usage/bullet-points.md index a399367281..66026162c7 100644 --- a/docs/usage/bullet-points.md +++ b/docs/usage/bullet-points.md @@ -1,32 +1,218 @@ # Bullet Points -!> Bullet Points requires an understanding of [Paragraphs](usage/paragraph.md). -## Example +!> Bullet Points require an understanding of [Paragraphs](usage/paragraph.md). -To make a bullet point, simply make a paragraph into a bullet point: +## Basic Bullet Points + +Create bullet points by adding the `bullet` property to paragraphs: ```ts const doc = new Document({ - sections: [{ - children: [ - new Paragraph({ - text: "Bullet points", - bullet: { - level: 0 // How deep you want the bullet to be. Maximum level is 9 - } - }), - new Paragraph({ - text: "Are awesome", - bullet: { - level: 0 - } - }) - ], - }] + sections: [ + { + children: [ + new Paragraph({ + text: "First item", + bullet: { + level: 0, + }, + }), + new Paragraph({ + text: "Second item", + bullet: { + level: 0, + }, + }), + new Paragraph({ + text: "Third item", + bullet: { + level: 0, + }, + }), + ], + }, + ], }); ``` -### This will produce: +### Output: -- Bullet points -- Are awesome +- First item +- Second item +- Third item + +## Multi-Level Lists + +Create nested lists using different `level` values (0-9): + +```ts +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ + text: "Main item 1", + bullet: { level: 0 }, + }), + new Paragraph({ + text: "Sub-item 1.1", + bullet: { level: 1 }, + }), + new Paragraph({ + text: "Sub-item 1.2", + bullet: { level: 1 }, + }), + new Paragraph({ + text: "Deep item 1.2.1", + bullet: { level: 2 }, + }), + new Paragraph({ + text: "Main item 2", + bullet: { level: 0 }, + }), + ], + }, + ], +}); +``` + +### Output: + +- Main item 1 + - Sub-item 1.1 + - Sub-item 1.2 + - Deep item 1.2.1 +- Main item 2 + +## Bullet Options + +| Property | Type | Notes | Description | +| -------- | -------- | -------- | ----------------------- | +| level | `number` | Required | Indentation level (0-9) | + +## Programmatic List Generation + +Generate bullet lists from data: + +```ts +const items = ["Apple", "Banana", "Cherry", "Date"]; + +const doc = new Document({ + sections: [ + { + children: items.map( + (item) => + new Paragraph({ + text: item, + bullet: { level: 0 }, + }), + ), + }, + ], +}); +``` + +## Nested Data Structures + +Create hierarchical lists from nested data: + +```ts +interface MenuItem { + name: string; + children?: MenuItem[]; +} + +const menu: MenuItem[] = [ + { + name: "Fruits", + children: [{ name: "Apple" }, { name: "Orange" }], + }, + { + name: "Vegetables", + children: [{ name: "Carrot" }, { name: "Broccoli" }], + }, +]; + +function createBulletItems(items: MenuItem[], level: number = 0): Paragraph[] { + const paragraphs: Paragraph[] = []; + + for (const item of items) { + paragraphs.push( + new Paragraph({ + text: item.name, + bullet: { level }, + }), + ); + + if (item.children) { + paragraphs.push(...createBulletItems(item.children, level + 1)); + } + } + + return paragraphs; +} + +const doc = new Document({ + sections: [ + { + children: createBulletItems(menu), + }, + ], +}); +``` + +## Mixing Bullets with Other Content + +Combine bullet points with regular paragraphs: + +```ts +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ + text: "Shopping List", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph("Items to buy:"), + new Paragraph({ + text: "Milk", + bullet: { level: 0 }, + }), + new Paragraph({ + text: "Bread", + bullet: { level: 0 }, + }), + new Paragraph({ + text: "Eggs", + bullet: { level: 0 }, + }), + new Paragraph("Remember to check expiration dates!"), + ], + }, + ], +}); +``` + +## Styled Bullet Items + +Apply text formatting to bullet items: + +```ts +new Paragraph({ + bullet: { level: 0 }, + children: [new TextRun({ text: "Important: ", bold: true }), new TextRun("This item requires attention")], +}); +``` + +## Related Topics + +- **[Numbering](usage/numbering.md)** - For numbered lists with custom formats +- **[Paragraph](usage/paragraph.md)** - For paragraph formatting options +- **[Styling with JS](usage/styling-with-js.md)** - For custom bullet styles + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/3-numbering-and-bullet-points.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/3-numbering-and-bullet-points.ts_ diff --git a/docs/usage/change-tracking.md b/docs/usage/change-tracking.md index e9ea9cb75e..98e784d7ff 100644 --- a/docs/usage/change-tracking.md +++ b/docs/usage/change-tracking.md @@ -9,7 +9,7 @@ const paragraph = new Paragraph({ children: [ new TextRun("This is a simple demo "), new TextRun({ - text: "on how to " + text: "on how to ", }), new InsertedTextRun({ text: "mark a text as an insertion ", @@ -22,7 +22,7 @@ const paragraph = new Paragraph({ id: 1, author: "Firstname Lastname", date: "2020-10-06T09:00:00Z", - }) + }), ], }); ``` @@ -43,7 +43,7 @@ const paragraph = new Paragraph({ id: 0, author: "Firstname Lastname", date: "2020-10-06T09:00:00Z", - }) + }), ], }); ``` @@ -71,6 +71,6 @@ new TextRun({ author: "Firstname Lastname", date: "2020-10-06T09:05:00Z", bold: false, - } -}).break() -```` + }, +}).break(); +``` diff --git a/docs/usage/checkboxes.md b/docs/usage/checkboxes.md new file mode 100644 index 0000000000..c32b383c03 --- /dev/null +++ b/docs/usage/checkboxes.md @@ -0,0 +1,168 @@ +# Checkboxes + +!> Checkboxes require an understanding of [Paragraphs](usage/paragraph.md). + +Checkboxes allow you to add interactive checkbox controls to your Word documents. These are commonly used in forms, checklists, and surveys. + +?> These checkboxes are interactive in Word - users can click to toggle them on and off. + +## Basic Checkbox + +Create a simple checkbox: + +```ts +import { CheckBox, Document, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ + children: [new CheckBox(), new TextRun(" Unchecked item")], + }), + ], + }, + ], +}); +``` + +## Checked Checkbox + +Create a pre-checked checkbox: + +```ts +new Paragraph({ + children: [new CheckBox({ checked: true }), new TextRun(" Completed task")], +}); +``` + +## Custom Checkbox Symbols + +You can customize the symbols used for checked and unchecked states. This is useful for branding consistency, platform compatibility, or when the default symbols don't render correctly on certain systems: + +```ts +new CheckBox({ + checked: true, + checkedState: { + value: "2611", // Unicode ballot box with check + font: "MS Gothic", + }, + uncheckedState: { + value: "2610", // Unicode ballot box + font: "MS Gothic", + }, +}); +``` + +### Common Unicode Values + +| Symbol | Unicode | Description | +| -------- | ------- | --------------------- | +| ☐ | `2610` | Ballot Box | +| ☑ | `2611` | Ballot Box with Check | +| ☒ | `2612` | Ballot Box with X | +| ✓ | `2713` | Check Mark | +| ✗ | `2717` | Ballot X | + +## Checkbox Options + +| Property | Type | Notes | Description | +| -------------- | ------------- | -------- | ------------------------------------ | +| checked | `boolean` | Optional | Whether the checkbox is checked | +| checkedState | `SymbolState` | Optional | Symbol and font for checked state | +| uncheckedState | `SymbolState` | Optional | Symbol and font for unchecked state | +| alias | `string` | Optional | Accessibility label for the checkbox | + +### SymbolState Options + +| Property | Type | Notes | Description | +| -------- | -------- | -------- | -------------------------- | +| value | `string` | Required | Unicode hex value | +| font | `string` | Optional | Font to use for the symbol | + +## Accessibility + +Use the `alias` property to provide an accessibility label: + +```ts +new Paragraph({ + children: [ + new TextRun("Do you agree to the terms?"), + new TextRun({ break: 1 }), + new CheckBox({ + checked: false, + alias: "Terms agreement checkbox", + }), + new TextRun(" Yes, I agree"), + ], +}); +``` + +## Building a Checklist + +Create a complete checklist: + +```ts +import { CheckBox, Document, Paragraph, TextRun } from "docx"; + +const tasks = [ + { text: "Review documentation", done: true }, + { text: "Write unit tests", done: true }, + { text: "Deploy to production", done: false }, + { text: "Update README", done: false }, +]; + +const doc = new Document({ + sections: [ + { + children: tasks.map( + (task) => + new Paragraph({ + children: [new CheckBox({ checked: task.done }), new TextRun(` ${task.text}`)], + }), + ), + }, + ], +}); +``` + +## Form with Multiple Checkboxes + +```ts +import { CheckBox, Document, HeadingLevel, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ + text: "Survey Form", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + text: "Which features do you use?", + heading: HeadingLevel.HEADING_2, + }), + new Paragraph({ + children: [new CheckBox(), new TextRun(" Tables")], + }), + new Paragraph({ + children: [new CheckBox(), new TextRun(" Images")], + }), + new Paragraph({ + children: [new CheckBox(), new TextRun(" Headers/Footers")], + }), + new Paragraph({ + children: [new CheckBox(), new TextRun(" Styles")], + }), + ], + }, + ], +}); +``` + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/90-check-boxes.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/90-check-boxes.ts_ diff --git a/docs/usage/columns.md b/docs/usage/columns.md new file mode 100644 index 0000000000..8b558e76e4 --- /dev/null +++ b/docs/usage/columns.md @@ -0,0 +1,223 @@ +# Columns + +!> Columns require an understanding of [Sections](usage/sections.md). + +Create multi-column layouts like newspapers or newsletters by configuring columns in your section properties. + +## Basic Columns + +Create equal-width columns: + +```ts +import { Document, Paragraph } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + column: { + count: 2, + space: 708, // Space between columns (~0.5 inches in twips; 1440 twips = 1 inch) + }, + }, + children: [new Paragraph("This text will flow across two columns...")], + }, + ], +}); +``` + +## Column Options + +| Property | Type | Notes | Description | +| ---------- | ---------- | -------- | -------------------------------- | +| count | `number` | Required | Number of columns | +| space | `number` | Optional | Space between columns (twips) | +| separate | `boolean` | Optional | Draw a line between columns | +| equalWidth | `boolean` | Optional | Whether columns have equal width | +| children | `Column[]` | Optional | Individual column definitions | + +## Column Separator + +Add a vertical line between columns: + +```ts +properties: { + column: { + count: 2, + space: 708, + separate: true, // Adds a line between columns + }, +} +``` + +## Different Width Columns + +Create columns with custom widths: + +```ts +import { Column, Document, Paragraph } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + column: { + count: 2, + space: 720, + equalWidth: false, + children: [ + new Column({ width: 2880, space: 720 }), // Narrow column + new Column({ width: 5760 }), // Wide column + ], + }, + }, + children: [new Paragraph("Content flows through unequal columns...")], + }, + ], +}); +``` + +### Column Class Options + +| Property | Type | Notes | Description | +| -------- | -------- | -------- | ----------------------- | +| width | `number` | Required | Column width (twips) | +| space | `number` | Optional | Space after this column | + +## Column Breaks + +Force content to the next column using `ColumnBreak`: + +```ts +import { ColumnBreak, Document, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + column: { + count: 2, + space: 708, + }, + }, + children: [ + new Paragraph({ + children: [new TextRun("This text is in column 1."), new ColumnBreak(), new TextRun("This text is in column 2.")], + }), + ], + }, + ], +}); +``` + +## Three Columns + +```ts +properties: { + column: { + count: 3, + space: 708, + }, +} +``` + +## Mixing Column Layouts + +Use multiple sections to mix column layouts: + +```ts +import { Document, Paragraph, SectionType } from "docx"; + +const doc = new Document({ + sections: [ + // Single column section + { + children: [new Paragraph("This is a full-width introduction paragraph.")], + }, + // Two column section + { + properties: { + type: SectionType.CONTINUOUS, // Don't start new page + column: { + count: 2, + space: 708, + }, + }, + children: [new Paragraph("This content flows in two columns...")], + }, + // Back to single column + { + properties: { + type: SectionType.CONTINUOUS, + }, + children: [new Paragraph("This is a full-width conclusion.")], + }, + ], +}); +``` + +## Complete Example + +Newsletter-style layout with unequal columns: + +```ts +import { Column, ColumnBreak, Document, HeadingLevel, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + column: { + count: 2, + space: 720, // 0.5 inches between columns (1440 twips = 1 inch) + separate: true, + equalWidth: false, + children: [ + new Column({ width: 3600, space: 720 }), // Narrow column (~2.5 inches) + new Column({ width: 5040 }), // Wide column (~3.5 inches) + ], + }, + }, + children: [ + new Paragraph({ + text: "Newsletter Title", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + children: [ + new TextRun("First column content goes here. "), + new TextRun("It will flow naturally within the column width. "), + new TextRun("Add more content as needed."), + ], + }), + new Paragraph({ + children: [new ColumnBreak()], + }), + new Paragraph({ + children: [new TextRun("Second column content starts here. "), new TextRun("This appears in the right column.")], + }), + ], + }, + ], +}); +``` + +## Demos + +### Multiple Columns + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/44-multiple-columns.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/44-multiple-columns.ts_ + +### Column Break + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/67-column-break.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/67-column-break.ts_ + +### Different Width Columns + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/69-different-width-columns.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/69-different-width-columns.ts_ diff --git a/docs/usage/comments.md b/docs/usage/comments.md index d76a6bb3e1..f6ca1f16c6 100644 --- a/docs/usage/comments.md +++ b/docs/usage/comments.md @@ -1,17 +1,231 @@ # Comments -!> Comments requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md). +!> Comments require an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md). -## Intro +Comments allow you to add annotations to specific parts of your document, similar to the review feature in Microsoft Word. -To add comments in `docx`, a `comments` block is specified in the `Document`. This block defines all the comments in your document. Each comment has an `id`, which you then reference later. +## Overview -In the spot you want to add a comment, you simply add a `CommentRangeStart` and a `CommentRangeEnd` to specify where the comment starts and ends. +To add comments in `docx`: -Alternatively, you can use `CommentReference` to specify a comment at a specific singular point. +1. Define all comments in the `comments` block of the `Document` +2. Each comment has a unique `id` +3. Mark where comments appear using `CommentRangeStart`, `CommentRangeEnd`, and `CommentReference` -### Example +## Basic Comment -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/73-comments.ts ':include') +Add a comment to a range of text: + +```ts +import { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + comments: { + children: [ + new Comment({ + id: "0", + author: "John Smith", + date: new Date(), + children: [new Paragraph("This needs to be reviewed.")], + }), + ], + }, + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun("This is normal text. "), + new CommentRangeStart("0"), + new TextRun("This text has a comment."), + new CommentRangeEnd("0"), + new CommentReference("0"), + ], + }), + ], + }, + ], +}); +``` + +## Comment Options + +| Property | Type | Notes | Description | +| -------- | ------------- | -------- | ------------------- | +| id | `string` | Required | Unique identifier | +| author | `string` | Optional | Comment author name | +| date | `Date` | Optional | Comment timestamp | +| initials | `string` | Optional | Author initials | +| children | `Paragraph[]` | Required | Comment content | + +## Point Comment + +Add a comment at a specific point (not a range): + +```ts +new Paragraph({ + children: [ + new TextRun("Check this point"), + new CommentReference("0"), // Comment appears here + ], +}); +``` + +## Multiple Comments + +Add several comments to a document: + +```ts +const doc = new Document({ + comments: { + children: [ + new Comment({ + id: "0", + author: "Alice", + date: new Date("2024-01-15"), + children: [new Paragraph("First comment")], + }), + new Comment({ + id: "1", + author: "Bob", + date: new Date("2024-01-16"), + children: [new Paragraph("Second comment")], + }), + ], + }, + sections: [ + { + children: [ + new Paragraph({ + children: [ + new CommentRangeStart("0"), + new TextRun("Text with first comment."), + new CommentRangeEnd("0"), + new CommentReference("0"), + new TextRun(" "), + new CommentRangeStart("1"), + new TextRun("Text with second comment."), + new CommentRangeEnd("1"), + new CommentReference("1"), + ], + }), + ], + }, + ], +}); +``` + +## Reply Threads + +Create comment replies using the `parentId` property to build a thread: + +```ts +comments: { + children: [ + new Comment({ + id: "0", + author: "Alice", + date: new Date("2024-01-15"), + children: [new Paragraph("Is this correct?")], + }), + new Comment({ + id: "1", + author: "Bob", + date: new Date("2024-01-16"), + parentId: "0", // This is a reply to comment "0" + children: [new Paragraph("Yes, I verified it.")], + }), + new Comment({ + id: "2", + author: "Alice", + date: new Date("2024-01-17"), + parentId: "0", // Another reply to comment "0" + children: [new Paragraph("Thanks for checking!")], + }), + ], +} +``` + +## Rich Text Comments + +Comments can contain formatted text: + +```ts +new Comment({ + id: "0", + author: "Reviewer", + children: [ + new Paragraph({ + children: [new TextRun({ text: "Important: ", bold: true }), new TextRun("Please verify the figures in this section.")], + }), + new Paragraph("See page 12 of the source document."), + ], +}); +``` + +## Complete Example + +Document with review comments: + +```ts +import { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx"; +import * as fs from "fs"; + +const doc = new Document({ + comments: { + children: [ + new Comment({ + id: "suggestion", + author: "Editor", + date: new Date(), + children: [new Paragraph("Consider rephrasing this for clarity.")], + }), + new Comment({ + id: "fact-check", + author: "Fact Checker", + date: new Date(), + children: [ + new Paragraph({ + children: [new TextRun({ text: "Verified ", bold: true }), new TextRun("- Source: Annual Report 2023")], + }), + ], + }), + ], + }, + sections: [ + { + children: [ + new Paragraph({ + text: "Quarterly Report", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + children: [ + new TextRun("Our "), + new CommentRangeStart("suggestion"), + new TextRun("company achieved remarkable growth"), + new CommentRangeEnd("suggestion"), + new CommentReference("suggestion"), + new TextRun(" this quarter. "), + new CommentRangeStart("fact-check"), + new TextRun("Revenue increased by 25%"), + new CommentRangeEnd("fact-check"), + new CommentReference("fact-check"), + new TextRun(" compared to last year."), + ], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("document.docx", buffer); +}); +``` + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/73-comments.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/73-comments.ts_ diff --git a/docs/usage/convenience-functions.md b/docs/usage/convenience-functions.md index 76236ca6c4..ff95be16a2 100644 --- a/docs/usage/convenience-functions.md +++ b/docs/usage/convenience-functions.md @@ -1,22 +1,175 @@ -# Convenience functions +# Convenience Functions -OOXML and this library mainly uses a unit called twentieths of a point or `twip` for short. a twip is a typographical measurement, defined as 1/20 of a typographical point. One twip is 1/1440 inch, or 17.64 μm. This unit is not intuitive for many users, so some functions were created to help +OOXML and this library mainly uses a unit called twentieths of a point or `twip` for short. A twip is a typographical measurement, defined as 1/20 of a typographical point. One twip is 1/1440 inch, or 17.64 micrometers. -More info here: https://en.wikipedia.org/wiki/Twip +These functions help convert familiar units to twips. -## Convert Inches to Twip +More info: https://en.wikipedia.org/wiki/Twip + +## Unit Conversion Functions + +### Convert Inches to Twip ```ts import { convertInchesToTwip } from "docx"; -const twip = convertInchesToTwip(1); // returns 1440 -const twip = convertInchesToTwip(0.5); // returns 720 +convertInchesToTwip(1); // returns 1440 +convertInchesToTwip(0.5); // returns 720 +convertInchesToTwip(2); // returns 2880 ``` -## Convert Millimeters to Twip +### Convert Millimeters to Twip ```ts import { convertMillimetersToTwip } from "docx"; -const twip = convertMillimetersToTwip(50); // returns 2834 +convertMillimetersToTwip(25.4); // returns 1440 (1 inch = 25.4mm) +convertMillimetersToTwip(50); // returns 2834 +convertMillimetersToTwip(10); // returns 567 ``` + +## Common Use Cases + +### Setting Page Margins + +```ts +import { Document, convertInchesToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + page: { + margin: { + top: convertInchesToTwip(1), // 1 inch + right: convertInchesToTwip(1), + bottom: convertInchesToTwip(1), + left: convertInchesToTwip(1.5), // 1.5 inches for binding + }, + }, + }, + children: [ + /* ... */ + ], + }, + ], +}); +``` + +### Setting Page Size + +```ts +import { Document, convertMillimetersToTwip, PageOrientation } from "docx"; + +// A4 paper size +const doc = new Document({ + sections: [ + { + properties: { + page: { + size: { + width: convertMillimetersToTwip(210), // A4 width + height: convertMillimetersToTwip(297), // A4 height + orientation: PageOrientation.PORTRAIT, + }, + }, + }, + children: [ + /* ... */ + ], + }, + ], +}); +``` + +### Column Spacing + +```ts +import { Document, convertMillimetersToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + column: { + count: 2, + space: convertMillimetersToTwip(10), // 10mm between columns + }, + }, + children: [ + /* ... */ + ], + }, + ], +}); +``` + +### Table Cell Width + +```ts +import { Table, TableCell, TableRow, WidthType, convertInchesToTwip } from "docx"; + +new Table({ + rows: [ + new TableRow({ + children: [ + new TableCell({ + width: { + size: convertInchesToTwip(2), // 2 inch wide cell + type: WidthType.DXA, + }, + children: [new Paragraph("Cell content")], + }), + ], + }), + ], +}); +``` + +## Quick Reference + +### Inches to Twips + +| Inches | Twips | +| ------ | ----- | +| 0.25 | 360 | +| 0.5 | 720 | +| 0.75 | 1080 | +| 1 | 1440 | +| 1.5 | 2160 | +| 2 | 2880 | + +### Millimeters to Twips (approximate) + +| Millimeters | Twips | +| ----------- | ----- | +| 5 | 283 | +| 10 | 567 | +| 15 | 850 | +| 20 | 1134 | +| 25 | 1417 | +| 50 | 2834 | + +## EMUs (English Metric Units) + +For image positioning, OOXML uses EMUs (English Metric Units). One inch equals 914400 EMUs. + +```ts +// Image offset of 1 inch +floating: { + horizontalPosition: { + offset: 914400, // 1 inch in EMUs + }, + verticalPosition: { + offset: 914400, + }, +} +``` + +?> Unlike twips, there are currently no built-in conversion functions for EMUs. You can calculate them manually: `inches * 914400` or `mm * 36000`. + +## Related Documentation + +- [Understanding Units in OOXML](https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/) +- [Document](usage/document.md) - Document-level options +- [Page Layout](usage/page-layout.md) - Page size and margins diff --git a/docs/usage/document.md b/docs/usage/document.md index 5d7aff8d55..1d19dfc4a5 100644 --- a/docs/usage/document.md +++ b/docs/usage/document.md @@ -5,21 +5,82 @@ To create a new document, it is very easy: ```ts -const doc = new docx.Document(); +const doc = new docx.Document({ + sections: [ + { + children: [new Paragraph("Hello World")], + }, + ], +}); ``` -## Document properties +## Document Properties -You can add properties to the Word document by specifying options, for example: +You can add metadata properties to the Word document: ```ts const doc = new docx.Document({ creator: "Dolan Miu", description: "My extremely interesting document", title: "My Document", + subject: "Report", + keywords: "report, annual, finance", + sections: [ + /* ... */ + ], }); ``` +These properties appear in Word's File > Info panel and in file properties. + +## Options by Category + +### Metadata Properties + +| Property | Type | Description | +| -------------- | -------- | ----------------------------- | +| title | `string` | Document title | +| subject | `string` | Document subject | +| creator | `string` | Author name | +| keywords | `string` | Keywords for searching | +| description | `string` | Document description/comments | +| lastModifiedBy | `string` | Last person to modify | +| revision | `number` | Revision number | + +### Content Options + +| Property | Type | Description | +| --------- | ------------------------------------------- | ----------------- | +| sections | `ISectionOptions[]` | Document sections | +| comments | `ICommentsOptions` | Document comments | +| footnotes | `Record` | Footnotes | + +### Styling Options + +| Property | Type | Description | +| -------------- | ------------------- | ------------------------ | +| styles | `IStylesOptions` | Custom styles | +| externalStyles | `string` | External XML styles | +| numbering | `INumberingOptions` | Numbering definitions | +| fonts | `FontOptions[]` | Embedded fonts | +| defaultTabStop | `number` | Default tab stop (twips) | + +### Document Behavior + +| Property | Type | Description | +| -------------------------- | ------------------------------------------------------ | -------------------------- | +| background | `IDocumentBackgroundOptions` | Document background | +| features | `{ trackRevisions?: boolean; updateFields?: boolean }` | Feature flags | +| evenAndOddHeaderAndFooters | `boolean` | Different odd/even headers | +| hyphenation | `IHyphenationOptions` | Hyphenation settings | + +### Compatibility + +| Property | Type | Description | +| ------------------------ | ----------------------- | -------------------------- | +| compatibility | `ICompatibilityOptions` | Compatibility settings | +| compatabilityModeVersion | `number` | Word version compatibility | + ### Full list of options: | Property | Type | Notes | @@ -61,6 +122,60 @@ const doc = new docx.Document({ You can mix and match whatever properties you want, or provide no properties. +### Custom Properties + +Add custom metadata properties that appear in Word's document properties: + +```ts +const doc = new docx.Document({ + customProperties: [ + { + name: "Department", + value: "Engineering", + }, + { + name: "Project Code", + value: "PRJ-2024-001", + }, + { + name: "Approved", + value: true, + }, + { + name: "Version", + value: 2.5, + }, + ], + sections: [ + /* ... */ + ], +}); +``` + +Custom properties support these value types: + +- `string` - Text values +- `number` - Numeric values +- `boolean` - True/false values + +### Document Features + +Enable special features like track changes or field updating: + +```ts +const doc = new docx.Document({ + features: { + trackRevisions: true, // Enable track changes + updateFields: true, // Update fields (like TOC) when opened + }, + sections: [ + /* ... */ + ], +}); +``` + +?> Set `updateFields: true` when using Table of Contents so it updates automatically when the document is opened. + ### Units for positioning Various parts of the API require positioning arguments. The units are "20ths of a point" from the [OOXML](http://officeopenxml.com/index.php) specification. diff --git a/docs/usage/fields.md b/docs/usage/fields.md index 69475cc425..b2b3432248 100644 --- a/docs/usage/fields.md +++ b/docs/usage/fields.md @@ -8,16 +8,16 @@ There are very complicated fields like the table of contents, but in many cases Word uses field codes to identify what the result of the field should be. You can find these field codes by adding a field in a document (`Insert -> Quick Parts -> Field...`) and clicking the 'Field codes'-button. Some examples include: -Field type | Example | Description ------------ | --------------- | --------------------------------------------------------- -= (Formula) | `=2*21` | Calculates the result of a formula. You can also use bookmarks as variables, see below. -Author | `AUTHOR` | Includes the author mentioned in the document properties. -CreateDate | `CREATEDATE` | Date the document was created. -Date | `DATE` | Today's date. -FileName | `FILENAME \p` | The name of the document. Add `\p` for the complete path. -Info | `INFO NumWords` | Data from the document properties, e.g. the number of words in the document. -NumPages | `NUMPAGES` | Number of pages in the document. -UserName | `USERNAME` | Your user name from the Office personalization settings. +| Field type | Example | Description | +| ----------- | --------------- | --------------------------------------------------------------------------------------- | +| = (Formula) | `=2*21` | Calculates the result of a formula. You can also use bookmarks as variables, see below. | +| Author | `AUTHOR` | Includes the author mentioned in the document properties. | +| CreateDate | `CREATEDATE` | Date the document was created. | +| Date | `DATE` | Today's date. | +| FileName | `FILENAME \p` | The name of the document. Add `\p` for the complete path. | +| Info | `INFO NumWords` | Data from the document properties, e.g. the number of words in the document. | +| NumPages | `NUMPAGES` | Number of pages in the document. | +| UserName | `USERNAME` | Your user name from the Office personalization settings. | Fields can be added as a child of a paragraph: @@ -43,9 +43,9 @@ One type of field is the formula that can be used to do some basic calculations. const paragraph = new Paragraph({ children: [ new TextRun("Value one is: "), - new Bookmark({ id: "One", children: [new TextRun("451")]}), + new Bookmark({ id: "One", children: [new TextRun("451")] }), new TextRun(". The second value is: "), - new Bookmark({ id: "Two", children: [new TextRun("886")]}), + new Bookmark({ id: "Two", children: [new TextRun("886")] }), new TextRun(". The sum of these values is: "), new SimpleField("=One+Two"), ], diff --git a/docs/usage/fonts.md b/docs/usage/fonts.md new file mode 100644 index 0000000000..94c398d61a --- /dev/null +++ b/docs/usage/fonts.md @@ -0,0 +1,239 @@ +# Custom Fonts + +Custom fonts allow you to embed fonts directly into your document, ensuring consistent appearance across different systems. + +## Embedding Fonts + +Embed a font by providing the font data in the `Document` constructor: + +```ts +import * as fs from "fs"; +import { CharacterSet, Document, Paragraph, TextRun } from "docx"; + +const fontData = fs.readFileSync("./fonts/MyCustomFont.ttf"); + +const doc = new Document({ + fonts: [ + { + name: "MyCustomFont", + data: fontData, + characterSet: CharacterSet.ANSI, + }, + ], + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun({ + text: "This text uses a custom font", + font: "MyCustomFont", + }), + ], + }), + ], + }, + ], +}); +``` + +## Font Options + +| Property | Type | Notes | Description | +| ------------ | -------------- | -------- | -------------------------- | +| name | `string` | Required | Font name to reference | +| data | `Buffer` | Required | Font file data | +| characterSet | `CharacterSet` | Optional | Character set for the font | + +## Character Sets + +Available character sets: + +| Value | Description | +| -------------------------- | ------------------------ | +| `CharacterSet.ANSI` | Standard ANSI characters | +| `CharacterSet.DEFAULT` | Default character set | +| `CharacterSet.SYMBOL` | Symbol characters | +| `CharacterSet.MAC` | Macintosh characters | +| `CharacterSet.SHIFTJIS` | Japanese Shift-JIS | +| `CharacterSet.HANGUL` | Korean Hangul | +| `CharacterSet.JOHAB` | Korean Johab | +| `CharacterSet.GB2312` | Simplified Chinese | +| `CharacterSet.CHINESEBIG5` | Traditional Chinese | +| `CharacterSet.GREEK` | Greek characters | +| `CharacterSet.TURKISH` | Turkish characters | +| `CharacterSet.VIETNAMESE` | Vietnamese characters | +| `CharacterSet.HEBREW` | Hebrew characters | +| `CharacterSet.ARABIC` | Arabic characters | +| `CharacterSet.BALTIC` | Baltic characters | +| `CharacterSet.RUSSIAN` | Cyrillic characters | +| `CharacterSet.THAI` | Thai characters | +| `CharacterSet.EASTEUROPE` | Eastern European | + +## Using Custom Fonts + +### In TextRun + +```ts +new TextRun({ + text: "Custom font text", + font: "MyCustomFont", +}); +``` + +### In Paragraph Style + +```ts +new Paragraph({ + run: { + font: "MyCustomFont", + }, + children: [new TextRun("All text in this paragraph uses the custom font")], +}); +``` + +### In Document Styles + +```ts +const doc = new Document({ + fonts: [{ name: "CustomFont", data: fontData, characterSet: CharacterSet.ANSI }], + styles: { + default: { + document: { + run: { + font: "CustomFont", + }, + }, + }, + }, + sections: [ + /* ... */ + ], +}); +``` + +## Multiple Fonts + +Embed multiple fonts: + +```ts +const doc = new Document({ + fonts: [ + { + name: "HeadingFont", + data: fs.readFileSync("./fonts/Heading.ttf"), + characterSet: CharacterSet.ANSI, + }, + { + name: "BodyFont", + data: fs.readFileSync("./fonts/Body.ttf"), + characterSet: CharacterSet.ANSI, + }, + ], + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun({ + text: "Heading", + font: "HeadingFont", + size: 48, + }), + ], + }), + new Paragraph({ + children: [ + new TextRun({ + text: "Body text with a different font", + font: "BodyFont", + }), + ], + }), + ], + }, + ], +}); +``` + +## Mixing System and Custom Fonts + +You can mix embedded fonts with system fonts: + +```ts +new Paragraph({ + children: [ + new TextRun({ + text: "System font (Arial), ", + font: "Arial", + }), + new TextRun({ + text: "Custom embedded font", + font: "MyCustomFont", + }), + ], +}); +``` + +## Browser Usage + +In browsers, convert your font file to a base64 string or ArrayBuffer: + +```ts +import { CharacterSet, Document, Packer, Paragraph, TextRun } from "docx"; +import { saveAs } from "file-saver"; + +// Fetch the font file and convert to ArrayBuffer +const response = await fetch("./fonts/MyFont.ttf"); +const fontData = await response.arrayBuffer(); + +const doc = new Document({ + fonts: [ + { + name: "MyFont", + data: Buffer.from(fontData), + characterSet: CharacterSet.ANSI, + }, + ], + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun({ + text: "Text with embedded font", + font: "MyFont", + }), + ], + }), + ], + }, + ], +}); + +// Export the document +Packer.toBlob(doc).then((blob) => { + saveAs(blob, "document.docx"); +}); +``` + +## Supported Font Formats + +- **TTF** (TrueType Font) - Most common, widely supported +- **OTF** (OpenType Font) - Also supported + +?> For best compatibility, use TTF fonts when possible. + +## Demo + +### Embedding Custom Fonts + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/91-custom-fonts.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/91-custom-fonts.ts_ + +### Declarative Custom Fonts + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/92-declarative-custom-fonts.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/92-declarative-custom-fonts.ts_ diff --git a/docs/usage/headers-and-footers.md b/docs/usage/headers-and-footers.md index e2260174c7..410097de76 100644 --- a/docs/usage/headers-and-footers.md +++ b/docs/usage/headers-and-footers.md @@ -1,58 +1,412 @@ # Headers and Footers -!> Headers and Footers requires an understanding of [Sections](usage/sections.md). +!> Headers and Footers require an understanding of [Sections](usage/sections.md). -Every Section has a sections which you can define its Headers and Footers: +Every section has headers and footers that appear on each page within that section. + +## Basic Headers and Footers ```ts +import { Document, Footer, Header, Paragraph } from "docx"; + const doc = new Document({ - sections: [{ - headers: { - default: new Header({ // The standard default header on every page or header on odd pages when the 'Different Odd & Even Pages' option is activated - children: [], - }), - first: new Header({ // The header on first page when the 'Different First Page' option is activated - children: [], - }), - even: new Header({ // The header on even pages when the 'Different Odd & Even Pages' option is activated - children: [], - }), + sections: [ + { + headers: { + default: new Header({ + children: [new Paragraph("Header text")], + }), + }, + footers: { + default: new Footer({ + children: [new Paragraph("Footer text")], + }), + }, + children: [new Paragraph("Document content")], }, - footers: { - default: new Footer({ // The standard default footer on every page or footer on odd pages when the 'Different Odd & Even Pages' option is activated - children: [], - }), - first: new Footer({ // The footer on first page when the 'Different First Page' option is activated - children: [], - }), - even: new Footer({ // The footer on even pages when the 'Different Odd & Even Pages' option is activated - children: [], - }), - }, - children: [], - }]; + ], }); ``` -## Example +## Header/Footer Types -Example showing basic header and footer - -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/8-header-footer.ts ':include') - -_Source: https://github.com/dolanmiu/docx/blob/master/demo/8-header-footer.ts_ +| Type | Description | Requires | +| --------- | --------------------------------------------------- | ---------------------------------- | +| `default` | Standard header/footer on every page (or odd pages) | - | +| `first` | Header/footer on the first page only | `titlePage: true` | +| `even` | Header/footer on even pages | `evenAndOddHeaderAndFooters: true` | ## Different First Page -To specify `'Different First Page'`, set `titlePage: true` in the sections array as shown below. +To have a different header/footer on the first page: -``` -sections: [ +```ts +const doc = new Document({ + sections: [ { - properties: { - titlePage: true, + properties: { + titlePage: true, // Enable different first page + }, + headers: { + default: new Header({ + children: [new Paragraph("Header on all pages except first")], + }), + first: new Header({ + children: [new Paragraph("Special first page header")], + }), + }, + footers: { + default: new Footer({ + children: [new Paragraph("Footer on all pages except first")], + }), + first: new Footer({ + children: [], // No footer on first page + }), + }, + children: [ + /* ... */ + ], + }, + ], +}); ``` -## Multiple Headers and Footers +## Different Odd and Even Pages -More headers and footers can be accomplished by creating more `Section`. New headers and footers can be set per `Section` +For documents like books with different left/right pages: + +```ts +const doc = new Document({ + evenAndOddHeaderAndFooters: true, // Enable at document level + sections: [ + { + headers: { + default: new Header({ + children: [ + new Paragraph({ + text: "Chapter Title", + alignment: AlignmentType.RIGHT, // Right on odd pages + }), + ], + }), + even: new Header({ + children: [ + new Paragraph({ + text: "Book Title", + alignment: AlignmentType.LEFT, // Left on even pages + }), + ], + }), + }, + children: [ + /* ... */ + ], + }, + ], +}); +``` + +## Page Numbers in Headers/Footers + +Add page numbers using the `PageNumber` class: + +```ts +import { AlignmentType, Footer, PageNumber, Paragraph, TextRun } from "docx"; + +const footer = new Footer({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun("Page "), + new TextRun({ + children: [PageNumber.CURRENT], + }), + new TextRun(" of "), + new TextRun({ + children: [PageNumber.TOTAL_PAGES], + }), + ], + }), + ], +}); +``` + +### Common Page Number Patterns + +**Centered page number:** + +```ts +new Footer({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [new TextRun({ children: [PageNumber.CURRENT] })], + }), + ], +}); +``` + +**Right-aligned page number:** + +```ts +new Footer({ + children: [ + new Paragraph({ + alignment: AlignmentType.RIGHT, + children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })], + }), + ], +}); +``` + +## Images in Headers/Footers + +Add logos or images: + +```ts +import { Header, ImageRun, Paragraph } from "docx"; + +const header = new Header({ + children: [ + new Paragraph({ + children: [ + new ImageRun({ + type: "png", + data: fs.readFileSync("./logo.png"), + transformation: { + width: 100, + height: 50, + }, + }), + ], + }), + ], +}); +``` + +## Header/Footer Margins + +Control the distance from the edge of the page: + +```ts +sections: [ + { + properties: { + page: { + margin: { + header: 720, // Distance from top edge to header (in twips) + footer: 720, // Distance from bottom edge to footer + }, + }, + }, + headers: { + /* ... */ + }, + footers: { + /* ... */ + }, + children: [ + /* ... */ + ], + }, +]; +``` + +## Multiple Elements in Headers/Footers + +Headers and footers can contain multiple paragraphs, tables, and images: + +```ts +const header = new Header({ + children: [ + new Paragraph({ + children: [ + new ImageRun({ + type: "png", + data: fs.readFileSync("./logo.png"), + transformation: { width: 80, height: 40 }, + }), + ], + }), + new Paragraph({ + text: "Company Name", + alignment: AlignmentType.CENTER, + }), + new Paragraph({ + text: "Confidential Document", + alignment: AlignmentType.RIGHT, + }), + ], +}); +``` + +## Using Tables for Layout + +Create complex header layouts with tables: + +```ts +import { AlignmentType, BorderStyle, Header, Paragraph, Table, TableCell, TableRow, WidthType } from "docx"; + +// Helper to create invisible borders for layout tables +const noBorders = { + top: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }, + bottom: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }, + left: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }, + right: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" }, +}; + +const header = new Header({ + children: [ + new Table({ + width: { size: 100, type: WidthType.PERCENTAGE }, + rows: [ + new TableRow({ + children: [ + new TableCell({ + children: [new Paragraph("Left content")], + borders: noBorders, + }), + new TableCell({ + children: [ + new Paragraph({ + text: "Center content", + alignment: AlignmentType.CENTER, + }), + ], + borders: noBorders, + }), + new TableCell({ + children: [ + new Paragraph({ + text: "Right content", + alignment: AlignmentType.RIGHT, + }), + ], + borders: noBorders, + }), + ], + }), + ], + }), + ], +}); +``` + +## Multiple Sections with Different Headers + +Each section can have its own headers and footers: + +```ts +const doc = new Document({ + sections: [ + { + headers: { + default: new Header({ + children: [new Paragraph("Chapter 1")], + }), + }, + children: [new Paragraph("Chapter 1 content...")], + }, + { + headers: { + default: new Header({ + children: [new Paragraph("Chapter 2")], + }), + }, + children: [new Paragraph("Chapter 2 content...")], + }, + ], +}); +``` + +## Complete Example + +Professional document with company header: + +```ts +import { AlignmentType, Document, Footer, Header, ImageRun, PageNumber, Packer, Paragraph, TextRun } from "docx"; +import * as fs from "fs"; + +const doc = new Document({ + sections: [ + { + properties: { + titlePage: true, + }, + headers: { + first: new Header({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new ImageRun({ + type: "png", + data: fs.readFileSync("./logo.png"), + transformation: { width: 150, height: 75 }, + }), + ], + }), + ], + }), + default: new Header({ + children: [ + new Paragraph({ + children: [new TextRun({ text: "Company Name", bold: true }), new TextRun(" | Confidential")], + }), + ], + }), + }, + footers: { + first: new Footer({ + children: [], // No footer on cover page + }), + default: new Footer({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun("Page "), + new TextRun({ children: [PageNumber.CURRENT] }), + new TextRun(" of "), + new TextRun({ children: [PageNumber.TOTAL_PAGES] }), + ], + }), + ], + }), + }, + children: [new Paragraph("Document content...")], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("document.docx", buffer); +}); +``` + +## Demos + +### Basic Header and Footer + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/8-header-footer.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/8-header-footer.ts_ + +### Odd/Even Headers and Footers + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/63-odd-even-header-footer.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/63-odd-even-header-footer.ts_ + +### Header and Footer Margins + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/59-header-footer-margins.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/59-header-footer-margins.ts_ + +### Images in Header and Footer + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/9-images-in-header-and-footer.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/9-images-in-header-and-footer.ts_ diff --git a/docs/usage/hyperlinks.md b/docs/usage/hyperlinks.md index a5faa3d7f4..877a2cc207 100644 --- a/docs/usage/hyperlinks.md +++ b/docs/usage/hyperlinks.md @@ -79,6 +79,10 @@ const paragraph = new Paragraph({ }); ``` +## Related Topics + +- **[Bookmarks](usage/bookmarks.md)** - For detailed coverage of bookmarks, internal hyperlinks, and page references + ## Styling hyperlinks It is possible to set the style of the text of both internal and external hyperlinks. This can be done applying run formatting on any of the `TextRun` children of the hyperlink. Use the `style: "Hyperlink"` property to show the default link styles, which can be combined with any other style. diff --git a/docs/usage/images.md b/docs/usage/images.md index 8fa763b3bf..995fc6a084 100644 --- a/docs/usage/images.md +++ b/docs/usage/images.md @@ -2,6 +2,34 @@ !> Images requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md). +## Common Use Cases + +| I want to... | Use | Example | +| -------------------------------------- | ----------------------- | ---------------------------- | +| Insert an image inline with text | Inline (default) | Logo next to company name | +| Position image at specific coordinates | Floating with offset | Letterhead logo at top-right | +| Have text wrap around an image | Floating with wrap | Magazine-style layout | +| Put an image in a table cell | Inline in TableCell | Product catalog | +| Add image to header/footer | Inline in Header/Footer | Company letterhead | + +## Inline vs Floating: When to Use Which + +**Use Inline when:** + +- Image should flow with text +- Image is part of content (diagrams, screenshots) +- Image goes inside tables +- Image in headers/footers + +**Use Floating when:** + +- Image needs precise positioning +- Text should wrap around image +- Image overlays content (watermarks) +- Complex page layouts + +--- + To create a `floating` image on top of text: ```ts @@ -27,7 +55,7 @@ By default with no arguments, its an `inline` image: ```ts const image = new ImageRun({ - type: 'gif', + type: "gif", data: fs.readFileSync("./demo/images/pizza.gif"), transformation: { width: 100, @@ -85,8 +113,8 @@ const doc = new Document({ Three types of image positioning is supported: -- Floating -- Inline +- Floating +- Inline By default, images are exported as `Inline` elements. @@ -100,7 +128,7 @@ To change the position the image to be on top of the text, simply add the `float ```ts const image = new ImageRun({ - type: 'png', + type: "png", data: buffer, transformation: { width: 903, @@ -119,7 +147,7 @@ const image = new ImageRun({ ```ts const image = new ImageRun({ - type: 'png', + type: "png", data: buffer, transformation: { width: 903, @@ -185,7 +213,7 @@ For example: ```ts const image = new ImageRun({ - type: 'gif', + type: "gif", data: fs.readFileSync("./demo/images/pizza.gif"), transformation: { width: 200, @@ -234,7 +262,7 @@ For example: ```ts const image = new ImageRun({ - type: 'gif', + type: "gif", data: fs.readFileSync("./demo/images/pizza.gif"), transformation: { width: 200, @@ -265,7 +293,7 @@ Specifies common non-visual DrawingML properties. A name, title and description ```ts const image = new ImageRun({ - type: 'gif', + type: "gif", data: fs.readFileSync("./demo/images/pizza.gif"), altText: { title: "This is an ultimate title", diff --git a/docs/usage/line-numbers.md b/docs/usage/line-numbers.md new file mode 100644 index 0000000000..fec51f160c --- /dev/null +++ b/docs/usage/line-numbers.md @@ -0,0 +1,178 @@ +# Line Numbers + +!> Line Numbers require an understanding of [Sections](usage/sections.md). + +Line numbers are useful for legal documents, code listings, scripts, and any document where referencing specific lines is important. + +## Basic Line Numbers + +Add line numbers to a section: + +```ts +import { Document, LineNumberRestartFormat, Paragraph } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.CONTINUOUS, + }, + }, + children: [new Paragraph("Line 1"), new Paragraph("Line 2"), new Paragraph("Line 3")], + }, + ], +}); +``` + +## Line Number Options + +| Property | Type | Notes | Description | +| -------- | ------------------------- | -------- | -------------------------- | +| countBy | `number` | Optional | Show number every N lines | +| start | `number` | Optional | Starting line number | +| restart | `LineNumberRestartFormat` | Optional | When to restart numbering | +| distance | `number` | Optional | Distance from text (twips) | + +## Restart Options + +Control when line numbers restart: + +```ts +import { LineNumberRestartFormat } from "docx"; + +// Continuous - numbers continue throughout document +lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.CONTINUOUS, +} + +// Restart each page +lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.NEW_PAGE, +} + +// Restart each section +lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.NEW_SECTION, +} +``` + +## Count Interval + +Show line numbers at specific intervals: + +```ts +// Show every 5th line number (5, 10, 15...) +lineNumbers: { + countBy: 5, + restart: LineNumberRestartFormat.CONTINUOUS, +} +``` + +## Starting Number + +Start from a specific line number: + +```ts +lineNumbers: { + countBy: 1, + start: 100, // First line is 100 + restart: LineNumberRestartFormat.CONTINUOUS, +} +``` + +## Suppressing Line Numbers + +Suppress line numbers for specific paragraphs: + +```ts +new Paragraph({ + text: "This paragraph will not have a line number", + suppressLineNumbers: true, +}); +``` + +This is useful for headings, titles, or any content that shouldn't be numbered. + +## Complete Example + +Legal document with line numbers: + +```ts +import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.NEW_PAGE, + }, + }, + children: [ + new Paragraph({ + text: "AGREEMENT", + heading: HeadingLevel.HEADING_1, + suppressLineNumbers: true, // Don't number the title + }), + new Paragraph("This Agreement is entered into as of the date last signed below."), + new Paragraph("WHEREAS, Party A desires to engage Party B for services;"), + new Paragraph("WHEREAS, Party B has the expertise to provide such services;"), + new Paragraph({ + text: "TERMS AND CONDITIONS", + heading: HeadingLevel.HEADING_2, + suppressLineNumbers: true, // Don't number section headers + }), + new Paragraph("1. Party B shall provide consulting services as requested by Party A."), + new Paragraph("2. Payment shall be made within 30 days of invoice receipt."), + new Paragraph("3. This agreement may be terminated by either party with 30 days notice."), + ], + }, + ], +}); +``` + +## Multiple Sections with Different Settings + +```ts +import { Document, LineNumberRestartFormat, Paragraph, SectionType } from "docx"; + +const doc = new Document({ + sections: [ + // First section - no line numbers + { + children: [new Paragraph("Introduction without line numbers...")], + }, + // Second section - numbered lines + { + properties: { + type: SectionType.NEXT_PAGE, + lineNumbers: { + countBy: 1, + restart: LineNumberRestartFormat.CONTINUOUS, + }, + }, + children: [new Paragraph("This section has line numbers...")], + }, + ], +}); +``` + +## Demos + +### Basic Line Numbers + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/40-line-numbers.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/40-line-numbers.ts_ + +### Line Number Suppression + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/70-line-numbers-suppression.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/70-line-numbers-suppression.ts_ diff --git a/docs/usage/numbering.md b/docs/usage/numbering.md index 661f2c6759..758b0623f2 100644 --- a/docs/usage/numbering.md +++ b/docs/usage/numbering.md @@ -95,7 +95,7 @@ Along with `reference` and `level`, the `numbering` object supports an optional | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | reference | `string` | The numbering style reference, must match a defined config | | level | `number` | The list level (0 = top-level, 1 = sub-list, etc.) | -| instance | `number` | *(Optional)* Identifies the instance of the list. Lists with the same `instance` (or none) continue numbering across paragraphs. A new `instance` value restarts numbering from `1`. | +| instance | `number` | _(Optional)_ Identifies the instance of the list. Lists with the same `instance` (or none) continue numbering across paragraphs. A new `instance` value restarts numbering from `1`. | Example: @@ -116,8 +116,6 @@ new Paragraph({ }); ``` - - ## Un-ordered lists / Bullet points Add a `numbering` section to the `Document` to numbering style, define your levels. Use `LevelFormat.BULLET` for the `format` in `levels`: diff --git a/docs/usage/packers.md b/docs/usage/packers.md index da2518593e..8f9b78dd3e 100644 --- a/docs/usage/packers.md +++ b/docs/usage/packers.md @@ -79,7 +79,7 @@ Packer.toString(doc, true, overrides).then((string) => { You can also use the lower-level `Packer.pack` method to export to any specified type. ```ts -Packer.pack(doc, 'string').then((string) => { +Packer.pack(doc, "string").then((string) => { console.log(string); }); ``` diff --git a/docs/usage/page-layout.md b/docs/usage/page-layout.md new file mode 100644 index 0000000000..dfdde45e0a --- /dev/null +++ b/docs/usage/page-layout.md @@ -0,0 +1,264 @@ +# Page Layout + +!> Page Layout requires an understanding of [Sections](usage/sections.md). + +Page layout options control the physical appearance of your document pages, including size, margins, orientation, and borders. + +## Page Size + +Set custom page dimensions: + +```ts +import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + page: { + size: { + width: convertMillimetersToTwip(210), // A4 width + height: convertMillimetersToTwip(297), // A4 height + }, + }, + }, + children: [new Paragraph("A4 sized page")], + }, + ], +}); +``` + +### Common Page Sizes + +| Size | Width (mm) | Height (mm) | +| ------ | ---------- | ----------- | +| Letter | 216 | 279 | +| Legal | 216 | 356 | +| A4 | 210 | 297 | +| A3 | 297 | 420 | +| A5 | 148 | 210 | + +## Page Orientation + +Set portrait or landscape orientation: + +```ts +import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx"; + +// Landscape A4 +// Note: For landscape, swap width and height values so the larger dimension becomes the width +const doc = new Document({ + sections: [ + { + properties: { + page: { + size: { + orientation: PageOrientation.LANDSCAPE, + width: convertMillimetersToTwip(297), // A4 height becomes landscape width + height: convertMillimetersToTwip(210), // A4 width becomes landscape height + }, + }, + }, + children: [new Paragraph("Landscape page")], + }, + ], +}); +``` + +?> When switching to landscape, you must manually swap the width and height values. The `orientation` property alone only tells Word how to display the page - you still need to provide the correct dimensions. + +## Page Margins + +Set margins for the page: + +```ts +import { Document, Paragraph, convertInchesToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + page: { + margin: { + top: convertInchesToTwip(1), + right: convertInchesToTwip(1), + bottom: convertInchesToTwip(1), + left: convertInchesToTwip(1.5), // Extra for binding + }, + }, + }, + children: [new Paragraph("Page with custom margins")], + }, + ], +}); +``` + +### Margin Options + +| Property | Type | Description | +| -------- | -------- | ---------------------------------------------------------------- | +| top | `number` | Top margin (twips) | +| right | `number` | Right margin | +| bottom | `number` | Bottom margin | +| left | `number` | Left margin | +| header | `number` | Header margin | +| footer | `number` | Footer margin | +| gutter | `number` | Gutter margin (extra space for binding in double-sided printing) | + +## Page Borders + +Add borders around pages: + +```ts +import { BorderStyle, Document, PageBorderDisplay, PageBorderOffsetFrom, Paragraph } from "docx"; + +// Note: Border size is measured in 1/8 points (so size: 8 = 1pt, size: 16 = 2pt) +const doc = new Document({ + sections: [ + { + properties: { + page: { + borders: { + pageBorderTop: { + style: BorderStyle.SINGLE, + size: 8, // 1pt (8 eighths of a point) + color: "000000", + }, + pageBorderRight: { + style: BorderStyle.SINGLE, + size: 8, + color: "000000", + }, + pageBorderBottom: { + style: BorderStyle.DOUBLE, + size: 16, // 2pt + color: "FF0000", + }, + pageBorderLeft: { + style: BorderStyle.SINGLE, + size: 8, + color: "000000", + }, + }, + }, + }, + children: [new Paragraph("Page with borders")], + }, + ], +}); +``` + +### Border Options + +| Property | Type | Description | +| -------- | ------------- | ---------------------------------------------------- | +| style | `BorderStyle` | Border style | +| size | `number` | Border width in 1/8 points (e.g., 8 = 1pt, 16 = 2pt) | +| color | `string` | Hex color code | +| space | `number` | Space from text (points) | + +### Border Styles + +Common border styles include: + +- `BorderStyle.SINGLE` - Single line +- `BorderStyle.DOUBLE` - Double line +- `BorderStyle.DASHED` - Dashed line +- `BorderStyle.DOTTED` - Dotted line +- `BorderStyle.THICK` - Thick line +- `BorderStyle.WAVE` - Wavy line + +### Page Border Display Options + +Control when and how borders appear: + +```ts +import { PageBorderDisplay, PageBorderOffsetFrom, PageBorderZOrder } from "docx"; + +page: { + borders: { + pageBorders: { + display: PageBorderDisplay.ALL_PAGES, // or FIRST_PAGE, NOT_FIRST_PAGE + offsetFrom: PageBorderOffsetFrom.TEXT, // or PAGE + zOrder: PageBorderZOrder.FRONT, // or BACK + }, + // ... individual border definitions + }, +} +``` + +## Complete Example + +Combining multiple layout options: + +```ts +import { BorderStyle, Document, PageBorderDisplay, PageOrientation, Paragraph, convertInchesToTwip, convertMillimetersToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + page: { + size: { + orientation: PageOrientation.PORTRAIT, + width: convertMillimetersToTwip(210), + height: convertMillimetersToTwip(297), + }, + margin: { + top: convertInchesToTwip(1), + right: convertInchesToTwip(1), + bottom: convertInchesToTwip(1), + left: convertInchesToTwip(1.25), + }, + borders: { + pageBorderTop: { + style: BorderStyle.SINGLE, + size: 8, + color: "4472C4", + }, + pageBorderRight: { + style: BorderStyle.SINGLE, + size: 8, + color: "4472C4", + }, + pageBorderBottom: { + style: BorderStyle.SINGLE, + size: 8, + color: "4472C4", + }, + pageBorderLeft: { + style: BorderStyle.SINGLE, + size: 8, + color: "4472C4", + }, + pageBorders: { + display: PageBorderDisplay.ALL_PAGES, + }, + }, + }, + }, + children: [new Paragraph("This page has A4 size, 1-inch margins, and blue borders.")], + }, + ], +}); +``` + +## Demos + +### Page Borders + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/71-page-borders-2.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/71-page-borders-2.ts_ + +### Page Sizes + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/65-page-sizes.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/65-page-sizes.ts_ + +### Landscape Orientation + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/7-landscape.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/7-landscape.ts_ diff --git a/docs/usage/page-numbers.md b/docs/usage/page-numbers.md index 377a453e39..a94ff62ffd 100644 --- a/docs/usage/page-numbers.md +++ b/docs/usage/page-numbers.md @@ -9,15 +9,15 @@ new Paragraph({ children: [ new TextRun({ children: ["Page #: ", PageNumber.CURRENT], - }) - ] -}) + }), + ], +}); ``` ## Current page number ```ts -PageNumber.CURRENT +PageNumber.CURRENT; ``` For example: @@ -27,15 +27,15 @@ new Paragraph({ children: [ new TextRun({ children: ["Page Number ", PageNumber.CURRENT], - }) - ] -}) + }), + ], +}); ``` ## Total number of pages ```ts -PageNumber.TOTAL_PAGES +PageNumber.TOTAL_PAGES; ``` For example: @@ -45,12 +45,11 @@ new Paragraph({ children: [ new TextRun({ children: ["Total Pages Number: ", PageNumber.TOTAL_PAGES], - }) - ] -}) + }), + ], +}); ``` - ## Both You can combine the two to get "Page 2 of 10" effect: @@ -72,6 +71,6 @@ new Paragraph({ Adding page numbers to Header and Footer -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/39-page-numbers.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/39-page-numbers.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/39-page-numbers.ts_ diff --git a/docs/usage/paragraph.md b/docs/usage/paragraph.md index 57a4007f5c..ccbc82df1b 100644 --- a/docs/usage/paragraph.md +++ b/docs/usage/paragraph.md @@ -64,7 +64,7 @@ This is the list of options for a paragraph. A detailed explanation is below: | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | [text](#text) | `string` | Optional | | | [heading](#heading) | `HeadingLevel` | Optional | `HEADING_1`, `HEADING_2`, `HEADING_3`, `HEADING_4`, `HEADING_5`, `HEADING_6`, `TITLE` | -| [border](#border) | `IBorderOptions` | Optional | `top`, `bottom`, `left`, `right`, `between`. Each of these are of type IBorderPropertyOptions. Click here for Example | +| [border](#border) | `IBorderOptions` | Optional | `top`, `bottom`, `left`, `right`, `between`. Each of these are of type IBorderPropertyOptions. Click here for Example | | [spacing](#spacing) | `ISpacingProperties` | Optional | See below for ISpacingProperties | | [outlineLevel](#outline-level) | `number` | Optional | | | alignment | `AlignmentType` | Optional | `START`, `CENTER`, `END`, `BOTH`, `MEDIUM_KASHIDA`, `DISTRIBUTE`, `NUM_TAB`, `HIGH_KASHIDA`, `LOW_KASHIDA`, `THAI_DISTRIBUTE`, `LEFT`, `RIGHT`, `JUSTIFIED` | diff --git a/docs/usage/patcher.md b/docs/usage/patcher.md index c2e0915cc9..f1fb0fdc44 100644 --- a/docs/usage/patcher.md +++ b/docs/usage/patcher.md @@ -35,7 +35,6 @@ interface Patch { | type | `PatchType` | Required | `DOCUMENT`, `PARAGRAPH` | | children | `FileChild[] or ParagraphChild[]` | Required | The contents to replace with. A `FileChild` is a `Paragraph` or `Table`, whereas a `ParagraphChild` is typical `Paragraph` children. | - The patcher also takes in a `keepOriginalStyles` boolean, which will preserve the styles of the patched text when set to true. ### How to patch existing document @@ -79,7 +78,11 @@ patchDocument(fs.readFileSync("My Document.docx"), { ], link: "https://www.google.co.uk", }), - new ImageRun({ type: 'png', data: fs.readFileSync("./demo/images/dog.png"), transformation: { width: 100, height: 100 } }), + new ImageRun({ + type: "png", + data: fs.readFileSync("./demo/images/dog.png"), + transformation: { width: 100, height: 100 }, + }), ], }), ], diff --git a/docs/usage/sections.md b/docs/usage/sections.md index 79c8f4c27a..19f5f91dbe 100644 --- a/docs/usage/sections.md +++ b/docs/usage/sections.md @@ -6,47 +6,212 @@ A section is a grouping of paragraphs that have a specific set of properties use For example, you could have one section which is portrait with a header and footer, and another section in landscape with no footer, and a header showing the current page number. -## Example +## Basic Example This creates a simple section in a document with one paragraph inside: ```ts const doc = new Document({ - sections: [{ - children: [ - new Paragraph({ - children: [new TextRun("Hello World")], - }), - ], - }]; + sections: [ + { + children: [ + new Paragraph({ + children: [new TextRun("Hello World")], + }), + ], + }, + ], }); ``` -## Properties +## Multiple Sections -You can specify additional properties to the section, by providing a `properties` attribute. - -### Section Type - -Setting the section type determines how the contents of the section will be placed relative to the previous section. E.g., There are five different types: - -- `CONTINUOUS` -- `EVEN_PAGE` -- `NEXT_COLUMN` -- `NEXT_PAGE` -- `ODD_PAGE` +Create documents with multiple sections for different layouts: ```ts const doc = new Document({ - sections: [{ - properties: { - type: SectionType.CONTINUOUS, - } - children: [ - new Paragraph({ - children: [new TextRun("Hello World")], - }), - ], - }]; + sections: [ + { + // First section - portrait + children: [new Paragraph("This is the first section in portrait.")], + }, + { + // Second section - landscape + properties: { + page: { + size: { + orientation: PageOrientation.LANDSCAPE, + }, + }, + }, + children: [new Paragraph("This section is in landscape orientation.")], + }, + ], }); ``` + +## Section Properties + +You can specify additional properties to the section by providing a `properties` attribute. + +### Section Type + +Setting the section type determines how the contents of the section will be placed relative to the previous section: + +| Type | Description | +| ------------- | ---------------------------------------------- | +| `CONTINUOUS` | Start on the same page as the previous section | +| `NEXT_PAGE` | Start on a new page (default) | +| `EVEN_PAGE` | Start on the next even-numbered page | +| `ODD_PAGE` | Start on the next odd-numbered page | +| `NEXT_COLUMN` | Start in the next column | + +```ts +import { SectionType } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [new Paragraph("First section content")], + }, + { + properties: { + type: SectionType.CONTINUOUS, // Don't start new page + }, + children: [new Paragraph("This continues on the same page")], + }, + ], +}); +``` + +### When to Use Each Section Type + +- **CONTINUOUS**: Multi-column layouts, changing headers without page breaks +- **NEXT_PAGE**: New chapters, distinct document parts +- **EVEN_PAGE/ODD_PAGE**: Books with content starting on specific sides +- **NEXT_COLUMN**: Newsletter-style column breaks + +## Common Use Cases + +### Different Headers Per Section + +```ts +const doc = new Document({ + sections: [ + { + headers: { + default: new Header({ + children: [new Paragraph("Chapter 1")], + }), + }, + children: [new Paragraph("Chapter 1 content...")], + }, + { + headers: { + default: new Header({ + children: [new Paragraph("Chapter 2")], + }), + }, + children: [new Paragraph("Chapter 2 content...")], + }, + ], +}); +``` + +### Portrait and Landscape Mix + +```ts +import { PageOrientation, convertMillimetersToTwip } from "docx"; + +const doc = new Document({ + sections: [ + { + // Portrait section for text + children: [new Paragraph("Introduction text...")], + }, + { + // Landscape section for wide table + properties: { + page: { + size: { + orientation: PageOrientation.LANDSCAPE, + width: convertMillimetersToTwip(297), + height: convertMillimetersToTwip(210), + }, + }, + }, + children: [ + new Table({ + // Wide table that needs landscape + rows: [ + /* ... */ + ], + }), + ], + }, + ], +}); +``` + +### Multi-Column Section + +```ts +const doc = new Document({ + sections: [ + { + // Single column intro + children: [new Paragraph("Introduction paragraph...")], + }, + { + // Two-column body + properties: { + type: SectionType.CONTINUOUS, + column: { + count: 2, + space: 708, + }, + }, + children: [new Paragraph("Two-column content...")], + }, + { + // Back to single column + properties: { + type: SectionType.CONTINUOUS, + }, + children: [new Paragraph("Single column conclusion...")], + }, + ], +}); +``` + +## Section Properties Reference + +| Property | Type | Description | +| ------------- | ----------------------- | --------------------------------------- | +| type | `SectionType` | How section starts relative to previous | +| page | `IPageSizeAttributes` | Page size, margins, borders | +| column | `IColumnsAttributes` | Multi-column configuration | +| titlePage | `boolean` | Different first page header/footer | +| lineNumbers | `ILineNumberAttributes` | Line numbering configuration | +| verticalAlign | `VerticalAlign` | Vertical alignment of content | + +## Related Topics + +- **[Page Layout](usage/page-layout.md)** - Page size, margins, and borders +- **[Headers & Footers](usage/headers-and-footers.md)** - Section headers and footers +- **[Columns](usage/columns.md)** - Multi-column layouts +- **[Line Numbers](usage/line-numbers.md)** - Line numbering per section + +## Demos + +### Multiple Sections + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/16-multiple-sections.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/16-multiple-sections.ts_ + +### Section Types + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/58-section-types.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/58-section-types.ts_ diff --git a/docs/usage/styling-with-js.md b/docs/usage/styling-with-js.md index d02efc62dd..f478d6810c 100644 --- a/docs/usage/styling-with-js.md +++ b/docs/usage/styling-with-js.md @@ -21,27 +21,27 @@ const name = new TextRun({ ### Run formatting -- `bold`, `italics`, `smallCaps`, `allCaps`, `strike`, `doubleStrike`, `subScript`, `superScript`: Set the formatting property to true -- `underline({type="single", color=null})`: Set the underline style and color -- `emphasisMark({type="dot"})`: Set the emphasis mark style -- `color(color)`: Set the text color, using 6 hex characters for RRGGBB (no leading `#`) -- `size(halfPts)`: Set the font size, measured in half-points -- `font(name)` or `font({ascii, cs, eastAsia, hAnsi, hint})`: Set the run's font -- `style(name)`: Apply a named run style -- `characterSpacing(value)`: Set the character spacing adjustment (in TWIPs) +- `bold`, `italics`, `smallCaps`, `allCaps`, `strike`, `doubleStrike`, `subScript`, `superScript`: Set the formatting property to true +- `underline({type="single", color=null})`: Set the underline style and color +- `emphasisMark({type="dot"})`: Set the emphasis mark style +- `color(color)`: Set the text color, using 6 hex characters for RRGGBB (no leading `#`) +- `size(halfPts)`: Set the font size, measured in half-points +- `font(name)` or `font({ascii, cs, eastAsia, hAnsi, hint})`: Set the run's font +- `style(name)`: Apply a named run style +- `characterSpacing(value)`: Set the character spacing adjustment (in TWIPs) ### Paragraph formatting -- `heading1`, `heading2`, `heading3`, `heading4`, `heading5`, `title`: apply the appropriate style to the paragraph -- `left`, `center`, `right`, `justified`: set the paragraph's alignment -- `thematicBreak`, `pageBreak`: Insert a thick rule or a page break beneath the paragraph -- `leftTabStop(position)`: Add a left tab stop (measured in TWIPs from the left) -- `maxRightTabStop`: Add a right tab stop at the far right -- `bullet`: Use the default bullet style -- `setNumbering(numbering, indentLevel)`: Use a custom numbering format for the paragraph -- `style(name)`: Apply a named paragraph style -- `indent(start, hanging=0)`: Set the paragraph's indent level (in TWIPs) -- `spacing({before=0, after=0, line=0})`: Set the line and before/after on the paragraph. Before/after is measured in TWIPs, line is measured in 240ths of a line +- `heading1`, `heading2`, `heading3`, `heading4`, `heading5`, `title`: apply the appropriate style to the paragraph +- `left`, `center`, `right`, `justified`: set the paragraph's alignment +- `thematicBreak`, `pageBreak`: Insert a thick rule or a page break beneath the paragraph +- `leftTabStop(position)`: Add a left tab stop (measured in TWIPs from the left) +- `maxRightTabStop`: Add a right tab stop at the far right +- `bullet`: Use the default bullet style +- `setNumbering(numbering, indentLevel)`: Use a custom numbering format for the paragraph +- `style(name)`: Apply a named paragraph style +- `indent(start, hanging=0)`: Set the paragraph's indent level (in TWIPs) +- `spacing({before=0, after=0, line=0})`: Set the line and before/after on the paragraph. Before/after is measured in TWIPs, line is measured in 240ths of a line Paragraph styles have all the run formatting methods, except `style()`, and `left()`, `center()`, `right()`, `justified()`, `thematicBreak()`, `leftTabStop(position)`, `maxRightTabStop()`, `indent(start, hanging=0)`, and `spacing({before=0, after=0, line=0})` methods. @@ -49,10 +49,10 @@ Paragraph styles have all the run formatting methods, except `style()`, and `lef There are 4 items in `docx` that can be styled: -- Characters: Attributes that can change within a paragraph. e.g., bold, italics, etc. -- Paragraphs: Attributes like indent, text alignment, line spacing, etc. -- Tables: Border styles, table formats, etc. -- List items: These are the numbers and bullets that are automatically inserted +- Characters: Attributes that can change within a paragraph. e.g., bold, italics, etc. +- Paragraphs: Attributes like indent, text alignment, line spacing, etc. +- Tables: Border styles, table formats, etc. +- List items: These are the numbers and bullets that are automatically inserted There are a few different ways of styling this content in `docx`, which somewhat resemble the HTML/CSS approach. In order of greatest to lowest priority: @@ -137,12 +137,12 @@ const doc = new Document({ paragraph: { spacing: { before: 240, - after: 120 + after: 120, }, }, }, - ] - } + ], + }, }); ``` @@ -180,22 +180,22 @@ To determine the value of a styling property, you must first identify whether it The following properties are treated in a special manner; they're called toggle properties: -- Bold -- All caps -- Small caps -- Italics -- Single strike-through -- Hidden -- Imprint -- Emboss -- Character outline -- Character shadow +- Bold +- All caps +- Small caps +- Italics +- Single strike-through +- Hidden +- Imprint +- Emboss +- Character outline +- Character shadow For these properties, the rules state the following conflict resolution in case the property is specified at multiple points for the same item: -- Direct formatting trumps all if specified (either true or false) -- Otherwise, if the property is true in document defaults, the property is set to true -- Otherwise, the property's value is an XOR of its effective table, paragraph, and character values. (So specifying bold `true` on a table style and a paragraph style would result in non-bold text if a paragraph inside the table had that style) +- Direct formatting trumps all if specified (either true or false) +- Otherwise, if the property is true in document defaults, the property is set to true +- Otherwise, the property's value is an XOR of its effective table, paragraph, and character values. (So specifying bold `true` on a table style and a paragraph style would result in non-bold text if a paragraph inside the table had that style) ## Examples @@ -203,6 +203,6 @@ For these properties, the rules state the following conflict resolution in case Importing Images from file system path -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/2-declaritive-styles.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/2-declaritive-styles.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/2-declaritive-styles.ts_ diff --git a/docs/usage/styling-with-xml.md b/docs/usage/styling-with-xml.md index dd48286a9d..2f78ea4f15 100644 --- a/docs/usage/styling-with-xml.md +++ b/docs/usage/styling-with-xml.md @@ -9,15 +9,14 @@ ![image](https://user-images.githubusercontent.com/2917613/41195113-65edebfa-6c1f-11e8-97b4-77de2d60044a.png) ![image](https://user-images.githubusercontent.com/2917613/41195126-ca99c36c-6c1f-11e8-9e58-19e5f69b3b87.png) - *Note*: Font and color selection from the theme are currently not supported. + _Note_: Font and color selection from the theme are currently not supported. 3. You can even create a totally new `Style`: ![image](https://user-images.githubusercontent.com/2917613/41195135-f0f7862a-6c1f-11e8-8be4-dd6d8fe5be03.png) ![image](https://user-images.githubusercontent.com/2917613/41195139-0ec52130-6c20-11e8-8fae-f6b44b43fdf8.png) - *Note*: When selecting the style type, it is important to consider the component being used. - + _Note_: When selecting the style type, it is important to consider the component being used. 4. Save 5. Re-name the saved `.docx` file to `.zip` and un-zip diff --git a/docs/usage/symbols.md b/docs/usage/symbols.md index 08cf4ffa31..35bf2cc0a5 100644 --- a/docs/usage/symbols.md +++ b/docs/usage/symbols.md @@ -8,10 +8,7 @@ You can add multiple `symbol runs` in `Paragraphs` along with [text runs](usage/ import { Paragraph, TextRun, SymbolRun } from "docx"; const paragraph = new Paragraph({ - children: [ - new TextRun("This is a checkbox: "), - new SymbolRun("F071") - ], + children: [new TextRun("This is a checkbox: "), new SymbolRun("F071")], }); ``` diff --git a/docs/usage/table-of-contents.md b/docs/usage/table-of-contents.md index 4a88508bc8..4d57f84ca1 100644 --- a/docs/usage/table-of-contents.md +++ b/docs/usage/table-of-contents.md @@ -31,9 +31,9 @@ const doc = new Document({ heading: HeadingLevel.HEADING_1, pageBreakBefore: true, }), - ] - } - ] + ], + }, + ], }); ``` @@ -62,6 +62,6 @@ Here is the list of all options that you can use to generate your tables of cont ## Examples -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/28-table-of-contents.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/28-table-of-contents.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/28-table-of-contents.ts_ diff --git a/docs/usage/tables.md b/docs/usage/tables.md index 6455dd2549..6be25d281d 100644 --- a/docs/usage/tables.md +++ b/docs/usage/tables.md @@ -4,9 +4,9 @@ ## Intro -- `Tables` contain a list of `Rows` -- `Rows` contain a list of `TableCells` -- `TableCells` contain a list of `Paragraphs` and/or `Tables`. You can add `Tables` as tables can be nested inside each other +- `Tables` contain a list of `Rows` +- `Rows` contain a list of `TableCells` +- `TableCells` contain a list of `Paragraphs` and/or `Tables`. You can add `Tables` as tables can be nested inside each other Create a simple table like so: @@ -20,9 +20,11 @@ Then add the table in the `section` ```ts const doc = new Document({ - sections: [{ - children: [table], - }], + sections: [ + { + children: [table], + }, + ], }); ``` @@ -99,12 +101,12 @@ const table = new Table({ Here is a list of options you can add to the `table row`: -| Property | Type | Notes | -| ----------- | -------------------------------------- | -------- | -| children | `Array` | Required | -| cantSplit | `boolean` | Optional | -| tableHeader | `boolean` | Optional | -| height | `{ value: number, rule: HeightRule }` | Optional | +| Property | Type | Notes | +| ----------- | ------------------------------------- | -------- | +| children | `Array` | Required | +| cantSplit | `boolean` | Optional | +| tableHeader | `boolean` | Optional | +| height | `{ value: number, rule: HeightRule }` | Optional | ### Repeat row @@ -154,16 +156,16 @@ const tableRow = new TableRow({ ### Options -| Property | Type | Notes | -| ------------- | ----------------------------------- | ----------------------------------------------------------- | -| children | `Array` | Required. You can nest tables by adding a table into a cell | -| shading | `IShadingAttributesProperties` | Optional | -| margins | `ITableCellMarginOptions` | Optional | -| verticalAlign | `VerticalAlignTable` | Optional | -| columnSpan | `number` | Optional | -| rowSpan | `number` | Optional | -| borders | `BorderOptions` | Optional | -| width | `{ size: number type: WidthType }` | Optional | +| Property | Type | Notes | +| ------------- | ---------------------------------- | ----------------------------------------------------------- | +| children | `Array` | Required. You can nest tables by adding a table into a cell | +| shading | `IShadingAttributesProperties` | Optional | +| margins | `ITableCellMarginOptions` | Optional | +| verticalAlign | `VerticalAlignTable` | Optional | +| columnSpan | `number` | Optional | +| rowSpan | `number` | Optional | +| borders | `BorderOptions` | Optional | +| width | `{ size: number type: WidthType }` | Optional | #### Border Options @@ -346,7 +348,7 @@ const table = new Table({ ## Examples -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/4-basic-table.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/4-basic-table.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/4-basic-table.ts_ @@ -354,7 +356,7 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/4-basic-table.ts_ Example showing how to add colorful borders to tables -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/20-table-cell-borders.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/20-table-cell-borders.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/20-table-cell-borders.ts_ @@ -362,11 +364,11 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/20-table-cell-borders Example showing how to add images to tables -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/24-images-to-table-cell.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/24-images-to-table-cell.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/24-images-to-table-cell.ts_ -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/36-image-to-table-cell.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/36-image-to-table-cell.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/36-image-to-table-cell.ts_ @@ -374,7 +376,7 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/36-image-to-table-cel Example showing how align text in a table cell -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/31-tables.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/31-tables.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/31-tables.ts_ @@ -382,11 +384,11 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/31-tables.ts_ Example showing merging of columns and rows and shading -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/32-merge-and-shade-table-cells.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/32-merge-and-shade-table-cells.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/32-merge-and-shade-table-cells.ts_ -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/41-merge-table-cells-2.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/41-merge-table-cells-2.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/41-merge-table-cells-2.ts_ @@ -394,12 +396,12 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/41-merge-table-cells- Example showing merging of columns and rows -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/43-images-to-table-cell-2.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/43-images-to-table-cell-2.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/43-images-to-table-cell-2.ts_ ### Floating tables -[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/34-floating-tables.ts ':include') +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/34-floating-tables.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/34-floating-tables.ts_ diff --git a/docs/usage/templates.md b/docs/usage/templates.md new file mode 100644 index 0000000000..c2c7e5b1cb --- /dev/null +++ b/docs/usage/templates.md @@ -0,0 +1,283 @@ +# Templates + +Templates allow you to modify existing Word documents by replacing placeholder text with dynamic content. This is useful for generating documents from pre-designed layouts. + +!> For detailed information on the `patchDocument` function, see the [Patcher](usage/patcher.md) guide. + +## Overview + +The template workflow consists of: + +1. Create a Word document (.docx) with placeholder tags like `{{placeholder}}` +2. Use `patchDocument` to replace the placeholders with content +3. Export the modified document + +## Creating a Template + +Open your Word processor and create a document with placeholders: + +``` +Dear {{customer_name}}, + +Thank you for your order #{{order_number}}. + +Your items will ship on {{ship_date}}. + +Best regards, +{{company_name}} +``` + +?> Use double curly braces `{{}}` for placeholders. These will be replaced at runtime. + +## Basic Usage + +```ts +import * as fs from "fs"; +import { patchDocument, PatchType, TextRun } from "docx"; + +patchDocument({ + outputType: "nodebuffer", + data: fs.readFileSync("template.docx"), + patches: { + customer_name: { + type: PatchType.PARAGRAPH, + children: [new TextRun("John Smith")], + }, + order_number: { + type: PatchType.PARAGRAPH, + children: [new TextRun("12345")], + }, + ship_date: { + type: PatchType.PARAGRAPH, + children: [new TextRun("January 15, 2024")], + }, + company_name: { + type: PatchType.PARAGRAPH, + children: [new TextRun("Acme Corp")], + }, + }, +}).then((doc) => { + fs.writeFileSync("output.docx", doc); +}); +``` + +## Patch Types + +### PARAGRAPH Type + +Use `PatchType.PARAGRAPH` to replace with inline content (TextRun, images, hyperlinks): + +```ts +my_patch: { + type: PatchType.PARAGRAPH, + children: [ + new TextRun("Hello "), + new TextRun({ text: "World", bold: true }), + ], +} +``` + +### DOCUMENT Type + +Use `PatchType.DOCUMENT` to replace with block-level content (paragraphs, tables): + +```ts +my_patch: { + type: PatchType.DOCUMENT, + children: [ + new Paragraph("First paragraph"), + new Paragraph("Second paragraph"), + new Table({ + rows: [/* ... */], + }), + ], +} +``` + +## Advanced Patches + +### Images + +```ts +import { ImageRun, PatchType } from "docx"; + +image_placeholder: { + type: PatchType.PARAGRAPH, + children: [ + new ImageRun({ + type: "png", + data: fs.readFileSync("./logo.png"), + transformation: { width: 100, height: 50 }, + }), + ], +} +``` + +### Hyperlinks + +```ts +import { ExternalHyperlink, PatchType, TextRun } from "docx"; + +link_placeholder: { + type: PatchType.PARAGRAPH, + children: [ + new ExternalHyperlink({ + children: [ + new TextRun({ + text: "Visit our website", + style: "Hyperlink", + }), + ], + link: "https://example.com", + }), + ], +} +``` + +### Tables + +```ts +import { Paragraph, PatchType, Table, TableCell, TableRow } from "docx"; + +table_placeholder: { + type: PatchType.DOCUMENT, + children: [ + new Table({ + rows: [ + new TableRow({ + children: [ + new TableCell({ children: [new Paragraph("Item")] }), + new TableCell({ children: [new Paragraph("Price")] }), + ], + }), + new TableRow({ + children: [ + new TableCell({ children: [new Paragraph("Widget")] }), + new TableCell({ children: [new Paragraph("$9.99")] }), + ], + }), + ], + }), + ], +} +``` + +## Preserving Styles + +Set `keepOriginalStyles: true` to preserve the formatting of the placeholder text: + +```ts +patchDocument({ + outputType: "nodebuffer", + data: fs.readFileSync("template.docx"), + keepOriginalStyles: true, // Preserve template formatting + patches: { + // ... + }, +}); +``` + +## Headers and Footers + +Placeholders in headers and footers are also replaced: + +```ts +header_title: { + type: PatchType.PARAGRAPH, + children: [new TextRun("Company Report 2024")], +}, +footer_text: { + type: PatchType.PARAGRAPH, + children: [new TextRun("Confidential")], +} +``` + +## Complete Example + +Invoice template: + +```ts +import * as fs from "fs"; +import { ExternalHyperlink, ImageRun, Paragraph, patchDocument, PatchType, Table, TableCell, TableRow, TextRun } from "docx"; + +// Invoice data +const invoice = { + number: "INV-2024-001", + date: "January 10, 2024", + customer: "Acme Corporation", + items: [ + { name: "Widget A", qty: 5, price: 10.0 }, + { name: "Widget B", qty: 3, price: 15.0 }, + ], + total: 95.0, +}; + +patchDocument({ + outputType: "nodebuffer", + data: fs.readFileSync("invoice-template.docx"), + patches: { + invoice_number: { + type: PatchType.PARAGRAPH, + children: [new TextRun(invoice.number)], + }, + invoice_date: { + type: PatchType.PARAGRAPH, + children: [new TextRun(invoice.date)], + }, + customer_name: { + type: PatchType.PARAGRAPH, + children: [new TextRun(invoice.customer)], + }, + line_items: { + type: PatchType.DOCUMENT, + children: [ + new Table({ + rows: [ + new TableRow({ + children: [ + new TableCell({ children: [new Paragraph("Item")] }), + new TableCell({ children: [new Paragraph("Qty")] }), + new TableCell({ children: [new Paragraph("Price")] }), + ], + }), + ...invoice.items.map( + (item) => + new TableRow({ + children: [ + new TableCell({ children: [new Paragraph(item.name)] }), + new TableCell({ children: [new Paragraph(String(item.qty))] }), + new TableCell({ children: [new Paragraph(`$${item.price.toFixed(2)}`)] }), + ], + }), + ), + ], + }), + ], + }, + total: { + type: PatchType.PARAGRAPH, + children: [ + new TextRun({ + text: `$${invoice.total.toFixed(2)}`, + bold: true, + }), + ], + }, + }, +}).then((doc) => { + fs.writeFileSync("invoice-output.docx", doc); +}); +``` + +## Tips + +- **Placeholder naming**: Use descriptive names like `customer_name` instead of `x1` +- **Testing**: Open the template in Word to verify placeholders are formatted as plain text +- **Complex layouts**: Design the layout in Word, then add placeholders where content varies +- **Reusable templates**: Store templates in a dedicated folder for easy access + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/85-template-document.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/85-template-document.ts_ diff --git a/docs/usage/text-box.md b/docs/usage/text-box.md index 79cf6400e2..7288273e14 100644 --- a/docs/usage/text-box.md +++ b/docs/usage/text-box.md @@ -1,26 +1,208 @@ # Text Box -Similar `Text Frames`, but the difference being that it is `VML` `Shape` based. +Similar to `Text Frames`, but the difference being that it is `VML` `Shape` based. -!> `Text Boxes` requires an understanding of [Paragraphs](usage/paragraph.md). +!> `Text Boxes` require an understanding of [Paragraphs](usage/paragraph.md). > `Text boxes` are paragraphs of text in a document which are positioned in a separate region or frame in the document, and can be positioned with a specific size and position relative to non-frame paragraphs in the current document. -## Intro +## Basic Text Box -To make a `Text Box`, simply create a `Textbox` object inside the `Document`: +Create a text box with basic content: + +```ts +import { Document, Paragraph, TextRun, Textbox } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + new Textbox({ + children: [ + new Paragraph({ + children: [new TextRun("Hello from a textbox!")], + }), + ], + style: { + width: "200pt", + height: "100pt", + }, + }), + ], + }, + ], +}); +``` + +## Textbox Options + +| Property | Type | Notes | Description | +| --------- | --------------- | -------- | ---------------------------- | +| children | `Paragraph[]` | Required | Content inside the textbox | +| style | `ITextboxStyle` | Optional | Positioning and size options | +| alignment | `string` | Optional | Horizontal alignment | + +## Sizing + +### Fixed Size ```ts new Textbox({ - alignment: "center", - children: [ - new Paragraph({ - children: [new TextRun("Hi i'm a textbox!")], - }), - ], + children: [new Paragraph("Fixed size textbox")], + style: { + width: "200pt", + height: "100pt", + }, +}); +``` + +### Auto Height + +```ts +new Textbox({ + children: [new Paragraph("Auto height based on content")], style: { width: "200pt", height: "auto", }, }); ``` + +## Alignment + +Align the textbox horizontally: + +```ts +new Textbox({ + alignment: "center", + children: [new Paragraph("Centered textbox")], + style: { + width: "200pt", + height: "auto", + }, +}); +``` + +Available alignment values: + +- `"left"` - Align to left margin +- `"center"` - Center on page +- `"right"` - Align to right margin + +## Multiple Paragraphs + +Text boxes can contain multiple paragraphs: + +```ts +new Textbox({ + children: [ + new Paragraph({ + text: "Title", + heading: HeadingLevel.HEADING_2, + }), + new Paragraph("First paragraph of content."), + new Paragraph("Second paragraph of content."), + ], + style: { + width: "300pt", + height: "auto", + }, +}); +``` + +## Styled Content + +Apply formatting to text within the textbox: + +```ts +new Textbox({ + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun({ + text: "Important Notice", + bold: true, + size: 28, + }), + ], + }), + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [new TextRun("This is highlighted information")], + }), + ], + style: { + width: "250pt", + height: "auto", + }, +}); +``` + +## Complete Example + +Sidebar callout box: + +```ts +import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun, Textbox } from "docx"; +import * as fs from "fs"; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph("Main document content goes here..."), + new Textbox({ + alignment: "right", + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun({ + text: "Did You Know?", + bold: true, + color: "2F5496", + }), + ], + }), + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun({ + text: "docx can generate Word documents in both Node.js and browsers!", + italics: true, + }), + ], + }), + ], + style: { + width: "180pt", + height: "auto", + }, + }), + new Paragraph("More document content continues..."), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("document.docx", buffer); +}); +``` + +## Text Box vs Text Frame + +| Feature | Text Box | Text Frame | +| ------------- | ------------------- | ----------------- | +| Based on | VML Shape | Paragraph framing | +| Positioning | More flexible | Limited | +| Compatibility | Older Word versions | Modern Word | + +For most use cases, **Text Frames** are recommended. See [Text Frames](usage/text-frames.md) for more information. + +## Demo + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/94-texbox.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/94-texbox.ts_ diff --git a/package.json b/package.json index 2c1f2c1823..c9f4ba511e 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "predemo": "npm run build", "demo": "tsx ./demo/index.ts", "typedoc": "typedoc src/index.ts --tsconfig tsconfig.typedoc.json", - "prettier": "prettier -l \"{src,scripts,demo}/**/*.{ts,html}\"", + "prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"", "prettier:fix": "npm run prettier -- --write", "cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"", "serve.docs": "cd docs && docsify serve", diff --git a/src/export/formatter.ts b/src/export/formatter.ts index 694c97f9b4..f052ccbde2 100644 --- a/src/export/formatter.ts +++ b/src/export/formatter.ts @@ -1,6 +1,33 @@ +/** + * Formatter module for converting XML components to serializable objects. + * + * @module + */ import { BaseXmlComponent, IContext, IXmlableObject } from "@file/xml-components"; +/** + * Converts XML components into serializable objects ready for XML generation. + * + * The Formatter is responsible for preparing XML components for serialization by calling + * their prepForXml method with the appropriate context. This is a critical step in the + * export pipeline that transforms the declarative API objects into XML-compatible structures. + * + * @example + * ```typescript + * const formatter = new Formatter(); + * const paragraph = new Paragraph("Hello World"); + * const xmlObject = formatter.format(paragraph, context); + * ``` + */ export class Formatter { + /** + * Formats an XML component into a serializable object. + * + * @param input - The XML component to format + * @param context - The context containing file state and relationships + * @returns A serializable XML object structure + * @throws Error if the component cannot be formatted correctly + */ public format(input: BaseXmlComponent, context: IContext = { stack: [] } as unknown as IContext): IXmlableObject { const output = input.prepForXml(context); diff --git a/src/export/index.ts b/src/export/index.ts index 042cb4366d..a5ba49c04d 100644 --- a/src/export/index.ts +++ b/src/export/index.ts @@ -1 +1,6 @@ +/** + * Export module exports. + * + * @module + */ export * from "./packer/packer"; diff --git a/src/export/packer/image-replacer.ts b/src/export/packer/image-replacer.ts index 31415877f0..9866715299 100644 --- a/src/export/packer/image-replacer.ts +++ b/src/export/packer/image-replacer.ts @@ -1,6 +1,33 @@ +/** + * Image replacer module for substituting image placeholders in XML. + * + * @module + */ import { IMediaData, Media } from "@file/media"; +/** + * Replaces image placeholders with relationship IDs in XML content. + * + * During document compilation, images are referenced using placeholder tokens + * like {image1.png}. This class replaces those placeholders with the actual + * relationship IDs used in the OOXML structure. + * + * @example + * ```typescript + * const replacer = new ImageReplacer(); + * const mediaData = replacer.getMediaData(xmlString, media); + * const updatedXml = replacer.replace(xmlString, mediaData, 1); + * ``` + */ export class ImageReplacer { + /** + * Replaces image placeholder tokens with relationship IDs. + * + * @param xmlData - The XML string containing image placeholders + * @param mediaData - Array of media data to replace + * @param offset - Starting offset for relationship IDs + * @returns XML string with placeholders replaced by relationship IDs + */ public replace(xmlData: string, mediaData: readonly IMediaData[], offset: number): string { let currentXmlData = xmlData; @@ -11,6 +38,13 @@ export class ImageReplacer { return currentXmlData; } + /** + * Extracts media data referenced in the XML content. + * + * @param xmlData - The XML string to search for media references + * @param media - The media collection to search within + * @returns Array of media data found in the XML + */ public getMediaData(xmlData: string, media: Media): readonly IMediaData[] { return media.Array.filter((image) => xmlData.search(`{${image.fileName}}`) > 0); } diff --git a/src/export/packer/next-compiler.ts b/src/export/packer/next-compiler.ts index 9f2e41e062..cc655b0d5a 100644 --- a/src/export/packer/next-compiler.ts +++ b/src/export/packer/next-compiler.ts @@ -1,3 +1,8 @@ +/** + * Compiler module for converting File objects into OOXML ZIP archives. + * + * @module + */ import JSZip from "jszip"; import xml from "xml"; @@ -9,45 +14,110 @@ import { ImageReplacer } from "./image-replacer"; import { NumberingReplacer } from "./numbering-replacer"; import { PrettifyType } from "./packer"; +/** + * Represents a serialized XML file with its path in the OOXML package. + * + * @property data - The XML content as a string + * @property path - The file path within the ZIP archive (e.g., "word/document.xml") + */ export type IXmlifyedFile = { readonly data: string; readonly path: string; }; +/** + * Complete mapping of all XML files in an OOXML document package. + * + * This type represents the full structure of a .docx file, including the main + * document, styles, relationships, headers, footers, and metadata files. + */ type IXmlifyedFileMapping = { + /** Main document content (word/document.xml) */ readonly Document: IXmlifyedFile; + /** Style definitions (word/styles.xml) */ readonly Styles: IXmlifyedFile; + /** Core document properties (docProps/core.xml) */ readonly Properties: IXmlifyedFile; + /** Numbering definitions (word/numbering.xml) */ readonly Numbering: IXmlifyedFile; + /** Document relationships (word/_rels/document.xml.rels) */ readonly Relationships: IXmlifyedFile; + /** Package-level relationships (_rels/.rels) */ readonly FileRelationships: IXmlifyedFile; + /** Header content files */ readonly Headers: readonly IXmlifyedFile[]; + /** Footer content files */ readonly Footers: readonly IXmlifyedFile[]; + /** Header relationship files */ readonly HeaderRelationships: readonly IXmlifyedFile[]; + /** Footer relationship files */ readonly FooterRelationships: readonly IXmlifyedFile[]; + /** Content types mapping ([Content_Types].xml) */ readonly ContentTypes: IXmlifyedFile; + /** Custom document properties (docProps/custom.xml) */ readonly CustomProperties: IXmlifyedFile; + /** Application properties (docProps/app.xml) */ readonly AppProperties: IXmlifyedFile; + /** Footnotes content (word/footnotes.xml) */ readonly FootNotes: IXmlifyedFile; + /** Footnotes relationships (word/_rels/footnotes.xml.rels) */ readonly FootNotesRelationships: IXmlifyedFile; + /** Document settings (word/settings.xml) */ readonly Settings: IXmlifyedFile; + /** Comments content (word/comments.xml) */ readonly Comments?: IXmlifyedFile; + /** Comments relationships (word/_rels/comments.xml.rels) */ readonly CommentsRelationships?: IXmlifyedFile; + /** Font table (word/fontTable.xml) */ readonly FontTable?: IXmlifyedFile; + /** Font table relationships (word/_rels/fontTable.xml.rels) */ readonly FontTableRelationships?: IXmlifyedFile; }; +/** + * Compiles File objects into OOXML-compliant ZIP archives. + * + * The Compiler is responsible for converting the internal document representation + * into the complete set of XML files required for a .docx document, managing + * relationships, images, fonts, and all other document components. + * + * @example + * ```typescript + * const compiler = new Compiler(); + * const zip = compiler.compile(file, PrettifyType.WITH_2_BLANKS); + * ``` + */ export class Compiler { private readonly formatter: Formatter; private readonly imageReplacer: ImageReplacer; private readonly numberingReplacer: NumberingReplacer; + /** + * Creates a new Compiler instance. + * + * Initializes the formatter and replacer utilities used during compilation. + */ public constructor() { this.formatter = new Formatter(); this.imageReplacer = new ImageReplacer(); this.numberingReplacer = new NumberingReplacer(); } + /** + * Compiles a File object into a JSZip archive containing the complete OOXML package. + * + * This method orchestrates the entire compilation process: + * - Converts all document components to XML + * - Manages image and numbering placeholder replacements + * - Creates relationship files + * - Packages fonts and media files + * - Assembles everything into a ZIP archive + * + * @param file - The document to compile + * @param prettifyXml - Optional XML formatting style + * @param overrides - Optional custom XML file overrides + * @returns A JSZip instance containing the complete .docx package + */ public compile( file: File, prettifyXml?: (typeof PrettifyType)[keyof typeof PrettifyType], diff --git a/src/export/packer/numbering-replacer.ts b/src/export/packer/numbering-replacer.ts index 4391fa9361..cce09093dc 100644 --- a/src/export/packer/numbering-replacer.ts +++ b/src/export/packer/numbering-replacer.ts @@ -1,6 +1,34 @@ +/** + * Numbering replacer module for substituting numbering placeholders in XML. + * + * @module + */ import { ConcreteNumbering } from "@file/numbering"; +/** + * Replaces numbering instance placeholders with actual numbering IDs in XML content. + * + * Numbering instances (for bullets and numbered lists) use placeholder tokens during + * compilation. This class replaces those placeholders with the final numbering IDs + * that reference the numbering definitions in numbering.xml. + * + * @example + * ```typescript + * const replacer = new NumberingReplacer(); + * const updatedXml = replacer.replace(xmlString, concreteNumberings); + * ``` + */ export class NumberingReplacer { + /** + * Replaces numbering placeholder tokens with actual numbering IDs. + * + * Placeholder format: {reference-instance} where reference identifies the + * numbering definition and instance is the specific usage. + * + * @param xmlData - The XML string containing numbering placeholders + * @param concreteNumberings - Array of concrete numbering instances to replace + * @returns XML string with placeholders replaced by numbering IDs + */ public replace(xmlData: string, concreteNumberings: readonly ConcreteNumbering[]): string { let currentXmlData = xmlData; diff --git a/src/export/packer/packer.ts b/src/export/packer/packer.ts index 31994b0046..47b95cfa4e 100644 --- a/src/export/packer/packer.ts +++ b/src/export/packer/packer.ts @@ -1,3 +1,8 @@ +/** + * Packer module for exporting documents to various output formats. + * + * @module + */ import { Stream } from "stream"; import { File } from "@file/file"; @@ -6,13 +11,19 @@ import { OutputByType, OutputType } from "@util/output-type"; import { Compiler, IXmlifyedFile } from "./next-compiler"; /** - * Use blanks to prettify + * Prettify options for formatting XML output. + * + * Controls the indentation style used when formatting the generated XML. + * Prettified output is more human-readable but results in larger file sizes. */ export const PrettifyType = { + /** No prettification (smallest file size) */ NONE: "", + /** Indent with 2 spaces */ WITH_2_BLANKS: " ", + /** Indent with 4 spaces */ WITH_4_BLANKS: " ", - + /** Indent with tab character */ WITH_TAB: "\t", } as const; @@ -21,7 +32,35 @@ const convertPrettifyType = ( ): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined => prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify; +/** + * Exports documents to various output formats. + * + * The Packer class provides static methods to convert a File object into different + * output formats such as Buffer, Blob, string, or stream. It handles the compilation + * of the document structure into OOXML format and compression into a .docx ZIP archive. + * + * @example + * ```typescript + * // Export to buffer (Node.js) + * const buffer = await Packer.toBuffer(doc); + * + * // Export to blob (browser) + * const blob = await Packer.toBlob(doc); + * + * // Export with prettified XML + * const buffer = await Packer.toBuffer(doc, PrettifyType.WITH_2_BLANKS); + * ``` + */ export class Packer { + /** + * Exports a document to the specified output format. + * + * @param file - The document to export + * @param type - The output format type (e.g., "nodebuffer", "blob", "string") + * @param prettify - Whether to prettify the XML output (boolean or PrettifyType) + * @param overrides - Optional array of file overrides for custom XML content + * @returns A promise resolving to the exported document in the specified format + */ // eslint-disable-next-line require-await public static async pack( file: File, @@ -37,6 +76,14 @@ export class Packer { }); } + /** + * Exports a document to a string representation. + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A promise resolving to the document as a string + */ public static toString( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], @@ -45,6 +92,14 @@ export class Packer { return Packer.pack(file, "string", prettify, overrides); } + /** + * Exports a document to a Node.js Buffer. + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A promise resolving to the document as a Buffer + */ public static toBuffer( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], @@ -53,6 +108,14 @@ export class Packer { return Packer.pack(file, "nodebuffer", prettify, overrides); } + /** + * Exports a document to a base64-encoded string. + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A promise resolving to the document as a base64 string + */ public static toBase64String( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], @@ -61,6 +124,14 @@ export class Packer { return Packer.pack(file, "base64", prettify, overrides); } + /** + * Exports a document to a Blob (for browser environments). + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A promise resolving to the document as a Blob + */ public static toBlob( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], @@ -69,6 +140,14 @@ export class Packer { return Packer.pack(file, "blob", prettify, overrides); } + /** + * Exports a document to an ArrayBuffer. + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A promise resolving to the document as an ArrayBuffer + */ public static toArrayBuffer( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], @@ -77,6 +156,14 @@ export class Packer { return Packer.pack(file, "arraybuffer", prettify, overrides); } + /** + * Exports a document to a Node.js Stream. + * + * @param file - The document to export + * @param prettify - Whether to prettify the XML output + * @param overrides - Optional array of file overrides + * @returns A readable stream containing the document data + */ public static toStream( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], diff --git a/src/file/app-properties/app-properties-attributes.ts b/src/file/app-properties/app-properties-attributes.ts index fcfd5aacae..52eafd6fd5 100644 --- a/src/file/app-properties/app-properties-attributes.ts +++ b/src/file/app-properties/app-properties-attributes.ts @@ -1,7 +1,24 @@ +/** + * App Properties Attributes module for WordprocessingML documents. + * + * Provides namespace attributes for extended document properties. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * XML namespace attributes for the app properties element. + * + * @property xmlns - Main namespace for extended properties + * @property vt - Namespace for variant types + */ export class AppPropertiesAttributes extends XmlAttributeComponent<{ + /** Main namespace for extended properties */ readonly xmlns: string; + /** Namespace for variant types */ readonly vt: string; }> { protected readonly xmlKeys = { diff --git a/src/file/app-properties/app-properties.ts b/src/file/app-properties/app-properties.ts index 715d95fa1d..fe5e28cf1d 100644 --- a/src/file/app-properties/app-properties.ts +++ b/src/file/app-properties/app-properties.ts @@ -1,7 +1,49 @@ +/** + * App Properties module for WordprocessingML documents. + * + * Provides support for extended document properties specific to Office applications. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { AppPropertiesAttributes } from "./app-properties-attributes"; +/** + * Represents the extended application properties of a WordprocessingML document. + * + * Extended properties contain application-specific metadata such as total editing time, + * word count, character count, and other Office-specific information. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const appProps = new AppProperties(); + * ``` + */ export class AppProperties extends XmlComponent { public constructor() { super("Properties"); diff --git a/src/file/border/border.ts b/src/file/border/border.ts index 9ca63426bf..5ed3b8aad7 100644 --- a/src/file/border/border.ts +++ b/src/file/border/border.ts @@ -1,27 +1,44 @@ -// Note that the border type is identical in all places, -// regardless of where it's used like paragraph/table/etc. -// PageBorders are a superset, but we're not using any of those extras. -// -// http://officeopenxml.com/WPborders.php -// http://officeopenxml.com/WPtableBorders.php -// http://officeopenxml.com/WPtableCellProperties-Borders.php -// http://officeopenxml.com/WPsectionBorders.php -// -// This describes the CT_Border type. -// -// -// -// -// -// -// -// -// -// -// +/** + * Border module for WordprocessingML documents. + * + * Borders are used in multiple contexts (paragraphs, tables, table cells, sections) + * and share the same CT_Border type definition. This module provides the BorderElement + * class and BorderStyle constants used throughout the document structure. + * + * Reference: http://officeopenxml.com/WPborders.php + * + * @see http://officeopenxml.com/WPtableBorders.php + * @see http://officeopenxml.com/WPtableCellProperties-Borders.php + * @see http://officeopenxml.com/WPsectionBorders.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { eighthPointMeasureValue, hexColorValue, pointMeasureValue } from "@util/values"; +/** + * Options for configuring a border element. + * + * @property style - The border style (single, dashed, dotted, etc.) + * @property color - Border color in hex format (e.g., "FF00AA" for purple) + * @property size - Border thickness in eighths of a point (1/8 pt) + * @property space - Spacing offset from the content in points + */ export type IBorderOptions = { readonly style: (typeof BorderStyle)[keyof typeof BorderStyle]; /** Border color, in hex (eg 'FF00AA') */ @@ -32,6 +49,24 @@ export type IBorderOptions = { readonly space?: number; }; +/** + * Represents a border element in a WordprocessingML document. + * + * BorderElement is used to create border specifications for paragraphs, + * tables, table cells, and sections. The element name is specified + * during construction to create different border types (top, bottom, left, right, etc.). + * + * @example + * ```typescript + * // Create a top border + * new BorderElement("w:top", { + * style: BorderStyle.SINGLE, + * color: "FF0000", + * size: 24, + * space: 1, + * }); + * ``` + */ export class BorderElement extends XmlComponent { public constructor(elementName: string, { color, size, space, style }: IBorderOptions) { super(elementName); diff --git a/src/file/border/index.ts b/src/file/border/index.ts index cfae779c98..e4df7137b9 100644 --- a/src/file/border/index.ts +++ b/src/file/border/index.ts @@ -1 +1,6 @@ +/** + * Border module exports. + * + * @module + */ export * from "./border"; diff --git a/src/file/checkbox/checkbox-symbol.ts b/src/file/checkbox/checkbox-symbol.ts index 7e172c3141..9b54d20e54 100644 --- a/src/file/checkbox/checkbox-symbol.ts +++ b/src/file/checkbox/checkbox-symbol.ts @@ -1,14 +1,25 @@ -// This represents element type CT_SdtCheckboxSymbol element -// -// -// -// - +/** + * CheckBox symbol module for WordprocessingML documents. + * + * Provides XML components for checkbox symbol states. + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { shortHexNumber } from "@util/values"; +/** + * Attributes for a checkbox symbol element. + * + * Represents the font and value attributes for checkbox states. + * + * @property val - Hexadecimal character code for the symbol + * @property symbolfont - Font family for rendering the symbol + */ class CheckboxSymbolAttributes extends XmlAttributeComponent<{ + /** Hexadecimal character code for the symbol. */ readonly val?: string | number | boolean; + /** Font family for rendering the symbol. */ readonly symbolfont?: string; }> { protected readonly xmlKeys = { @@ -17,6 +28,32 @@ class CheckboxSymbolAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents a checkbox symbol element (checked or unchecked state). + * + * This element defines the appearance of a checkbox in a particular state, + * specifying the Unicode character and font to render. + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Checked state symbol + * new CheckBoxSymbolElement("w14:checkedState", "2612", "MS Gothic"); + * + * // Unchecked state symbol + * new CheckBoxSymbolElement("w14:uncheckedState", "2610", "MS Gothic"); + * + * // Symbol without explicit font + * new CheckBoxSymbolElement("w14:checked", "1"); + * ``` + */ export class CheckBoxSymbolElement extends XmlComponent { public constructor(name: string, val: string, font?: string) { super(name); diff --git a/src/file/checkbox/checkbox-util.ts b/src/file/checkbox/checkbox-util.ts index 010405e436..1d2b79aa86 100644 --- a/src/file/checkbox/checkbox-util.ts +++ b/src/file/checkbox/checkbox-util.ts @@ -1,27 +1,79 @@ -// -// -// -// -// -// -// -// - +/** + * CheckBox utility module for WordprocessingML documents. + * + * Provides the internal XML structure for checkbox content controls. + * + * @module + */ import { CheckBoxSymbolElement } from "@file/checkbox/checkbox-symbol"; import { XmlComponent } from "@file/xml-components"; +/** + * Configuration for a checkbox symbol state (checked or unchecked). + * + * @property value - Hexadecimal character code for the symbol (e.g., "2612" for ☒) + * @property font - Font family to use for rendering the symbol + */ export type ICheckboxSymbolProperties = { + /** Hexadecimal character code for the symbol (e.g., "2612" for ☒). */ readonly value?: string; + /** Font family to use for rendering the symbol. */ readonly font?: string; }; +/** + * Options for configuring a checkbox control. + * + * @property alias - Display name for the checkbox control + * @property checked - Whether the checkbox is initially checked + * @property checkedState - Symbol properties for the checked state + * @property uncheckedState - Symbol properties for the unchecked state + */ export type ICheckboxSymbolOptions = { + /** Display name for the checkbox control. */ readonly alias?: string; + /** Whether the checkbox is initially checked. */ readonly checked?: boolean; + /** Symbol properties for the checked state. */ readonly checkedState?: ICheckboxSymbolProperties; + /** Symbol properties for the unchecked state. */ readonly uncheckedState?: ICheckboxSymbolProperties; }; +/** + * Represents the checkbox element within a structured document tag. + * + * This class generates the w14:checkbox element that defines the checkbox behavior, + * including its checked state and the symbols used for checked and unchecked states. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Default checkbox (unchecked with default symbols) + * new CheckBoxUtil(); + * + * // Checked checkbox with defaults + * new CheckBoxUtil({ checked: true }); + * + * // Custom symbols + * new CheckBoxUtil({ + * checked: false, + * checkedState: { value: "2611", font: "Wingdings" }, + * uncheckedState: { value: "2610", font: "Wingdings" }, + * }); + * ``` + */ export class CheckBoxUtil extends XmlComponent { private readonly DEFAULT_UNCHECKED_SYMBOL: string = "2610"; private readonly DEFAULT_CHECKED_SYMBOL: string = "2612"; diff --git a/src/file/checkbox/checkbox.ts b/src/file/checkbox/checkbox.ts index dc17b3f555..ca1feeafd3 100644 --- a/src/file/checkbox/checkbox.ts +++ b/src/file/checkbox/checkbox.ts @@ -17,13 +17,38 @@ import { CheckBoxUtil, ICheckboxSymbolOptions } from "./checkbox-util"; * Represents an interactive checkbox in a WordprocessingML document. * * CheckBox creates a content control with checkbox functionality, - * displaying a checked or unchecked symbol based on its state. + * displaying a checked or unchecked symbol based on its state. The checkbox + * is implemented using structured document tags (w:sdt) with checkbox-specific + * properties. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` * * @example * ```typescript + * // Simple checkbox + * new CheckBox({ checked: true }); + * + * // Checkbox with custom alias + * new CheckBox({ + * checked: false, + * alias: "Accept Terms", + * }); + * + * // Checkbox with custom symbols * new CheckBox({ * checked: true, - * alias: "Accept Terms", + * checkedState: { value: "2611", font: "Wingdings" }, + * uncheckedState: { value: "2610", font: "Wingdings" }, * }); * ``` */ diff --git a/src/file/checkbox/index.ts b/src/file/checkbox/index.ts index 9af5c31e28..5eb7097208 100644 --- a/src/file/checkbox/index.ts +++ b/src/file/checkbox/index.ts @@ -1,3 +1,8 @@ +/** + * CheckBox module exports for WordprocessingML documents. + * + * @module + */ export * from "./checkbox-util"; export * from "./checkbox-symbol"; export * from "./checkbox"; diff --git a/src/file/content-types/content-types-attributes.ts b/src/file/content-types/content-types-attributes.ts index 4b5eb4a4f9..ebaeba9a73 100644 --- a/src/file/content-types/content-types-attributes.ts +++ b/src/file/content-types/content-types-attributes.ts @@ -1,6 +1,19 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for the Types (Content Types) element. + * + * Defines the XML namespace for the content types part. + * + * @example + * ```typescript + * new ContentTypeAttributes({ + * xmlns: "http://schemas.openxmlformats.org/package/2006/content-types" + * }); + * ``` + */ export class ContentTypeAttributes extends XmlAttributeComponent<{ + /** XML namespace for content types */ readonly xmlns?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/content-types/content-types.ts b/src/file/content-types/content-types.ts index eed207cf6e..d10dcdf776 100644 --- a/src/file/content-types/content-types.ts +++ b/src/file/content-types/content-types.ts @@ -21,6 +21,13 @@ import { Override } from "./override/override"; * MIME content types, enabling applications to process each part correctly. * * Reference: http://officeopenxml.com/anatomyofOOXML.php + * + * @example + * ```typescript + * const contentTypes = new ContentTypes(); + * contentTypes.addHeader(1); // Add header1.xml + * contentTypes.addFooter(1); // Add footer1.xml + * ``` */ export class ContentTypes extends XmlComponent { public constructor() { @@ -57,12 +64,22 @@ export class ContentTypes extends XmlComponent { this.root.push(new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", "/word/fontTable.xml")); } + /** + * Registers a footer part in the content types. + * + * @param index - Footer index number (e.g., 1 for footer1.xml) + */ public addFooter(index: number): void { this.root.push( new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", `/word/footer${index}.xml`), ); } + /** + * Registers a header part in the content types. + * + * @param index - Header index number (e.g., 1 for header1.xml) + */ public addHeader(index: number): void { this.root.push( new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", `/word/header${index}.xml`), diff --git a/src/file/content-types/default/default-attributes.ts b/src/file/content-types/default/default-attributes.ts index 66cc118b6d..66f39ce3cf 100644 --- a/src/file/content-types/default/default-attributes.ts +++ b/src/file/content-types/default/default-attributes.ts @@ -1,7 +1,22 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for a Default content type element. + * + * Defines the mapping between a file extension and its MIME content type. + * + * @example + * ```typescript + * new DefaultAttributes({ + * contentType: "image/png", + * extension: "png" + * }); + * ``` + */ export class DefaultAttributes extends XmlAttributeComponent<{ + /** MIME content type for files with this extension */ readonly contentType: string; + /** File extension (without the dot) */ readonly extension?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/content-types/default/default.ts b/src/file/content-types/default/default.ts index eba4d9e149..21cee260c9 100644 --- a/src/file/content-types/default/default.ts +++ b/src/file/content-types/default/default.ts @@ -2,6 +2,22 @@ import { XmlComponent } from "@file/xml-components"; import { DefaultAttributes } from "./default-attributes"; +/** + * Represents a default content type mapping by file extension. + * + * Default elements map file extensions (e.g., "png", "xml") to MIME content types. + * This tells the package reader what type of content to expect for files with + * a given extension. + * + * @example + * ```typescript + * // Map .png files to image/png content type + * new Default("image/png", "png"); + * + * // Map .xml files to application/xml content type + * new Default("application/xml", "xml"); + * ``` + */ export class Default extends XmlComponent { public constructor(contentType: string, extension?: string) { super("Default"); diff --git a/src/file/content-types/override/override-attributes.ts b/src/file/content-types/override/override-attributes.ts index 974ef09e4d..0d9fac572e 100644 --- a/src/file/content-types/override/override-attributes.ts +++ b/src/file/content-types/override/override-attributes.ts @@ -1,7 +1,22 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for an Override content type element. + * + * Defines the content type override for a specific part path. + * + * @example + * ```typescript + * new OverrideAttributes({ + * contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", + * partName: "/word/document.xml" + * }); + * ``` + */ export class OverrideAttributes extends XmlAttributeComponent<{ + /** MIME content type for this specific part */ readonly contentType: string; + /** Full path to the part in the package (e.g., "/word/document.xml") */ readonly partName?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/content-types/override/override.ts b/src/file/content-types/override/override.ts index 511edd95a6..1c8744718e 100644 --- a/src/file/content-types/override/override.ts +++ b/src/file/content-types/override/override.ts @@ -2,6 +2,28 @@ import { XmlComponent } from "@file/xml-components"; import { OverrideAttributes } from "./override-attributes"; +/** + * Represents a content type override for a specific part. + * + * Override elements map specific part paths to MIME content types, + * taking precedence over default extension mappings. This is used for + * important parts like document.xml, styles.xml, etc. + * + * @example + * ```typescript + * // Override content type for the main document part + * new Override( + * "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", + * "/word/document.xml" + * ); + * + * // Override for a header part + * new Override( + * "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", + * "/word/header1.xml" + * ); + * ``` + */ export class Override extends XmlComponent { public constructor(contentType: string, partName?: string) { super("Override"); diff --git a/src/file/core-properties/index.ts b/src/file/core-properties/index.ts index 99d40e003c..4d65d85a9a 100644 --- a/src/file/core-properties/index.ts +++ b/src/file/core-properties/index.ts @@ -1 +1,6 @@ +/** + * Core properties module exports. + * + * @module + */ export * from "./properties"; diff --git a/src/file/core-properties/properties.ts b/src/file/core-properties/properties.ts index d1b78cf7e0..622c30bb98 100644 --- a/src/file/core-properties/properties.ts +++ b/src/file/core-properties/properties.ts @@ -1,3 +1,12 @@ +/** + * Core Properties module for WordprocessingML documents. + * + * Provides support for document metadata based on Dublin Core properties. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCore.xsd + * + * @module + */ import { FontOptions } from "@file/fonts/font-table"; import { ICommentsOptions } from "@file/paragraph/run/comment-run"; import { IHyphenationOptions } from "@file/settings"; @@ -13,6 +22,32 @@ import { INumberingOptions } from "../numbering"; import { Paragraph } from "../paragraph"; import { IStylesOptions } from "../styles"; +/** + * Options for configuring document properties. + * + * @property sections - Document section configurations + * @property title - Document title + * @property subject - Document subject + * @property creator - Document creator/author + * @property keywords - Document keywords for searchability + * @property description - Document description + * @property lastModifiedBy - User who last modified the document + * @property revision - Revision number + * @property externalStyles - External stylesheet reference + * @property styles - Document styles configuration + * @property numbering - Numbering configuration + * @property comments - Document comments configuration + * @property footnotes - Document footnotes + * @property background - Document background settings + * @property features - Document features like track changes + * @property compatabilityModeVersion - Compatibility mode version + * @property compatibility - Compatibility settings + * @property customProperties - Custom document properties + * @property evenAndOddHeaderAndFooters - Enable different headers/footers for even/odd pages + * @property defaultTabStop - Default tab stop width + * @property fonts - Font configurations + * @property hyphenation - Hyphenation settings + */ export type IPropertiesOptions = { readonly sections: readonly ISectionOptions[]; readonly title?: string; @@ -48,30 +83,50 @@ export type IPropertiesOptions = { readonly hyphenation?: IHyphenationOptions; }; -// - -/* cSpell:disable */ -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -/* cSpell:enable */ - +/** + * Represents the core properties of a WordprocessingML document. + * + * Core properties contain document metadata based on Dublin Core elements, + * including title, subject, creator, keywords, description, and modification tracking. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCore.xsd + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const coreProps = new CoreProperties({ + * title: "My Document", + * subject: "Sample Document", + * creator: "John Doe", + * keywords: "docx, example", + * description: "A sample document", + * lastModifiedBy: "Jane Doe", + * revision: 1 + * }); + * ``` + */ export class CoreProperties extends XmlComponent { public constructor(options: Omit) { super("cp:coreProperties"); @@ -102,10 +157,18 @@ export class CoreProperties extends XmlComponent { } } +/** + * Attributes for timestamp elements in core properties. + * Specifies the W3C DateTime Format type for timestamps. + */ class TimestampElementProperties extends XmlAttributeComponent<{ readonly type: string }> { protected readonly xmlKeys = { type: "xsi:type" }; } +/** + * Represents a timestamp element (created or modified date). + * Uses W3C DateTime Format (dcterms:W3CDTF) for dates. + */ class TimestampElement extends XmlComponent { public constructor(name: string) { super(name); diff --git a/src/file/custom-properties/custom-properties-attributes.ts b/src/file/custom-properties/custom-properties-attributes.ts index fdae344710..2c3f7e46f7 100644 --- a/src/file/custom-properties/custom-properties-attributes.ts +++ b/src/file/custom-properties/custom-properties-attributes.ts @@ -1,7 +1,24 @@ +/** + * Custom Properties Attributes module for WordprocessingML documents. + * + * Provides namespace attributes for custom document properties. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * XML namespace attributes for the custom properties element. + * + * @property xmlns - Main namespace for custom properties + * @property vt - Namespace for variant types + */ export class CustomPropertiesAttributes extends XmlAttributeComponent<{ + /** Main namespace for custom properties */ readonly xmlns: string; + /** Namespace for variant types */ readonly vt: string; }> { protected readonly xmlKeys = { diff --git a/src/file/custom-properties/custom-properties.ts b/src/file/custom-properties/custom-properties.ts index f24dcaa12a..6097f03802 100644 --- a/src/file/custom-properties/custom-properties.ts +++ b/src/file/custom-properties/custom-properties.ts @@ -1,8 +1,42 @@ +/** + * Custom Properties module for WordprocessingML documents. + * + * Provides support for managing custom document properties collection. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * @module + */ import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; import { CustomPropertiesAttributes } from "./custom-properties-attributes"; import { CustomProperty, ICustomPropertyOptions } from "./custom-property"; +/** + * Represents the collection of custom document properties. + * + * Custom properties allow storing arbitrary metadata as name-value pairs. + * Each property is assigned a unique ID starting from 2 (per Office specification). + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const customProps = new CustomProperties([ + * { name: "Department", value: "Engineering" }, + * { name: "Project", value: "Alpha" } + * ]); + * ``` + */ export class CustomProperties extends XmlComponent { // eslint-disable-next-line functional/prefer-readonly-type private nextId: number; diff --git a/src/file/custom-properties/custom-property-attributes.ts b/src/file/custom-properties/custom-property-attributes.ts index 7f2c873c6c..a800b5b8a1 100644 --- a/src/file/custom-properties/custom-property-attributes.ts +++ b/src/file/custom-properties/custom-property-attributes.ts @@ -1,12 +1,31 @@ +/** + * Custom Property Attributes module for WordprocessingML documents. + * + * Provides attributes for individual custom document properties. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * XML attributes for a custom property element. + * + * @property formatId - Format identifier (GUID) + * @property pid - Property identifier (unique ID) + * @property name - Property name + */ export class CustomPropertyAttributes extends XmlAttributeComponent<{ - readonly fmtid: string; + /** Format identifier (GUID) */ + readonly formatId: string; + /** Property identifier (unique ID) */ readonly pid: string; + /** Property name */ readonly name: string; }> { protected readonly xmlKeys = { - fmtid: "fmtid", + formatId: "fmtid", pid: "pid", name: "name", }; diff --git a/src/file/custom-properties/custom-property.ts b/src/file/custom-properties/custom-property.ts index c72de03e33..0690f73b10 100644 --- a/src/file/custom-properties/custom-property.ts +++ b/src/file/custom-properties/custom-property.ts @@ -1,18 +1,63 @@ +/** + * Custom Property module for WordprocessingML documents. + * + * Provides support for individual custom document properties. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { CustomPropertyAttributes } from "./custom-property-attributes"; +/** + * Options for creating a custom property. + * + * @property name - The property name + * @property value - The property value (as string) + */ export type ICustomPropertyOptions = { + /** The property name */ readonly name: string; + /** The property value (as string) */ readonly value: string; }; +/** + * Represents a single custom document property. + * + * Custom properties allow storing arbitrary key-value pairs in the document metadata. + * Each property has a unique name and a string value. + * + * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const customProp = new CustomProperty(2, { + * name: "Department", + * value: "Engineering" + * }); + * ``` + */ export class CustomProperty extends XmlComponent { public constructor(id: number, properties: ICustomPropertyOptions) { super("property"); this.root.push( new CustomPropertyAttributes({ - fmtid: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", + formatId: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", pid: id.toString(), name: properties.name, }), @@ -21,6 +66,10 @@ export class CustomProperty extends XmlComponent { } } +/** + * Represents the value of a custom property. + * Uses the variant type "long pointer to wide string" for string values. + */ export class CustomPropertyValue extends XmlComponent { public constructor(value: string) { super("vt:lpwstr"); diff --git a/src/file/custom-properties/index.ts b/src/file/custom-properties/index.ts index 132da63d92..1e3ea6004d 100644 --- a/src/file/custom-properties/index.ts +++ b/src/file/custom-properties/index.ts @@ -1,2 +1,7 @@ +/** + * Custom properties module exports. + * + * @module + */ export * from "./custom-properties"; export * from "./custom-property"; diff --git a/src/file/document-wrapper.ts b/src/file/document-wrapper.ts index 578ac2d048..07af8629fe 100644 --- a/src/file/document-wrapper.ts +++ b/src/file/document-wrapper.ts @@ -1,3 +1,12 @@ +/** + * Document wrapper module for WordprocessingML documents. + * + * This module provides wrappers that combine the main document/header/footer + * views with their associated relationships, enabling proper management of + * document parts and their references. + * + * @module + */ import { Document, IDocumentOptions } from "./document"; import { Footer } from "./footer/footer"; import { FootNotes } from "./footnotes"; @@ -5,11 +14,36 @@ import { Header } from "./header/header"; import { Relationships } from "./relationships"; import { XmlComponent } from "./xml-components"; +/** + * Interface for document view wrappers. + * + * ViewWrappers combine a document part (view) with its relationships, + * providing a unified interface for managing document components. + * + * @property View - The document part (Document, Header, Footer, etc.) + * @property Relationships - The relationships associated with this view + */ export type IViewWrapper = { readonly View: Document | Footer | Header | FootNotes | XmlComponent; readonly Relationships: Relationships; }; +/** + * Wrapper for the main document body. + * + * DocumentWrapper combines the main Document view with its Relationships, + * managing the primary content of the .docx file along with references to + * images, hyperlinks, and other linked resources. + * + * @example + * ```typescript + * const wrapper = new DocumentWrapper({ + * sections: [{ + * children: [new Paragraph("Hello World")], + * }], + * }); + * ``` + */ export class DocumentWrapper implements IViewWrapper { private readonly document: Document; private readonly relationships: Relationships; diff --git a/src/file/document/body/body.ts b/src/file/document/body/body.ts index 48f2dbe53e..b6b71a5a4f 100644 --- a/src/file/document/body/body.ts +++ b/src/file/document/body/body.ts @@ -1,3 +1,10 @@ +/** + * Document body module for WordprocessingML documents. + * + * Reference: http://officeopenxml.com/WPdocument.php + * + * @module + */ import { Paragraph, ParagraphProperties } from "@file/paragraph"; import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; @@ -9,6 +16,10 @@ import { ISectionPropertiesOptions, SectionProperties } from "./section-properti * The body element is the container for all block-level content in the document. * This includes paragraphs, tables, and section properties that define page layout. * + * The body supports multiple sections, where each section (except the last one) must + * have its section properties stored in a paragraph's properties at the end of that + * section. The last section's properties are stored as a direct child of the body element. + * * Reference: http://officeopenxml.com/WPdocument.php * * ## XSD Schema @@ -20,6 +31,26 @@ import { ISectionPropertiesOptions, SectionProperties } from "./section-properti * * * ``` + * + * @example + * ```typescript + * // Body is typically created internally by the Document class + * const doc = new Document({}); + * const body = doc.Body; + * + * // Add content to the body via Document.add() + * doc.add(new Paragraph("Content in first section")); + * + * // Add a new section + * body.addSection({ + * page: { + * size: { width: 12240, height: 15840 }, + * }, + * }); + * + * // Content after addSection belongs to the new section + * doc.add(new Paragraph("Content in second section")); + * ``` */ export class Body extends XmlComponent { // eslint-disable-next-line functional/prefer-readonly-type @@ -30,13 +61,17 @@ export class Body extends XmlComponent { } /** - * Adds new section properties. - * Note: Previous section is created in paragraph after the current element, and then new section will be added. - * The spec says: - * - section element should be in the last paragraph of the section - * - last section should be direct child of body + * Adds new section properties to the document body. * - * @param options new section options + * Creates a new section by moving the previous section's properties into a paragraph + * at the end of that section, and then adding the new section as the current section. + * + * According to the OOXML specification: + * - Section properties for all sections except the last must be stored in a paragraph's + * properties (pPr/sectPr) at the end of each section + * - The last section's properties are stored as a direct child of the body element (w:body/w:sectPr) + * + * @param options - Section properties configuration (page size, margins, headers, footers, etc.) */ public addSection(options: ISectionPropertiesOptions): void { const currentSection = this.sections.pop() as SectionProperties; @@ -45,6 +80,15 @@ export class Body extends XmlComponent { this.sections.push(new SectionProperties(options)); } + /** + * Prepares the body element for XML serialization. + * + * Ensures that the last section's properties are placed as a direct child of the body + * element, as required by the OOXML specification. + * + * @param context - The XML serialization context + * @returns The prepared XML object or undefined + */ public prepForXml(context: IContext): IXmlableObject | undefined { if (this.sections.length === 1) { this.root.splice(0, 1); @@ -54,6 +98,14 @@ export class Body extends XmlComponent { return super.prepForXml(context); } + /** + * Adds a block-level component to the body. + * + * This method is used internally by the Document class to add paragraphs, + * tables, and other block-level elements to the document body. + * + * @param component - The XML component to add (paragraph, table, etc.) + */ public push(component: XmlComponent): void { this.root.push(component); } diff --git a/src/file/document/body/index.ts b/src/file/document/body/index.ts index 83678ef8ea..a0750a0963 100644 --- a/src/file/document/body/index.ts +++ b/src/file/document/body/index.ts @@ -1,2 +1,7 @@ +/** + * Document body module exports. + * + * @module + */ export * from "./body"; export * from "./section-properties"; diff --git a/src/file/document/body/section-properties/index.ts b/src/file/document/body/section-properties/index.ts index bb4ce998e3..77275ba910 100644 --- a/src/file/document/body/section-properties/index.ts +++ b/src/file/document/body/section-properties/index.ts @@ -1,2 +1,7 @@ +/** + * Section properties module exports. + * + * @module + */ export * from "./section-properties"; export * from "./properties"; diff --git a/src/file/document/body/section-properties/properties/column.ts b/src/file/document/body/section-properties/properties/column.ts index b90606f436..a241bc8bd4 100644 --- a/src/file/document/body/section-properties/properties/column.ts +++ b/src/file/document/body/section-properties/properties/column.ts @@ -1,16 +1,53 @@ +/** + * Column module for WordprocessingML section properties. + * + * Defines individual column properties within multi-column layouts. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * @module + */ import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, twipsMeasureValue } from "@util/values"; -// -// -// -// - +/** + * Options for configuring individual column properties. + * + * @property width - Column width in twips or universal measure + * @property space - Space after column in twips or universal measure (default: 0) + */ type IColumnAttributes = { + /** Column width in twips or universal measure */ readonly width: number | PositiveUniversalMeasure; + /** Space after column in twips or universal measure (default: 0) */ readonly space?: number | PositiveUniversalMeasure; }; +/** + * Represents a column definition (col) in a multi-column section layout. + * + * This element defines the width and spacing for an individual column when + * using unequal column widths in a section. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a column with specific width and spacing + * new Column({ + * width: 3000, + * space: 720 + * }); + * ``` + */ export class Column extends XmlComponent { public constructor({ width, space }: IColumnAttributes) { super("w:col"); diff --git a/src/file/document/body/section-properties/properties/columns.ts b/src/file/document/body/section-properties/properties/columns.ts index 628c01a8b9..dcbb3faff3 100644 --- a/src/file/document/body/section-properties/properties/columns.ts +++ b/src/file/document/body/section-properties/properties/columns.ts @@ -1,25 +1,80 @@ +/** + * Columns module for WordprocessingML section properties. + * + * Defines multi-column layouts within document sections. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * @module + */ import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, decimalNumber, twipsMeasureValue } from "@util/values"; import { Column } from "./column"; -// -// -// -// -// -// -// -// -// +/** + * Options for configuring column layout in a section. + * + * @property space - Spacing between columns in twips (default: 720) + * @property count - Number of columns (default: 1) + * @property separate - Whether to draw vertical separator lines between columns + * @property equalWidth - Whether all columns have equal width + * @property children - Individual column definitions (used when equalWidth is false) + */ export type IColumnsAttributes = { + /** Spacing between columns in twips (default: 720) */ readonly space?: number | PositiveUniversalMeasure; + /** Number of columns (default: 1) */ readonly count?: number; + /** Whether to draw vertical separator lines between columns */ readonly separate?: boolean; + /** Whether all columns have equal width */ readonly equalWidth?: boolean; + /** Individual column definitions (used when equalWidth is false, max: 45) */ readonly children?: readonly Column[]; }; +/** + * Represents column layout settings (cols) for a document section. + * + * This element defines the multi-column layout properties for a section, + * including column count, spacing, and whether columns have equal or custom widths. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Two equal-width columns with separator + * new Columns({ + * count: 2, + * space: 720, + * separate: true, + * equalWidth: true + * }); + * + * // Custom column widths + * new Columns({ + * equalWidth: false, + * children: [ + * new Column({ width: 3000, space: 720 }), + * new Column({ width: 4000, space: 0 }) + * ] + * }); + * ``` + */ export class Columns extends XmlComponent { public constructor({ space, count, separate, equalWidth, children }: IColumnsAttributes) { super("w:cols"); diff --git a/src/file/document/body/section-properties/properties/index.ts b/src/file/document/body/section-properties/properties/index.ts index 8cc32e6e23..4b96bc9773 100644 --- a/src/file/document/body/section-properties/properties/index.ts +++ b/src/file/document/body/section-properties/properties/index.ts @@ -1,3 +1,8 @@ +/** + * Section properties components module exports. + * + * @module + */ export * from "./column"; export * from "./columns"; export * from "./doc-grid"; diff --git a/src/file/document/body/section-properties/properties/page-borders.ts b/src/file/document/body/section-properties/properties/page-borders.ts index e597cac61b..2fea4ef11e 100644 --- a/src/file/document/body/section-properties/properties/page-borders.ts +++ b/src/file/document/body/section-properties/properties/page-borders.ts @@ -1,54 +1,113 @@ -// http://officeopenxml.com/WPsectionBorders.php +/** + * Page borders module for WordprocessingML section properties. + * + * Defines borders around pages in a document section. + * + * Reference: http://officeopenxml.com/WPsectionBorders.php + * + * @module + */ import { BorderElement, IBorderOptions } from "@file/border"; import { IgnoreIfEmptyXmlComponent, XmlAttributeComponent } from "@file/xml-components"; -// -// -// -// -// -// -// - +/** + * Specifies which pages display the page border. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export const PageBorderDisplay = { + /** Display border on all pages */ ALL_PAGES: "allPages", + /** Display border only on first page */ FIRST_PAGE: "firstPage", + /** Display border on all pages except first page */ NOT_FIRST_PAGE: "notFirstPage", } as const; -// -// -// -// -// -// +/** + * Specifies whether page border is positioned relative to page edge or text. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const PageBorderOffsetFrom = { + /** Position border relative to page edge */ PAGE: "page", + /** Position border relative to text (default) */ TEXT: "text", } as const; -// -// -// -// -// -// +/** + * Specifies z-order of page border relative to intersecting objects. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const PageBorderZOrder = { + /** Display border behind page contents */ BACK: "back", + /** Display border in front of page contents (default) */ FRONT: "front", } as const; +/** + * Attributes for configuring page border behavior. + * + * @property display - Which pages display the border + * @property offsetFrom - Whether border is positioned relative to page or text + * @property zOrder - Whether border appears in front or behind page contents + */ export type IPageBorderAttributes = { + /** Which pages display the border */ readonly display?: (typeof PageBorderDisplay)[keyof typeof PageBorderDisplay]; + /** Whether border is positioned relative to page or text (default: text) */ readonly offsetFrom?: (typeof PageBorderOffsetFrom)[keyof typeof PageBorderOffsetFrom]; + /** Whether border appears in front or behind page contents (default: front) */ readonly zOrder?: (typeof PageBorderZOrder)[keyof typeof PageBorderZOrder]; }; +/** + * Options for configuring page borders. + * + * @property pageBorders - General page border attributes (display, offset, z-order) + * @property pageBorderTop - Top border styling + * @property pageBorderRight - Right border styling + * @property pageBorderBottom - Bottom border styling + * @property pageBorderLeft - Left border styling + */ export type IPageBordersOptions = { + /** General page border attributes (display, offset, z-order) */ readonly pageBorders?: IPageBorderAttributes; + /** Top border styling */ readonly pageBorderTop?: IBorderOptions; + /** Right border styling */ readonly pageBorderRight?: IBorderOptions; + /** Bottom border styling */ readonly pageBorderBottom?: IBorderOptions; + /** Left border styling */ readonly pageBorderLeft?: IBorderOptions; }; @@ -60,17 +119,43 @@ class PageBordersAttributes extends XmlAttributeComponent }; } -// -// -// -// -// -// -// -// -// -// -// +/** + * Represents page borders (pgBorders) for a document section. + * + * This element specifies the borders to display around pages in a section, + * including which pages display the borders and how they are positioned. + * + * Reference: http://officeopenxml.com/WPsectionBorders.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Add page borders to all pages + * new PageBorders({ + * pageBorders: { + * display: PageBorderDisplay.ALL_PAGES, + * offsetFrom: PageBorderOffsetFrom.PAGE, + * zOrder: PageBorderZOrder.FRONT + * }, + * pageBorderTop: { style: BorderStyle.SINGLE, size: 24, color: "000000" }, + * pageBorderBottom: { style: BorderStyle.SINGLE, size: 24, color: "000000" } + * }); + * ``` + */ export class PageBorders extends IgnoreIfEmptyXmlComponent { public constructor(options?: IPageBordersOptions) { super("w:pgBorders"); diff --git a/src/file/document/body/section-properties/properties/page-margin.ts b/src/file/document/body/section-properties/properties/page-margin.ts index 03378a0db2..ca1249d81f 100644 --- a/src/file/document/body/section-properties/properties/page-margin.ts +++ b/src/file/document/body/section-properties/properties/page-margin.ts @@ -1,25 +1,72 @@ +/** + * Page margin module for WordprocessingML section properties. + * + * Defines page margins for document sections. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * @module + */ import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, UniversalMeasure, signedTwipsMeasureValue, twipsMeasureValue } from "@util/values"; -// -// -// -// -// -// -// -// -// +/** + * Options for configuring page margins. + * + * All measurements are in twips (1/20th of a point) or universal measure. + * + * @property top - Top margin + * @property right - Right margin + * @property bottom - Bottom margin + * @property left - Left margin + * @property header - Header margin (distance from top of page to header) + * @property footer - Footer margin (distance from bottom of page to footer) + * @property gutter - Gutter margin for binding + */ export type IPageMarginAttributes = { + /** Top margin in twips or universal measure */ readonly top?: number | UniversalMeasure; + /** Right margin in twips or universal measure */ readonly right?: number | PositiveUniversalMeasure; + /** Bottom margin in twips or universal measure */ readonly bottom?: number | UniversalMeasure; + /** Left margin in twips or universal measure */ readonly left?: number | PositiveUniversalMeasure; + /** Header margin (distance from top of page to header) in twips or universal measure */ readonly header?: number | PositiveUniversalMeasure; + /** Footer margin (distance from bottom of page to footer) in twips or universal measure */ readonly footer?: number | PositiveUniversalMeasure; + /** Gutter margin for binding in twips or universal measure */ readonly gutter?: number | PositiveUniversalMeasure; }; +/** + * Represents page margins (pgMar) for a document section. + * + * This element specifies the page margins for all pages in a section, + * including top, bottom, left, right, header, footer, and gutter margins. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create page margins with 1 inch margins (1440 twips = 1 inch) + * new PageMargin(1440, 1440, 1440, 1440, 720, 720, 0); + * ``` + */ export class PageMargin extends XmlComponent { public constructor( top: number | UniversalMeasure, diff --git a/src/file/document/body/section-properties/properties/page-number.ts b/src/file/document/body/section-properties/properties/page-number.ts index 055349d0ec..8ad5a4ef05 100644 --- a/src/file/document/body/section-properties/properties/page-number.ts +++ b/src/file/document/body/section-properties/properties/page-number.ts @@ -1,39 +1,61 @@ -// http://officeopenxml.com/WPSectionPgNumType.php +/** + * Page number module for WordprocessingML section properties. + * + * Defines page numbering format and starting value for document sections. + * + * Reference: http://officeopenxml.com/WPSectionPgNumType.php + * + * @module + */ import { NumberFormat } from "@file/shared/number-format"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; -// -// -// -// -// -// -// -// -// - +/** + * Specifies the separator character between chapter number and page number. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + */ export const PageNumberSeparator = { + /** Hyphen separator (-) */ HYPHEN: "hyphen", + /** Period separator (.) */ PERIOD: "period", + /** Colon separator (:) */ COLON: "colon", + /** Em dash separator (—) */ EM_DASH: "emDash", + /** En dash separator (–) */ EN_DASH: "endash", } as const; +/** + * Options for configuring page numbering. + * + * @property start - Starting page number for the section + * @property formatType - Number format (decimal, roman, letter, etc.) + * @property separator - Separator between chapter and page number + */ export type IPageNumberTypeAttributes = { + /** Starting page number for the section */ readonly start?: number; + /** Number format (decimal, roman, letter, etc., default: decimal) */ readonly formatType?: (typeof NumberFormat)[keyof typeof NumberFormat]; + /** Separator between chapter and page number (default: hyphen) */ readonly separator?: (typeof PageNumberSeparator)[keyof typeof PageNumberSeparator]; }; -// -// -// -// -// -// - export class PageNumberTypeAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { start: "w:start", @@ -42,6 +64,33 @@ export class PageNumberTypeAttributes extends XmlAttributeComponent + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Start page numbering at 5 with lowercase roman numerals + * new PageNumberType({ + * start: 5, + * formatType: NumberFormat.LOWER_ROMAN + * }); + * ``` + */ export class PageNumberType extends XmlComponent { public constructor({ start, formatType, separator }: IPageNumberTypeAttributes) { super("w:pgNumType"); diff --git a/src/file/document/body/section-properties/properties/page-text-direction.ts b/src/file/document/body/section-properties/properties/page-text-direction.ts index ee883e3f1e..7cacf76147 100644 --- a/src/file/document/body/section-properties/properties/page-text-direction.ts +++ b/src/file/document/body/section-properties/properties/page-text-direction.ts @@ -1,7 +1,24 @@ +/** + * Page text direction module for WordprocessingML section properties. + * + * Defines text flow direction for pages in a section. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Specifies the text flow direction for pages in a section. + * + * This controls whether text flows horizontally (left-to-right) or + * vertically (top-to-bottom), commonly used for East Asian languages. + */ export const PageTextDirectionType = { + /** Left-to-right, top-to-bottom (standard Western text flow) */ LEFT_TO_RIGHT_TOP_TO_BOTTOM: "lrTb", + /** Top-to-bottom, right-to-left (vertical East Asian text flow) */ TOP_TO_BOTTOM_RIGHT_TO_LEFT: "tbRl", } as const; @@ -11,6 +28,23 @@ class PageTextDirectionAttributes extends XmlAttributeComponent<{ protected readonly xmlKeys = { val: "w:val" }; } +/** + * Represents text direction (textDirection) for pages in a section. + * + * This element specifies the direction and orientation of text flow + * for all pages in a section. + * + * Reference: http://officeopenxml.com/WPsectionPr.php + * + * @example + * ```typescript + * // Horizontal text flow (left-to-right, top-to-bottom) + * new PageTextDirection(PageTextDirectionType.LEFT_TO_RIGHT_TOP_TO_BOTTOM); + * + * // Vertical text flow (top-to-bottom, right-to-left) + * new PageTextDirection(PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT); + * ``` + */ export class PageTextDirection extends XmlComponent { public constructor(value: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType]) { super("w:textDirection"); diff --git a/src/file/document/body/section-properties/properties/section-type.ts b/src/file/document/body/section-properties/properties/section-type.ts index e56a4c45a9..6a0a41a910 100644 --- a/src/file/document/body/section-properties/properties/section-type.ts +++ b/src/file/document/body/section-properties/properties/section-type.ts @@ -1,27 +1,45 @@ -// http://officeopenxml.com/WPsection.php +/** + * Section type module for WordprocessingML section properties. + * + * Defines how a section begins relative to the previous section. + * + * Reference: http://officeopenxml.com/WPsection.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; -// -// -// -// -// -// -// -// -// - +/** + * Specifies the type of section break. + * + * This determines where the section begins relative to the previous section. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + */ export const SectionType = { + /** Section begins on the next page */ NEXT_PAGE: "nextPage", + /** Section begins on the next column */ NEXT_COLUMN: "nextColumn", + /** Section begins immediately following the previous section */ CONTINUOUS: "continuous", + /** Section begins on the next even-numbered page */ EVEN_PAGE: "evenPage", + /** Section begins on the next odd-numbered page */ ODD_PAGE: "oddPage", } as const; -// -// -// export class SectionTypeAttributes extends XmlAttributeComponent<{ readonly val: (typeof SectionType)[keyof typeof SectionType]; }> { @@ -30,6 +48,30 @@ export class SectionTypeAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents section type (type) for a document section. + * + * This element specifies the type of section break, which determines + * where the new section begins relative to the previous section. + * + * Reference: http://officeopenxml.com/WPsection.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a continuous section (no page break) + * new Type(SectionType.CONTINUOUS); + * + * // Create a section that starts on next odd page + * new Type(SectionType.ODD_PAGE); + * ``` + */ export class Type extends XmlComponent { public constructor(value: (typeof SectionType)[keyof typeof SectionType]) { super("w:type"); diff --git a/src/file/document/body/section-properties/section-properties.ts b/src/file/document/body/section-properties/section-properties.ts index d93a1cfd0a..29a693f95a 100644 --- a/src/file/document/body/section-properties/section-properties.ts +++ b/src/file/document/body/section-properties/section-properties.ts @@ -27,55 +27,116 @@ import { SectionType, Type } from "./properties/section-type"; /** * Header/footer group for specifying different headers/footers * for default, first, and even pages. + * + * @property default - Header/footer for default pages (odd pages when even headers are used) + * @property first - Header/footer for first page (requires titlePage setting) + * @property even - Header/footer for even pages (requires evenAndOddHeaders setting) */ export type IHeaderFooterGroup = { + /** Header/footer for default pages (odd pages when even headers are used) */ readonly default?: T; + /** Header/footer for first page (requires titlePage setting) */ readonly first?: T; + /** Header/footer for even pages (requires evenAndOddHeaders setting) */ readonly even?: T; }; /** * Options for configuring section properties. * + * This type defines all possible configuration options for a document section, + * including page layout, margins, headers/footers, and numbering. + * + * @property page - Page-level settings (size, margins, borders, numbering, text direction) + * @property grid - Document grid settings for East Asian typography + * @property headerWrapperGroup - Header definitions for default, first, and even pages + * @property footerWrapperGroup - Footer definitions for default, first, and even pages + * @property lineNumbers - Line numbering settings + * @property titlePage - Whether first page has different header/footer + * @property verticalAlign - Vertical alignment of text on page + * @property column - Column layout settings + * @property type - Section break type (next page, continuous, etc.) + * * @see {@link SectionProperties} */ export type ISectionPropertiesOptions = { + /** Page-level settings including size, margins, borders, and text direction */ readonly page?: { + /** Page size and orientation */ readonly size?: Partial; + /** Page margins (top, bottom, left, right, header, footer, gutter) */ readonly margin?: IPageMarginAttributes; + /** Page numbering format and starting value */ readonly pageNumbers?: IPageNumberTypeAttributes; + /** Page border settings */ readonly borders?: IPageBordersOptions; + /** Text flow direction (horizontal or vertical) */ readonly textDirection?: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType]; }; + /** Document grid settings for precise East Asian character layout */ readonly grid?: Partial; + /** Header definitions for default, first, and even pages */ readonly headerWrapperGroup?: IHeaderFooterGroup; + /** Footer definitions for default, first, and even pages */ readonly footerWrapperGroup?: IHeaderFooterGroup; + /** Line numbering settings for the section */ readonly lineNumbers?: ILineNumberAttributes; + /** Whether first page has different header/footer */ readonly titlePage?: boolean; + /** Vertical alignment of text on page (top, center, bottom, justified) */ readonly verticalAlign?: SectionVerticalAlign; + /** Column layout settings (count, spacing, equal width) */ readonly column?: IColumnsAttributes; + /** Section break type (next page, continuous, even page, odd page) */ readonly type?: (typeof SectionType)[keyof typeof SectionType]; }; /** * Default margin values for sections (in twips). + * + * Standard margins are 1 inch (1440 twips) on all sides. + * Header/footer margins are 0.5 inches (708 twips) from page edge. + * + * @property TOP - Top margin: 1440 twips (1 inch) + * @property RIGHT - Right margin: 1440 twips (1 inch) + * @property BOTTOM - Bottom margin: 1440 twips (1 inch) + * @property LEFT - Left margin: 1440 twips (1 inch) + * @property HEADER - Header margin: 708 twips (0.5 inches) + * @property FOOTER - Footer margin: 708 twips (0.5 inches) + * @property GUTTER - Gutter margin: 0 twips */ export const sectionMarginDefaults = { + /** Top margin: 1440 twips (1 inch) */ TOP: 1440, + /** Right margin: 1440 twips (1 inch) */ RIGHT: 1440, + /** Bottom margin: 1440 twips (1 inch) */ BOTTOM: 1440, + /** Left margin: 1440 twips (1 inch) */ LEFT: 1440, + /** Header margin from top: 708 twips (0.5 inches) */ HEADER: 708, + /** Footer margin from bottom: 708 twips (0.5 inches) */ FOOTER: 708, + /** Gutter margin for binding: 0 twips */ GUTTER: 0, }; /** * Default page size values (in twips, A4 portrait). + * + * A4 size is 210mm x 297mm (8.27" x 11.69"). + * + * @property WIDTH - Page width: 11906 twips (8.27 inches, 210mm) + * @property HEIGHT - Page height: 16838 twips (11.69 inches, 297mm) + * @property ORIENTATION - Page orientation: portrait */ export const sectionPageSizeDefaults = { + /** Page width: 11906 twips (8.27 inches, 210mm) */ WIDTH: 11906, + /** Page height: 16838 twips (11.69 inches, 297mm) */ HEIGHT: 16838, + /** Page orientation: portrait */ ORIENTATION: PageOrientation.PORTRAIT, }; @@ -84,6 +145,7 @@ export const sectionPageSizeDefaults = { * * Section properties define the page layout for a section of the document, * including page size, margins, headers/footers, columns, and page numbering. + * A document can contain multiple sections with different properties. * * Reference: http://officeopenxml.com/WPsection.php * @@ -98,6 +160,34 @@ export const sectionPageSizeDefaults = { * * * ``` + * + * @example + * ```typescript + * // Create section with custom page size and margins + * new SectionProperties({ + * page: { + * size: { + * width: 12240, + * height: 15840, + * orientation: PageOrientation.PORTRAIT + * }, + * margin: { + * top: 1440, + * right: 1440, + * bottom: 1440, + * left: 1440 + * }, + * pageNumbers: { + * start: 1, + * formatType: NumberFormat.DECIMAL + * } + * }, + * column: { + * count: 2, + * space: 720 + * } + * }); + * ``` */ export class SectionProperties extends XmlComponent { public constructor({ diff --git a/src/file/document/document-attributes.ts b/src/file/document/document-attributes.ts index 31e7db2143..b445efa462 100644 --- a/src/file/document/document-attributes.ts +++ b/src/file/document/document-attributes.ts @@ -1,5 +1,21 @@ +/** + * Document attributes module for WordprocessingML documents. + * + * This module defines the XML namespace declarations used in OOXML documents. + * These namespaces are required for proper document parsing and generation. + * + * Reference: http://officeopenxml.com/anatomyofOOXML.php + * + * @module + */ import { AttributeMap, XmlAttributeComponent } from "@file/xml-components"; +/** + * XML namespace URIs used in WordprocessingML documents. + * + * These namespaces define the various XML schemas that can be referenced + * in a document, including WordprocessingML, DrawingML, VML, and others. + */ /* cSpell:disable */ export const DocumentAttributeNamespaces = { wpc: "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas", @@ -42,12 +58,35 @@ export const DocumentAttributeNamespaces = { }; /* cSpell:enable */ +/** + * Type representing valid namespace keys. + */ export type DocumentAttributeNamespace = keyof typeof DocumentAttributeNamespaces; +/** + * Properties for document namespace attributes. + * + * Allows specifying which namespaces to include and optional Ignorable attribute + * for compatibility with older processors. + */ export type IDocumentAttributesProperties = Partial> & { readonly Ignorable?: string; }; +/** + * Represents XML namespace attributes for a WordprocessingML document. + * + * This class generates the xmlns declarations required at the root element + * of document.xml and other document parts. + * + * @example + * ```typescript + * new DocumentAttributes(['w', 'r', 'wp'], 'w14 w15'); + * // Generates: xmlns:w="..." xmlns:r="..." xmlns:wp="..." mc:Ignorable="w14 w15" + * ``` + * + * @internal + */ export class DocumentAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { Ignorable: "mc:Ignorable", diff --git a/src/file/document/document-background/document-background.ts b/src/file/document/document-background/document-background.ts index c3d3143ca0..5ca63a4e93 100644 --- a/src/file/document/document-background/document-background.ts +++ b/src/file/document/document-background/document-background.ts @@ -1,30 +1,46 @@ -// http://officeopenxml.com/WPdocument.php -// http://www.datypic.com/sc/ooxml/e-w_background-1.html +/** + * Document background module for WordprocessingML documents. + * + * This module provides functionality for setting document background colors + * and theme-based backgrounds. + * + * Reference: http://officeopenxml.com/WPdocument.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { hexColorValue, uCharHexNumber } from "@util/values"; -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// - +/** + * Attributes for the document background element. + * + * ## XSD Schema (ST_ThemeColor) + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @internal + */ export class DocumentBackgroundAttributes extends XmlAttributeComponent<{ readonly color?: string; readonly themeColor?: string; @@ -39,29 +55,53 @@ export class DocumentBackgroundAttributes extends XmlAttributeComponent<{ }; } +/** + * Options for creating a document background. + * + * @see {@link DocumentBackground} + */ export type IDocumentBackgroundOptions = { + /** Background color in hex format (e.g., "FF0000" for red) */ readonly color?: string; + /** Theme color name (e.g., "accent1", "dark1") */ readonly themeColor?: string; + /** Theme shade value (darkens the theme color) */ readonly themeShade?: string; + /** Theme tint value (lightens the theme color) */ readonly themeTint?: string; }; -// -// -// -// -// -// -// -// -// -// -// -// -// - +/** + * Represents a document background in a WordprocessingML document. + * + * The background element specifies the background color or theme color + * for the document. + * + * Reference: http://officeopenxml.com/WPdocument.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new DocumentBackground({ color: "FFFF00" }); // Yellow background + * new DocumentBackground({ themeColor: "accent1" }); // Theme accent color + * ``` + */ export class DocumentBackground extends XmlComponent { public constructor(options: IDocumentBackgroundOptions) { super("w:background"); diff --git a/src/file/document/document-background/index.ts b/src/file/document/document-background/index.ts index 604f3da1f2..74841208fc 100644 --- a/src/file/document/document-background/index.ts +++ b/src/file/document/document-background/index.ts @@ -1 +1,6 @@ +/** + * Document background module exports. + * + * @module + */ export * from "./document-background"; diff --git a/src/file/document/document.ts b/src/file/document/document.ts index 80ce44822b..1bc7da3449 100644 --- a/src/file/document/document.ts +++ b/src/file/document/document.ts @@ -17,6 +17,8 @@ import { DocumentBackground, IDocumentBackgroundOptions } from "./document-backg /** * Options for creating a Document element. * + * @property background - Optional background settings for the document + * * @see {@link Document} */ export type IDocumentOptions = { @@ -54,6 +56,23 @@ export type IDocumentOptions = { * * * ``` + * + * @example + * ```typescript + * // Create a document with default options + * const doc = new Document({}); + * + * // Create a document with background + * const doc = new Document({ + * background: { + * color: "FF0000", + * }, + * }); + * + * // Add content to the document + * doc.add(new Paragraph("Hello World")); + * doc.add(new Table({ rows: [...] })); + * ``` */ export class Document extends XmlComponent { private readonly body: Body; @@ -106,11 +125,22 @@ export class Document extends XmlComponent { this.root.push(this.body); } + /** + * Adds a block-level element to the document body. + * + * @param item - The element to add (paragraph, table, table of contents, or hyperlink) + * @returns The Document instance for method chaining + */ public add(item: Paragraph | Table | TableOfContents | ConcreteHyperlink): Document { this.body.push(item); return this; } + /** + * Gets the document body element. + * + * @returns The Body instance containing all document content + */ public get Body(): Body { return this.body; } diff --git a/src/file/document/index.ts b/src/file/document/index.ts index a93dd86f99..570258c1f3 100644 --- a/src/file/document/index.ts +++ b/src/file/document/index.ts @@ -1,3 +1,8 @@ +/** + * Document module exports. + * + * @module + */ export * from "./document"; export * from "./document-attributes"; export * from "./body"; diff --git a/src/file/drawing/anchor/anchor-attributes.ts b/src/file/drawing/anchor/anchor-attributes.ts index 8d3210fdea..53f99fe236 100644 --- a/src/file/drawing/anchor/anchor-attributes.ts +++ b/src/file/drawing/anchor/anchor-attributes.ts @@ -1,16 +1,42 @@ +/** + * Anchor attributes module for DrawingML floating elements. + * + * This module defines the attributes for anchored/floating drawings, + * controlling positioning, z-order, and wrapping behavior. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; import { IDistance } from "../drawing"; +/** + * Attributes for an anchored drawing element. + * + * These attributes control the positioning and behavior of floating drawings. + */ export type IAnchorAttributes = { + /** Whether the drawing can overlap other content ("0" = false, "1" = true) */ readonly allowOverlap?: "0" | "1"; + /** Whether the drawing is behind document text ("0" = false, "1" = true) */ readonly behindDoc?: "0" | "1"; + /** Whether the drawing is contained within table cells ("0" = false, "1" = true) */ readonly layoutInCell?: "0" | "1"; + /** Whether the anchor position is locked ("0" = false, "1" = true) */ readonly locked?: "0" | "1"; + /** Z-order positioning (higher values appear in front) */ readonly relativeHeight?: number; + /** Whether to use simple positioning ("0" = false, "1" = true) */ readonly simplePos?: "0" | "1"; } & IDistance; +/** + * XML attributes component for anchored drawings. + * + * Maps the IAnchorAttributes to XML attribute names for the wp:anchor element. + * + * @internal + */ export class AnchorAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { distT: "distT", diff --git a/src/file/drawing/anchor/index.ts b/src/file/drawing/anchor/index.ts index 57faf47fc0..8f03d52f0a 100644 --- a/src/file/drawing/anchor/index.ts +++ b/src/file/drawing/anchor/index.ts @@ -1,2 +1,7 @@ +/** + * Drawing anchor module exports. + * + * @module + */ export * from "./anchor"; export * from "./anchor-attributes"; diff --git a/src/file/drawing/doc-properties/doc-properties-children.ts b/src/file/drawing/doc-properties/doc-properties-children.ts index 0809f581e5..c8de979744 100644 --- a/src/file/drawing/doc-properties/doc-properties-children.ts +++ b/src/file/drawing/doc-properties/doc-properties-children.ts @@ -1,3 +1,11 @@ +/** + * Child elements for document properties. + * + * This module provides hyperlink elements that can be attached to + * drawing elements for interactive behavior. + * + * @module + */ // // // @@ -18,6 +26,28 @@ import { BuilderElement, XmlComponent } from "@file/xml-components"; // TODO: Implement the rest of the attributes +/** + * Creates a click hyperlink element for a drawing. + * + * This element defines what happens when a user clicks on a drawing element. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @param linkId - The relationship ID for the hyperlink target + * @param hasXmlNs - Whether to include the XML namespace declaration + * @returns An XML component representing the click hyperlink + */ export const createHyperlinkClick = (linkId: string, hasXmlNs: boolean): XmlComponent => new BuilderElement({ name: "a:hlinkClick", @@ -37,6 +67,28 @@ export const createHyperlinkClick = (linkId: string, hasXmlNs: boolean): XmlComp }, }); +/** + * Creates a hover hyperlink element for a drawing. + * + * This element defines what happens when a user hovers over a drawing element. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @param linkId - The relationship ID for the hyperlink target + * @param hasXmlNs - Whether to include the XML namespace declaration + * @returns An XML component representing the hover hyperlink + */ export const createHyperlinkHover = (linkId: string, hasXmlNs: boolean): XmlComponent => new BuilderElement({ name: "a:hlinkHover", diff --git a/src/file/drawing/effect-extent/effect-extent.ts b/src/file/drawing/effect-extent/effect-extent.ts index 16e39cf021..f9ccbd09aa 100644 --- a/src/file/drawing/effect-extent/effect-extent.ts +++ b/src/file/drawing/effect-extent/effect-extent.ts @@ -1,5 +1,18 @@ +/** + * Effect extent for DrawingML objects. + * + * This module provides support for defining additional extent to compensate + * for drawing effects applied to objects. + * + * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_effectExtent_topic_ID0E5O3OB.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Attributes for effect extent. + */ export type EffectExtentAttributes = { /** * ## Additional Extent on Top Edge @@ -28,14 +41,19 @@ export type EffectExtentAttributes = { }; /** - * This element specifies the additional extent which shall be added to each edge of the image (top, bottom, left, right) in order to compensate for any drawing effects applied to the DrawingML object. + * Creates an effect extent element. * - * The `` element (§5.5.2.7) specifies the size of the actual DrawingML object; however, an object may have effects applied which change its overall size + * This element specifies the additional extent which shall be added to each + * edge of the image (top, bottom, left, right) in order to compensate for any + * drawing effects applied to the DrawingML object. + * + * The extent element specifies the size of the actual DrawingML object; however, + * an object may have effects applied which change its overall size. This element + * accounts for that additional space. * * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_effectExtent_topic_ID0E5O3OB.html * * ## XSD Schema - * * ```xml * * @@ -44,6 +62,16 @@ export type EffectExtentAttributes = { * * * ``` + * + * @example + * ```typescript + * const effectExtent = createEffectExtent({ + * top: 0, + * right: 0, + * bottom: 0, + * left: 0 + * }); + * ``` */ export const createEffectExtent = ({ top, right, bottom, left }: EffectExtentAttributes): XmlComponent => new BuilderElement({ diff --git a/src/file/drawing/extent/extent.ts b/src/file/drawing/extent/extent.ts index 1da44a67c5..a930913802 100644 --- a/src/file/drawing/extent/extent.ts +++ b/src/file/drawing/extent/extent.ts @@ -1,5 +1,18 @@ +/** + * Extent (size) for DrawingML objects. + * + * This module provides support for defining the size of DrawingML objects + * in inline drawings. + * + * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_extent_topic_ID0EQB4OB.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Attributes for extent. + */ type ExtentAttributes = { /** * ## Extent Length @@ -37,17 +50,28 @@ type ExtentAttributes = { }; /** - * This element specifies the extents of the parent `DrawingML` object within the document (i.e. its final height and width). + * Creates an extent element for inline drawings. + * + * This element specifies the extents of the parent DrawingML object within + * the document (i.e. its final height and width). * * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_extent_topic_ID0EQB4OB.html * * ## XSD Schema - * * ```xml - * - * - * - * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a 1-inch by 1-inch extent + * const extent = createExtent({ + * x: 914400, + * y: 914400 + * }); * ``` */ export const createExtent = ({ x, y }: ExtentAttributes): XmlComponent => diff --git a/src/file/drawing/floating/horizontal-position.ts b/src/file/drawing/floating/horizontal-position.ts index 4e6e32d889..2f68ccb106 100644 --- a/src/file/drawing/floating/horizontal-position.ts +++ b/src/file/drawing/floating/horizontal-position.ts @@ -1,4 +1,13 @@ -// http://officeopenxml.com/drwPicFloating-position.php +/** + * Horizontal position module for floating drawings in WordprocessingML documents. + * + * This module provides horizontal positioning for floating drawing objects, + * specifying the horizontal placement relative to a base element. + * + * Reference: http://officeopenxml.com/drwPicFloating-position.php + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createAlign } from "./align"; @@ -6,9 +15,41 @@ import { HorizontalPositionRelativeFrom, IHorizontalPositionOptions } from "./fl import { createPositionOffset } from "./position-offset"; /** - * Horizontal Positioning + * Creates a horizontal position element for floating drawings. + * + * The positionH element specifies the horizontal positioning of a floating + * object relative to a base element (page, margin, column, etc.). * * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionH-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @param options - Horizontal position configuration + * @returns The positionH XML element + * + * @example + * ```typescript + * // Align to the left of the page + * createHorizontalPosition({ + * relative: HorizontalPositionRelativeFrom.PAGE, + * align: HorizontalPositionAlign.LEFT, + * }); + * + * // Offset from the margin + * createHorizontalPosition({ + * relative: HorizontalPositionRelativeFrom.MARGIN, + * offset: 914400, // 1 inch in EMUs + * }); + * ``` */ export const createHorizontalPosition = ({ relative, align, offset }: IHorizontalPositionOptions): XmlComponent => new BuilderElement<{ diff --git a/src/file/drawing/floating/index.ts b/src/file/drawing/floating/index.ts index 80061d16e1..7e57a972d4 100644 --- a/src/file/drawing/floating/index.ts +++ b/src/file/drawing/floating/index.ts @@ -1,3 +1,8 @@ +/** + * Floating drawing position module exports. + * + * @module + */ export * from "./floating-position"; export * from "./simple-pos"; export * from "./horizontal-position"; diff --git a/src/file/drawing/floating/vertical-position.ts b/src/file/drawing/floating/vertical-position.ts index bacd08819a..ee39cde8f5 100644 --- a/src/file/drawing/floating/vertical-position.ts +++ b/src/file/drawing/floating/vertical-position.ts @@ -1,4 +1,13 @@ -// http://officeopenxml.com/drwPicFloating-position.php +/** + * Vertical position module for floating drawings in WordprocessingML documents. + * + * This module provides vertical positioning for floating drawing objects, + * specifying the vertical placement relative to a base element. + * + * Reference: http://officeopenxml.com/drwPicFloating-position.php + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createAlign } from "./align"; @@ -6,11 +15,41 @@ import { IVerticalPositionOptions, VerticalPositionRelativeFrom } from "./floati import { createPositionOffset } from "./position-offset"; /** - * Vertical Positioning + * Creates a vertical position element for floating drawings. * - * This simple type specifies the possible values for the base from which the relative vertical positioning of an object shall be calculated. + * The positionV element specifies the vertical positioning of a floating + * object relative to a base element (page, margin, paragraph, line, etc.). * * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionV-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @param options - Vertical position configuration + * @returns The positionV XML element + * + * @example + * ```typescript + * // Align to the top of the page + * createVerticalPosition({ + * relative: VerticalPositionRelativeFrom.PAGE, + * align: VerticalPositionAlign.TOP, + * }); + * + * // Offset from the paragraph + * createVerticalPosition({ + * relative: VerticalPositionRelativeFrom.PARAGRAPH, + * offset: 457200, // 0.5 inch in EMUs + * }); + * ``` */ export const createVerticalPosition = ({ relative, align, offset }: IVerticalPositionOptions): XmlComponent => new BuilderElement<{ diff --git a/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-lock-attributes.ts b/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-lock-attributes.ts index 96024b7682..48712a6e11 100644 --- a/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-lock-attributes.ts +++ b/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-lock-attributes.ts @@ -1,7 +1,15 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for graphic frame locking properties. + * + * Defines the XML attributes that control which operations are forbidden + * on a graphic frame element. + */ export class GraphicFrameLockAttributes extends XmlAttributeComponent<{ + /** DrawingML namespace declaration */ readonly xmlns?: string; + /** Disallow aspect ratio changes (0=allow, 1=disallow) */ readonly noChangeAspect?: number; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-locks.ts b/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-locks.ts index c22a603d8c..bdb2a907db 100644 --- a/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-locks.ts +++ b/src/file/drawing/graphic-frame/graphic-frame-locks/graphic-frame-locks.ts @@ -2,6 +2,35 @@ import { XmlComponent } from "@file/xml-components"; import { GraphicFrameLockAttributes } from "./graphic-frame-lock-attributes"; +/** + * Represents graphic frame locking properties in DrawingML. + * + * This element specifies all locking properties for a graphic frame. These properties + * inform the generating application about which operations are forbidden on the parent + * graphic frame. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const locks = new GraphicFrameLocks(); + * ``` + */ export class GraphicFrameLocks extends XmlComponent { public constructor() { super("a:graphicFrameLocks"); diff --git a/src/file/drawing/index.ts b/src/file/drawing/index.ts index 8a1a62a201..5b31b801d0 100644 --- a/src/file/drawing/index.ts +++ b/src/file/drawing/index.ts @@ -1,3 +1,8 @@ +/** + * Drawing module exports. + * + * @module + */ export * from "./drawing"; export * from "./text-wrap"; export * from "./floating"; diff --git a/src/file/drawing/inline/graphic/graphic-data/graphic-data-attribute.ts b/src/file/drawing/inline/graphic/graphic-data/graphic-data-attribute.ts index 09c9074308..1c43484864 100644 --- a/src/file/drawing/inline/graphic/graphic-data/graphic-data-attribute.ts +++ b/src/file/drawing/inline/graphic/graphic-data/graphic-data-attribute.ts @@ -1,6 +1,24 @@ +/** + * Graphic data attributes module. + * + * This module defines the URI attribute that identifies the type + * of graphical content within a graphicData element. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * XML attributes component for graphic data. + * + * The URI attribute identifies the schema namespace of the content + * stored in the graphicData element. For pictures, this is typically + * "http://schemas.openxmlformats.org/drawingml/2006/picture". + * + * @internal + */ export class GraphicDataAttributes extends XmlAttributeComponent<{ + /** URI identifying the type of graphical content */ readonly uri?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/graphic-data.ts b/src/file/drawing/inline/graphic/graphic-data/graphic-data.ts index 0ca40ef9ed..28f1314c3f 100644 --- a/src/file/drawing/inline/graphic/graphic-data/graphic-data.ts +++ b/src/file/drawing/inline/graphic/graphic-data/graphic-data.ts @@ -1,3 +1,13 @@ +/** + * Graphic data module for DrawingML elements. + * + * This module provides the graphicData element that contains + * the actual graphical content within a graphic element. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { IMediaData, IMediaDataTransformation } from "@file/media"; import { XmlComponent } from "@file/xml-components"; @@ -5,6 +15,34 @@ import { GraphicDataAttributes } from "./graphic-data-attribute"; import { Pic } from "./pic"; import { OutlineOptions } from "./pic/shape-properties/outline/outline"; +/** + * Represents graphical data within a DrawingML graphic element. + * + * GraphicData contains the actual picture, chart, or other graphical + * content referenced by a graphic element. It uses a URI to identify + * the type of content being stored. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const graphicData = new GraphicData({ + * mediaData: imageData, + * transform: transformation, + * outline: { color: "000000", width: 9525 } + * }); + * ``` + */ export class GraphicData extends XmlComponent { private readonly pic: Pic; diff --git a/src/file/drawing/inline/graphic/graphic-data/index.ts b/src/file/drawing/inline/graphic/graphic-data/index.ts index 1196483b8a..4ecd153f4c 100644 --- a/src/file/drawing/inline/graphic/graphic-data/index.ts +++ b/src/file/drawing/inline/graphic/graphic-data/index.ts @@ -1 +1,6 @@ +/** + * Graphic data module exports. + * + * @module + */ export * from "./graphic-data"; diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-extentions.ts b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-extentions.ts index e15c132c58..b916b799bf 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-extentions.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-extentions.ts @@ -1,6 +1,26 @@ +/** + * Blip extensions module for SVG support. + * + * This module provides extension elements that enable SVG image support + * within blip elements using Office-specific extensions. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { IMediaData } from "@file/media"; import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates an SVG blip element for embedding SVG images. + * + * This element is a Microsoft Office extension that allows SVG images + * to be referenced within a blip. + * + * @param mediaData - The media data containing the SVG image information + * @returns An XML component representing the SVG blip element + * @internal + */ const createSvgBlip = (mediaData: IMediaData): XmlComponent => new BuilderElement({ name: "asvg:svgBlip", @@ -16,6 +36,16 @@ const createSvgBlip = (mediaData: IMediaData): XmlComponent => }, }); +/** + * Creates an extension element for SVG support. + * + * This element wraps the SVG blip extension with the appropriate URI + * to identify it as an SVG extension. + * + * @param mediaData - The media data containing the SVG image information + * @returns An XML component representing the extension element + * @internal + */ const createExtention = (mediaData: IMediaData): XmlComponent => new BuilderElement({ name: "a:ext", @@ -28,6 +58,24 @@ const createExtention = (mediaData: IMediaData): XmlComponent => children: [createSvgBlip(mediaData)], }); +/** + * Creates an extension list for SVG images. + * + * This element contains the extensions needed to embed SVG images + * within a blip. It wraps the SVG-specific extension elements. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @param mediaData - The media data containing the SVG image information + * @returns An XML component representing the extension list + */ export const createExtentionList = (mediaData: IMediaData): XmlComponent => new BuilderElement({ name: "a:extLst", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-fill.ts b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-fill.ts index 5f9bacebed..cc75f3733d 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-fill.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip-fill.ts @@ -1,3 +1,13 @@ +/** + * Blip fill module for DrawingML pictures. + * + * This module defines how an image (blip) fills a picture shape, + * including stretching and cropping options. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { IMediaData } from "@file/media"; import { XmlComponent } from "@file/xml-components"; @@ -5,6 +15,32 @@ import { createBlip } from "./blip"; import { SourceRectangle } from "./source-rectangle"; import { Stretch } from "./stretch"; +/** + * Represents a blip fill for pictures in DrawingML. + * + * This element specifies the type of fill used for a picture. It contains the blip (image) + * reference, an optional source rectangle, and the fill mode (typically stretch). + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const blipFill = new BlipFill(mediaData); + * ``` + */ export class BlipFill extends XmlComponent { public constructor(mediaData: IMediaData) { super("pic:blipFill"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip.ts b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip.ts index e57274c373..a6eda8f177 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/blip/blip.ts @@ -1,13 +1,71 @@ +/** + * Blip (Binary Large Image or Picture) module for DrawingML. + * + * This module provides the blip element that references the actual + * image data within a picture. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { IMediaData } from "@file/media"; import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createExtentionList } from "./blip-extentions"; +/** + * Attributes for a blip element. + */ type BlipAttributes = { + /** Relationship ID of the embedded image */ readonly embed: string; + /** Compression state of the image */ readonly cstate: string; }; +/** + * Creates a blip element for an image. + * + * A blip references the actual image data stored in the document package + * through a relationship ID. For SVG images, it includes extensions that + * reference the SVG data. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @param mediaData - The media data containing the image information + * @returns An XML component representing the blip element + */ export const createBlip = (mediaData: IMediaData): XmlComponent => new BuilderElement({ name: "a:blip", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/blip/source-rectangle.ts b/src/file/drawing/inline/graphic/graphic-data/pic/blip/source-rectangle.ts index 7ea1e64bcc..d6f72319d0 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/blip/source-rectangle.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/blip/source-rectangle.ts @@ -1,5 +1,37 @@ +/** + * Source rectangle module for blip fills. + * + * This module defines the portion of an image to use when filling a shape. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a source rectangle for blip fills. + * + * This element specifies a portion of the blip (image) to use as the fill. + * When not specified with attributes, it indicates the entire blip should be used. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const srcRect = new SourceRectangle(); + * ``` + */ export class SourceRectangle extends XmlComponent { public constructor() { super("a:srcRect"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/blip/stretch.ts b/src/file/drawing/inline/graphic/graphic-data/pic/blip/stretch.ts index 71ca6c5e8d..0499ed94cb 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/blip/stretch.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/blip/stretch.ts @@ -1,11 +1,61 @@ +/** + * Stretch fill module for blip fills. + * + * This module defines how images are stretched to fill shapes. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a fill rectangle for stretch fill mode. + * + * This element specifies the rectangular area of the shape to which + * the blip fill should be stretched. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ class FillRectangle extends XmlComponent { public constructor() { super("a:fillRect"); } } +/** + * Represents a stretch fill mode for blip fills. + * + * This element specifies that the blip (image) should be stretched to fill + * the entire shape. The stretch fill is one of the fill mode properties + * that determines how an image is applied to a shape. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const stretch = new Stretch(); + * ``` + */ export class Stretch extends XmlComponent { public constructor() { super("a:stretch"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/index.ts b/src/file/drawing/inline/graphic/graphic-data/pic/index.ts index 84e1d96f7b..5185e8c730 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/index.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/index.ts @@ -1 +1,6 @@ +/** + * Picture module exports. + * + * @module + */ export * from "./pic"; diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/child-non-visual-pic-properties.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/child-non-visual-pic-properties.ts index 18ca70c711..94dbb7a390 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/child-non-visual-pic-properties.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/child-non-visual-pic-properties.ts @@ -1,7 +1,42 @@ +/** + * Child non-visual picture properties module. + * + * This module provides picture-specific non-visual properties including + * locking settings that control operations on the picture. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { PicLocks } from "./pic-locks/pic-locks"; +/** + * Represents non-visual picture drawing properties. + * + * This element specifies the non-visual properties specific to a picture. + * These properties include picture-specific locking settings that control + * which operations are allowed on the picture. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const cNvPicPr = new ChildNonVisualProperties(); + * ``` + */ export class ChildNonVisualProperties extends XmlComponent { public constructor() { super("pic:cNvPicPr"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks-attributes.ts index 448eec9057..349791e5a7 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks-attributes.ts @@ -1,7 +1,25 @@ +/** + * Picture locks attributes module. + * + * This module defines the attributes that control locking behavior + * for picture elements. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for picture locking properties. + * + * Defines the XML attributes that control which operations are forbidden + * on a picture element. + * + * @internal + */ export class PicLocksAttributes extends XmlAttributeComponent<{ + /** Disallow aspect ratio changes (0=allow, 1=disallow) */ readonly noChangeAspect?: number; + /** Disallow arrowhead changes (0=allow, 1=disallow) */ readonly noChangeArrowheads?: number; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks.ts index 594b3da755..2d7754f9aa 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/child-non-visual-pic-properties/pic-locks/pic-locks.ts @@ -1,7 +1,51 @@ +/** + * Picture locks module. + * + * This module provides locking settings for pictures that control + * which operations are allowed on the picture element. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { PicLocksAttributes } from "./pic-locks-attributes"; +/** + * Represents picture locking properties in DrawingML. + * + * This element specifies all locking properties for a picture. These properties + * inform the generating application about which operations are forbidden on the + * parent picture object. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const locks = new PicLocks(); + * ``` + */ export class PicLocks extends XmlComponent { public constructor() { super("a:picLocks"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-pic-properties.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-pic-properties.ts index 6e28a27e13..a29848d66e 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-pic-properties.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-pic-properties.ts @@ -1,8 +1,42 @@ +/** + * Non-visual picture properties module. + * + * This module provides metadata and locking settings for pictures + * that don't affect their visual appearance. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { ChildNonVisualProperties } from "./child-non-visual-pic-properties/child-non-visual-pic-properties"; import { NonVisualProperties } from "./non-visual-properties/non-visual-properties"; +/** + * Represents non-visual picture properties. + * + * This element specifies non-visual properties for a picture. These properties + * include metadata like name, description, and locking settings that don't affect + * the visual appearance of the picture. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const nvPicPr = new NonVisualPicProperties(); + * ``` + */ export class NonVisualPicProperties extends XmlComponent { public constructor() { super("pic:nvPicPr"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties-attributes.ts index b3a4cfc47b..49dd4b805e 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties-attributes.ts @@ -1,8 +1,26 @@ +/** + * Non-visual properties attributes module. + * + * This module defines the attributes for non-visual drawing properties + * including ID, name, and description. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for non-visual drawing properties. + * + * Defines the identification and descriptive attributes for DrawingML objects. + * + * @internal + */ export class NonVisualPropertiesAttributes extends XmlAttributeComponent<{ + /** Unique identifier for the drawing element */ readonly id?: number; + /** Name of the drawing element */ readonly name?: string; + /** Description of the drawing element */ readonly descr?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties.ts b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties.ts index 880b79dcab..d9e9283682 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/non-visual-pic-properties/non-visual-properties/non-visual-properties.ts @@ -1,21 +1,48 @@ +/** + * Non-visual drawing properties module. + * + * This module provides basic metadata for drawing elements including + * ID, name, description, and hyperlink support. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ import { createHyperlinkClick } from "@file/drawing/doc-properties/doc-properties-children"; import { ConcreteHyperlink } from "@file/paragraph"; import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; import { NonVisualPropertiesAttributes } from "./non-visual-properties-attributes"; -// -// -// -// -// -// -// -// -// -// -// - +/** + * Represents non-visual drawing properties for pictures. + * + * This element specifies non-visual properties for a DrawingML object. + * These include identification, naming, description, and hyperlink properties. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const cNvPr = new NonVisualProperties(); + * ``` + */ export class NonVisualProperties extends XmlComponent { public constructor() { super("pic:cNvPr"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/pic-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/pic-attributes.ts index cc234b4976..531d32725e 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/pic-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/pic-attributes.ts @@ -1,6 +1,21 @@ +/** + * Picture attributes module. + * + * This module defines the XML namespace attribute for picture elements. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for picture elements. + * + * Defines the XML namespace declaration for picture elements in DrawingML. + * + * @internal + */ export class PicAttributes extends XmlAttributeComponent<{ + /** Picture namespace declaration (http://schemas.openxmlformats.org/drawingml/2006/picture) */ readonly xmlns?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/pic.ts b/src/file/drawing/inline/graphic/graphic-data/pic/pic.ts index da43e86f0a..65ef360093 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/pic.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/pic.ts @@ -1,3 +1,13 @@ +/** + * Picture module for DrawingML elements. + * + * This module provides the picture element that represents an image + * within a DrawingML graphic. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * @module + */ // http://officeopenxml.com/drwPic.php import { IMediaData, IMediaDataTransformation } from "@file/media"; import { XmlComponent } from "@file/xml-components"; @@ -8,6 +18,34 @@ import { PicAttributes } from "./pic-attributes"; import { OutlineOptions } from "./shape-properties/outline/outline"; import { ShapeProperties } from "./shape-properties/shape-properties"; +/** + * Represents a picture element in DrawingML. + * + * A picture contains non-visual properties, image data (blip fill), + * and shape properties that define how the image is displayed. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const pic = new Pic({ + * mediaData: imageData, + * transform: { emus: { x: 914400, y: 914400 } }, + * outline: { color: "000000", width: 9525 } + * }); + * ``` + */ export class Pic extends XmlComponent { public constructor({ mediaData, diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents-attributes.ts index 985efe9aa1..eae1de78b8 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents-attributes.ts @@ -1,7 +1,29 @@ +/** + * Extents attributes for DrawingML shapes. + * + * This module defines the width and height attributes for shape extents. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for shape extents (size). + * + * Defines the width (cx) and height (cy) in EMUs. + * + * ## XSD Schema + * ```xml + * + * + * ``` + * + * @internal + */ export class ExtentsAttributes extends XmlAttributeComponent<{ + /** Width in EMUs (English Metric Units) */ readonly cx?: number; + /** Height in EMUs (English Metric Units) */ readonly cy?: number; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents.ts index 4aa40e8a02..703ac7d3a6 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/extents/extents.ts @@ -1,8 +1,39 @@ +/** + * Extents (size) element for DrawingML shapes. + * + * This module defines the size of a shape or picture in EMUs. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * + * @module + */ // http://officeopenxml.com/drwSp-size.php import { XmlComponent } from "@file/xml-components"; import { ExtentsAttributes } from "./extents-attributes"; +/** + * Represents the extents (size) of a DrawingML shape. + * + * Defines the width and height of the shape in English Metric Units (EMUs). + * One EMU equals 1/914,400 of an inch. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a 1-inch by 1-inch shape + * const extents = new Extents(914400, 914400); + * ``` + */ export class Extents extends XmlComponent { private readonly attributes: ExtentsAttributes; diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/form.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/form.ts index ca413ca958..bdaa9d3213 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/form.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/form.ts @@ -1,3 +1,14 @@ +/** + * 2D transform (form) for DrawingML shapes. + * + * This module provides transformation support including position, size, + * rotation, and flip operations for shapes and pictures. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * Reference: http://officeopenxml.com/drwSp-rotate.php + * + * @module + */ // http://officeopenxml.com/drwSp-size.php // http://officeopenxml.com/drwSp-rotate.php import { IMediaDataTransformation } from "@file/media"; @@ -6,9 +17,17 @@ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { Extents } from "./extents/extents"; import { Offset } from "./offset/off"; +/** + * Attributes for 2D transformation. + * + * Defines flip and rotation properties. + */ export class FormAttributes extends XmlAttributeComponent<{ + /** Flip vertically */ readonly flipVertical?: boolean; + /** Flip horizontally */ readonly flipHorizontal?: boolean; + /** Rotation angle in 60,000ths of a degree */ readonly rotation?: number; }> { protected readonly xmlKeys = { @@ -18,6 +37,36 @@ export class FormAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents a 2D transformation for DrawingML objects. + * + * This element defines how a shape or picture is positioned, sized, + * rotated, and flipped within the document. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const form = new Form({ + * emus: { x: 914400, y: 914400 }, + * flip: { horizontal: true, vertical: false }, + * rotation: 450000 // 7.5 degrees + * }); + * ``` + */ export class Form extends XmlComponent { private readonly extents: Extents; diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/index.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/index.ts index c4a75a7a69..b5b82d5d7f 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/index.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/index.ts @@ -1 +1,6 @@ +/** + * Shape properties form module exports. + * + * @module + */ export * from "./form"; diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off-attributes.ts index a122813e34..969c8af461 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off-attributes.ts @@ -1,7 +1,29 @@ +/** + * Offset attributes for DrawingML shapes. + * + * This module defines the x and y coordinate attributes for shape offset. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for shape offset (position). + * + * Defines the x and y coordinates in EMUs. + * + * ## XSD Schema + * ```xml + * + * + * ``` + * + * @internal + */ export class OffsetAttributes extends XmlAttributeComponent<{ + /** X coordinate in EMUs (English Metric Units) */ readonly x?: number; + /** Y coordinate in EMUs (English Metric Units) */ readonly y?: number; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off.ts index ab0ab07f77..32212a34ba 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/form/offset/off.ts @@ -1,8 +1,38 @@ +/** + * Offset (position) element for DrawingML shapes. + * + * This module defines the position of a shape or picture in EMUs. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * + * @module + */ // http://officeopenxml.com/drwSp-size.php import { XmlComponent } from "@file/xml-components"; import { OffsetAttributes } from "./off-attributes"; +/** + * Represents the offset (position) of a DrawingML shape. + * + * Defines the x and y coordinates of the shape's position in + * English Metric Units (EMUs). One EMU equals 1/914,400 of an inch. + * + * Reference: http://officeopenxml.com/drwSp-size.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * const offset = new Offset(); + * ``` + */ export class Offset extends XmlComponent { public constructor() { super("a:off"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/no-fill.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/no-fill.ts index 22fc607fb6..a3c81b111e 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/no-fill.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/no-fill.ts @@ -1,3 +1,25 @@ +/** + * No fill element for DrawingML shapes. + * + * This module provides the no-fill option for outline and shape fills. + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates a no-fill element. + * + * Specifies that the outline or shape should have no fill applied. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @example + * ```typescript + * const noFill = createNoFill(); + * ``` + */ export const createNoFill = (): XmlComponent => new BuilderElement({ name: "a:noFill" }); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/outline.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/outline.ts index 05e21c7464..a42bd03dce 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/outline.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/outline.ts @@ -1,4 +1,13 @@ -// http://officeopenxml.com/drwSp-outline.php +/** + * Outline (line) properties for DrawingML shapes. + * + * This module provides support for configuring outline properties including + * width, cap style, compound line types, and fill properties. + * + * Reference: http://officeopenxml.com/drwSp-outline.php + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createNoFill } from "./no-fill"; @@ -24,9 +33,18 @@ import { createSolidFill } from "./solid-fill"; // // // + +/** + * Line cap styles for outline endpoints. + * + * Defines how the ends of a line are rendered. + */ export const LineCap = { + /** Round cap style */ ROUND: "rnd", + /** Square cap style */ SQUARE: "sq", + /** Flat cap style */ FLAT: "flat", } as const; @@ -39,11 +57,22 @@ export const LineCap = { // // // + +/** + * Compound line types for outlines. + * + * Defines the structure of compound lines (single, double, etc.). + */ export const CompoundLine = { + /** Single line */ SINGLE: "sng", + /** Double line */ DOUBLE: "dbl", + /** Thick-thin double line */ THICK_THIN: "thickThin", + /** Thin-thick double line */ THIN_THICK: "thinThick", + /** Triple line */ TRI: "tri", } as const; @@ -53,34 +82,68 @@ export const CompoundLine = { // // // + +/** + * Pen alignment options for outline positioning. + * + * Defines how the outline is aligned relative to the shape edge. + */ export const PenAlignment = { + /** Center alignment */ CENTER: "ctr", + /** Inset alignment */ INSET: "in", } as const; +/** + * Attributes for configuring outline properties. + */ export type OutlineAttributes = { + /** Line width in EMUs (English Metric Units) */ readonly width?: number; + /** Line cap style */ readonly cap?: keyof typeof LineCap; + /** Compound line type */ readonly compoundLine?: keyof typeof CompoundLine; + /** Pen alignment */ readonly align?: keyof typeof PenAlignment; }; +/** + * No fill option for outline. + */ type OutlineNoFill = { + /** No fill type */ readonly type: "noFill"; }; +/** + * RGB solid fill for outline. + */ type OutlineRgbSolidFill = { + /** Solid fill type */ readonly type: "solidFill"; + /** RGB color type */ readonly solidFillType: "rgb"; + /** Hex color value (e.g., "FF0000" for red) */ readonly value: string; }; +/** + * Scheme-based solid fill for outline. + */ type OutlineSchemeSolidFill = { + /** Solid fill type */ readonly type: "solidFill"; + /** Scheme color type */ readonly solidFillType: "scheme"; + /** Scheme color value */ readonly value: (typeof SchemeColor)[keyof typeof SchemeColor]; }; +/** + * Union type for solid fill options. + */ type OutlineSolidFill = OutlineRgbSolidFill | OutlineSchemeSolidFill; // @@ -90,10 +153,54 @@ type OutlineSolidFill = OutlineRgbSolidFill | OutlineSchemeSolidFill; // // // + +/** + * Fill properties for outline. + */ type OutlineFillProperties = OutlineNoFill | OutlineSolidFill; +/** + * Complete outline configuration options. + * + * Combines outline attributes with fill properties. + */ export type OutlineOptions = OutlineAttributes & OutlineFillProperties; +/** + * Creates an outline element for DrawingML shapes. + * + * The outline element specifies the line properties for the shape border, + * including width, cap style, compound line type, alignment, and fill. + * + * Reference: http://officeopenxml.com/drwSp-outline.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create outline with RGB color + * const outline = createOutline({ + * width: 9525, + * cap: "ROUND", + * type: "solidFill", + * solidFillType: "rgb", + * value: "FF0000" + * }); + * ``` + */ export const createOutline = (options: OutlineOptions): XmlComponent => new BuilderElement({ name: "a:ln", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/rgb-color.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/rgb-color.ts index abc28ffc45..9ca0b96b35 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/rgb-color.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/rgb-color.ts @@ -1,6 +1,17 @@ +/** + * RGB color element for DrawingML shapes. + * + * This module provides RGB color support for solid fills. + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Options for RGB color. + */ type SolidRgbColorOptions = { + /** Hex color value (e.g., "FF0000" for red) */ readonly value: string; }; @@ -10,6 +21,28 @@ type SolidRgbColorOptions = { // // // + +/** + * Creates an sRGB color element. + * + * Specifies a color using RGB hex values. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const redColor = createSolidRgbColor({ value: "FF0000" }); + * const blueColor = createSolidRgbColor({ value: "0000FF" }); + * ``` + */ export const createSolidRgbColor = (options: SolidRgbColorOptions): XmlComponent => new BuilderElement({ name: "a:srgbClr", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/scheme-color.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/scheme-color.ts index 17004133a2..88af136c34 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/scheme-color.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/scheme-color.ts @@ -1,6 +1,18 @@ +/** + * Scheme color element for DrawingML shapes. + * + * This module provides scheme-based color support for solid fills, + * allowing colors to be defined using theme color schemes. + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Options for scheme color. + */ type SchemeColorOptions = { + /** Scheme color value */ readonly value: (typeof SchemeColor)[keyof typeof SchemeColor]; }; @@ -27,23 +39,46 @@ type SchemeColorOptions = { // // cspell:ignore folHlink, phClr, hlink + +/** + * Scheme color values for theme-based colors. + * + * These values reference colors defined in the document's color scheme/theme. + */ export const SchemeColor = { + /** Background color 1 */ BG1: "bg1", + /** Text color 1 */ TX1: "tx1", + /** Background color 2 */ BG2: "bg2", + /** Text color 2 */ TX2: "tx2", + /** Accent color 1 */ ACCENT1: "accent1", + /** Accent color 2 */ ACCENT2: "accent2", + /** Accent color 3 */ ACCENT3: "accent3", + /** Accent color 4 */ ACCENT4: "accent4", + /** Accent color 5 */ ACCENT5: "accent5", + /** Accent color 6 */ ACCENT6: "accent6", + /** Hyperlink color */ HLINK: "hlink", + /** Followed hyperlink color */ FOLHLINK: "folHlink", + /** Dark color 1 */ DK1: "dk1", + /** Light color 1 */ LT1: "lt1", + /** Dark color 2 */ DK2: "dk2", + /** Light color 2 */ LT2: "lt2", + /** Placeholder color */ PHCLR: "phClr", } as const; @@ -53,6 +88,28 @@ export const SchemeColor = { // // // + +/** + * Creates a scheme color element. + * + * Specifies a color using a theme color scheme reference. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const accentColor = createSchemeColor({ value: SchemeColor.ACCENT1 }); + * const bgColor = createSchemeColor({ value: SchemeColor.BG1 }); + * ``` + */ export const createSchemeColor = (options: SchemeColorOptions): XmlComponent => new BuilderElement({ name: "a:schemeClr", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/solid-fill.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/solid-fill.ts index aa8ec9c177..7a74a3d4b6 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/solid-fill.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/outline/solid-fill.ts @@ -1,20 +1,71 @@ +/** + * Solid fill element for DrawingML shapes. + * + * This module provides solid fill support for outlines and shapes, + * supporting both RGB and scheme-based colors. + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createSolidRgbColor } from "./rgb-color"; import { SchemeColor, createSchemeColor } from "./scheme-color"; +/** + * RGB color options for solid fill. + */ export type RgbColorOptions = { + /** RGB color type */ readonly type: "rgb"; + /** Hex color value (e.g., "FF0000" for red) */ readonly value: string; }; +/** + * Scheme color options for solid fill. + */ export type SchemeColorOptions = { + /** Scheme color type */ readonly type: "scheme"; + /** Scheme color value */ readonly value: (typeof SchemeColor)[keyof typeof SchemeColor]; }; +/** + * Union type for solid fill options. + */ export type SolidFillOptions = RgbColorOptions | SchemeColorOptions; +/** + * Creates a solid fill element. + * + * Specifies a solid color fill using either RGB or scheme colors. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // RGB solid fill + * const fill = createSolidFill({ + * type: "rgb", + * value: "FF0000" + * }); + * + * // Scheme solid fill + * const schemeFill = createSolidFill({ + * type: "scheme", + * value: SchemeColor.ACCENT1 + * }); + * ``` + */ export const createSolidFill = (options: SolidFillOptions): XmlComponent => new BuilderElement({ name: "a:solidFill", diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/adjustment-values/adjustment-values.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/adjustment-values/adjustment-values.ts index 063d9899e1..3bd9645ad8 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/adjustment-values/adjustment-values.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/adjustment-values/adjustment-values.ts @@ -1,6 +1,37 @@ -// http://officeopenxml.com/drwSp-prstGeom.php +/** + * Adjustment values module for preset geometries. + * + * This module provides adjustment value lists that can modify the appearance + * of preset shape geometries. + * + * Reference: http://officeopenxml.com/drwSp-prstGeom.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a list of adjustment values for preset geometry. + * + * This element contains a list of shape adjust values that modify the + * appearance of a preset geometric shape. When empty, default values are used. + * + * Reference: http://officeopenxml.com/drwSp-prstGeom.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const avLst = new AdjustmentValues(); + * ``` + */ export class AdjustmentValues extends XmlComponent { public constructor() { super("a:avLst"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry-attributes.ts index ba6dae1121..a3c7b4c886 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry-attributes.ts @@ -1,6 +1,26 @@ +/** + * Preset geometry attributes for DrawingML shapes. + * + * This module defines the shape type attribute for preset geometries. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for preset geometry. + * + * Defines the shape type identifier for a preset geometry. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @internal + */ export class PresetGeometryAttributes extends XmlAttributeComponent<{ + /** Preset shape type (e.g., "rect", "ellipse", "triangle") */ readonly prst?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry.ts index 8b38aa1842..8f88e391b0 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/preset-geometry/preset-geometry.ts @@ -1,9 +1,42 @@ -// http://officeopenxml.com/drwSp-prstGeom.php +/** + * Preset geometry module for DrawingML shapes. + * + * This module provides predefined shape geometries that can be applied + * to pictures and shapes without requiring custom path definitions. + * + * Reference: http://officeopenxml.com/drwSp-prstGeom.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { AdjustmentValues } from "./adjustment-values/adjustment-values"; import { PresetGeometryAttributes } from "./preset-geometry-attributes"; +/** + * Represents a preset geometry for a DrawingML shape. + * + * This element specifies when a preset geometric shape should be used instead + * of a custom geometry. It includes a shape preset identifier and optional + * adjustment values that modify the base shape. + * + * Reference: http://officeopenxml.com/drwSp-prstGeom.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const geometry = new PresetGeometry(); + * ``` + */ export class PresetGeometry extends XmlComponent { public constructor() { super("a:prstGeom"); diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties-attributes.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties-attributes.ts index 1f2bc8d230..2b7f7ba3b7 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties-attributes.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties-attributes.ts @@ -1,6 +1,26 @@ +/** + * Shape properties attributes for DrawingML. + * + * This module defines attributes for shape properties. + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for shape properties. + * + * Defines optional attributes such as black and white mode. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @internal + */ export class ShapePropertiesAttributes extends XmlAttributeComponent<{ + /** Black and white display mode */ readonly bwMode?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties.ts b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties.ts index fb00d37eaa..3a753338ca 100644 --- a/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties.ts +++ b/src/file/drawing/inline/graphic/graphic-data/pic/shape-properties/shape-properties.ts @@ -1,3 +1,13 @@ +/** + * Shape properties for DrawingML pictures. + * + * This module provides the shape properties element which defines visual + * characteristics of a picture including transformation, geometry, and outline. + * + * Reference: http://officeopenxml.com/drwSp-SpPr.php + * + * @module + */ // http://officeopenxml.com/drwSp-SpPr.php import { IMediaDataTransformation } from "@file/media"; import { XmlComponent } from "@file/xml-components"; @@ -8,6 +18,49 @@ import { OutlineOptions, createOutline } from "./outline/outline"; import { PresetGeometry } from "./preset-geometry/preset-geometry"; import { ShapePropertiesAttributes } from "./shape-properties-attributes"; +/** + * Represents shape properties for a DrawingML picture. + * + * This element defines the visual formatting of a picture, including + * its transform (size, position, rotation, flip), geometry preset, + * and outline properties. + * + * Reference: http://officeopenxml.com/drwSp-SpPr.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const shapeProps = new ShapeProperties({ + * transform: { + * emus: { x: 914400, y: 914400 }, + * flip: { horizontal: false, vertical: false }, + * rotation: 0 + * }, + * outline: { + * width: 9525, + * type: "solidFill", + * solidFillType: "rgb", + * value: "FF0000" + * } + * }); + * ``` + */ export class ShapeProperties extends XmlComponent { private readonly form: Form; diff --git a/src/file/drawing/inline/graphic/graphic.ts b/src/file/drawing/inline/graphic/graphic.ts index 0bebd6e784..e196ba6c40 100644 --- a/src/file/drawing/inline/graphic/graphic.ts +++ b/src/file/drawing/inline/graphic/graphic.ts @@ -29,6 +29,26 @@ class GraphicAttributes extends XmlAttributeComponent<{ * * Graphic is the container for graphical content such as * pictures, shapes, and charts within a drawing. + * + * Reference: http://officeopenxml.com/drwPic.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const graphic = new Graphic({ + * mediaData: imageData, + * transform: transformation, + * outline: { color: "FF0000", width: 9525 } + * }); + * ``` */ export class Graphic extends XmlComponent { private readonly data: GraphicData; diff --git a/src/file/drawing/inline/graphic/index.ts b/src/file/drawing/inline/graphic/index.ts index 246194dba6..908a716ba2 100644 --- a/src/file/drawing/inline/graphic/index.ts +++ b/src/file/drawing/inline/graphic/index.ts @@ -1 +1,6 @@ +/** + * Graphic module exports. + * + * @module + */ export * from "./graphic"; diff --git a/src/file/drawing/inline/index.ts b/src/file/drawing/inline/index.ts index 2fdaa4a91f..475bcdefcf 100644 --- a/src/file/drawing/inline/index.ts +++ b/src/file/drawing/inline/index.ts @@ -1 +1,6 @@ +/** + * Inline drawing module exports. + * + * @module + */ export * from "./inline"; diff --git a/src/file/drawing/text-wrap/index.ts b/src/file/drawing/text-wrap/index.ts index ce8c0bbd13..07504f9bd0 100644 --- a/src/file/drawing/text-wrap/index.ts +++ b/src/file/drawing/text-wrap/index.ts @@ -1,3 +1,8 @@ +/** + * Text wrap module exports. + * + * @module + */ export * from "./text-wrapping"; export * from "./wrap-none"; export * from "./wrap-square"; diff --git a/src/file/file.ts b/src/file/file.ts index ea011b3388..c15d10e7d8 100644 --- a/src/file/file.ts +++ b/src/file/file.ts @@ -31,31 +31,57 @@ import { DefaultStylesFactory } from "./styles/factory"; * Options for a document section. * * Each section can have its own headers, footers, and page properties. + * + * @property headers - Optional header definitions for the section + * @property headers.default - Default header for all pages (when first/even not specified) + * @property headers.first - Header for the first page of the section + * @property headers.even - Header for even-numbered pages + * @property footers - Optional footer definitions for the section + * @property footers.default - Default footer for all pages (when first/even not specified) + * @property footers.first - Footer for the first page of the section + * @property footers.even - Footer for even-numbered pages + * @property properties - Section properties such as page size, margins, and orientation + * @property children - Array of content elements (paragraphs, tables, etc.) for this section */ export type ISectionOptions = { + /** Optional header definitions for the section. */ readonly headers?: { + /** Default header for all pages (when first/even not specified). */ readonly default?: Header; + /** Header for the first page of the section. */ readonly first?: Header; + /** Header for even-numbered pages. */ readonly even?: Header; }; + /** Optional footer definitions for the section. */ readonly footers?: { + /** Default footer for all pages (when first/even not specified). */ readonly default?: Footer; + /** Footer for the first page of the section. */ readonly first?: Footer; + /** Footer for even-numbered pages. */ readonly even?: Footer; }; + /** Section properties such as page size, margins, and orientation. */ readonly properties?: ISectionPropertiesOptions; + /** Array of content elements (paragraphs, tables, etc.) for this section. */ readonly children: readonly FileChild[]; }; /** * Represents a Word document file. * - * The File class is the main entry point for creating DOCX documents. - * It manages all document components including content, styles, numbering, - * headers/footers, and media. + * The File class (exported as `Document`) is the main entry point for creating DOCX documents. + * It manages all document components including content, styles, numbering, headers/footers, + * and media. Documents are organized into sections, each of which can have its own page + * settings, headers, and footers. + * + * This class handles the assembly of all OOXML parts required for a valid .docx file, + * including relationships, content types, and document properties. * * @example * ```typescript + * // Simple document with one section * const doc = new Document({ * sections: [{ * children: [ @@ -63,6 +89,55 @@ export type ISectionOptions = { * ], * }], * }); + * + * // Document with multiple sections and headers/footers + * const doc = new Document({ + * creator: "John Doe", + * sections: [ + * { + * headers: { + * default: new Header({ + * children: [new Paragraph("Header Text")], + * }), + * }, + * children: [ + * new Paragraph("Section 1 content"), + * ], + * }, + * { + * children: [ + * new Paragraph("Section 2 content"), + * ], + * }, + * ], + * }); + * + * // Document with custom styles and numbering + * const doc = new Document({ + * styles: { + * paragraphStyles: [ + * { + * id: "MyHeading", + * name: "My Heading", + * basedOn: "Heading1", + * run: { bold: true, color: "FF0000" }, + * }, + * ], + * }, + * numbering: { + * config: [ + * { + * reference: "my-numbering", + * levels: [ + * { level: 0, format: "decimal", text: "%1.", alignment: "left" }, + * ], + * }, + * ], + * }, + * sections: [{ + * children: [new Paragraph("Content")], + * }], + * }); * ``` */ export class File { diff --git a/src/file/fonts/create-regular-font.ts b/src/file/fonts/create-regular-font.ts index e72bd6541c..1eb98deb0f 100644 --- a/src/file/fonts/create-regular-font.ts +++ b/src/file/fonts/create-regular-font.ts @@ -1,7 +1,41 @@ +/** + * Create Regular Font module for WordprocessingML documents. + * + * Provides a helper to create regular (non-bold, non-italic) embedded fonts + * with default font signature settings. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { CharacterSet, createFont } from "./font"; +/** + * Creates a regular embedded font with default settings. + * + * This helper function creates a font definition with standard font signature + * values that work for most common fonts. The signature specifies Unicode + * and code page ranges supported by the font. + * + * @param options - Font creation options + * @param options.name - Font name + * @param options.index - Font relationship index + * @param options.fontKey - Unique font key (GUID) for obfuscation + * @param options.characterSet - Optional character set identifier + * + * @returns XmlComponent representing the font definition + * + * @example + * ```typescript + * const font = createRegularFont({ + * name: "Arial", + * index: 1, + * fontKey: "12345678-1234-1234-1234-123456789012" + * }); + * ``` + */ export const createRegularFont = ({ name, index, diff --git a/src/file/fonts/font-wrapper.ts b/src/file/fonts/font-wrapper.ts index 5013df398d..65667fcdd5 100644 --- a/src/file/fonts/font-wrapper.ts +++ b/src/file/fonts/font-wrapper.ts @@ -1,3 +1,12 @@ +/** + * Font Wrapper module for WordprocessingML documents. + * + * Manages font table and relationships for embedded fonts. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_fonts.html + * + * @module + */ import { IViewWrapper } from "@file/document-wrapper"; import { Relationships } from "@file/relationships"; import { XmlComponent } from "@file/xml-components"; @@ -5,8 +14,24 @@ import { uniqueUuid } from "@util/convenience-functions"; import { FontOptions, createFontTable } from "./font-table"; +/** + * Font options extended with a unique font key. + */ export type FontOptionsWithKey = FontOptions & { readonly fontKey: string }; +/** + * Wrapper class for managing the font table and its relationships. + * + * Creates a font table with embedded font files and manages the relationships + * required for font embedding. Each font is assigned a unique key for obfuscation. + * + * @example + * ```typescript + * const fontWrapper = new FontWrapper([ + * { name: "CustomFont", data: fontBuffer } + * ]); + * ``` + */ export class FontWrapper implements IViewWrapper { private readonly fontTable: XmlComponent; private readonly relationships: Relationships; diff --git a/src/file/fonts/font.ts b/src/file/fonts/font.ts index 8a62c0018d..2dff282e8f 100644 --- a/src/file/fonts/font.ts +++ b/src/file/fonts/font.ts @@ -1,47 +1,36 @@ +/** + * Font module for WordprocessingML documents. + * + * Provides support for font definitions and embedded fonts. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html + * + * @module + */ import { BuilderElement, OnOffElement, XmlComponent, createStringElement } from "@file/xml-components"; -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// - -// -// -// -// -// -// -// -// - -// http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html +/** + * Options for a font relationship (embedded font). + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html + * + * @property id - Relationship to Part + * @property fontKey - Embedded Font Obfuscation Key (GUID) + * @property subsetted - Whether the embedded font is subsetted + */ export type IFontRelationshipOptions = { - /** - * Relationship to Part - */ + /** Relationship to Part */ readonly id: string; - /** - * Embedded Font Obfuscation Key - */ + /** Embedded Font Obfuscation Key (GUID) */ readonly fontKey?: string; - /** - * Embedded Font Is Subsetted - */ + /** Whether the embedded font is subsetted */ readonly subsetted?: boolean; }; +/** + * Character set constants for font definitions. + * Maps character set names to their hexadecimal identifiers. + */ export const CharacterSet = { ANSI: "00", DEFAULT: "01", @@ -64,28 +53,67 @@ export const CharacterSet = { OEM: "FF", } as const; +/** + * Options for defining a font in the document. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html + * + * @property name - Font name (required) + * @property altName - Alternative font name + * @property panose1 - PANOSE-1 classification + * @property charset - Character set identifier + * @property family - Font family + * @property notTrueType - Whether this is not a TrueType font + * @property pitch - Font pitch + * @property sig - Font signature (Unicode and code page ranges) + * @property embedRegular - Embedded regular font relationship + * @property embedBold - Embedded bold font relationship + * @property embedItalic - Embedded italic font relationship + * @property embedBoldItalic - Embedded bold-italic font relationship + */ export type FontOptions = { + /** Font name (required) */ readonly name: string; + /** Alternative font name */ readonly altName?: string; + /** PANOSE-1 classification */ readonly panose1?: string; + /** Character set identifier */ readonly charset?: (typeof CharacterSet)[keyof typeof CharacterSet]; + /** Font family */ readonly family?: string; + /** Whether this is not a TrueType font */ readonly notTrueType?: boolean; + /** Font pitch */ readonly pitch?: string; + /** Font signature (Unicode and code page ranges) */ readonly sig?: { + /** Unicode Subset Bitfield 0 */ readonly usb0: string; + /** Unicode Subset Bitfield 1 */ readonly usb1: string; + /** Unicode Subset Bitfield 2 */ readonly usb2: string; + /** Unicode Subset Bitfield 3 */ readonly usb3: string; + /** Code Page Bitfield 0 */ readonly csb0: string; + /** Code Page Bitfield 1 */ readonly csb1: string; }; + /** Embedded regular font relationship */ readonly embedRegular?: IFontRelationshipOptions; + /** Embedded bold font relationship */ readonly embedBold?: IFontRelationshipOptions; + /** Embedded italic font relationship */ readonly embedItalic?: IFontRelationshipOptions; + /** Embedded bold-italic font relationship */ readonly embedBoldItalic?: IFontRelationshipOptions; }; +/** + * Creates a font relationship element for embedding fonts. + */ const createFontRelationship = ({ id, fontKey, subsetted }: IFontRelationshipOptions, name: string): XmlComponent => new BuilderElement({ name, @@ -96,6 +124,44 @@ const createFontRelationship = ({ id, fontKey, subsetted }: IFontRelationshipOpt children: [...(subsetted ? [new OnOffElement("w:subsetted", subsetted)] : [])], }); +/** + * Creates a font element with the specified options. + * + * This function builds a complete font definition including optional embedded font files, + * font signature, character set, and other font properties. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * const font = createFont({ + * name: "Arial", + * family: "swiss", + * pitch: "variable", + * charset: CharacterSet.ANSI + * }); + * ``` + */ export const createFont = ({ name, altName, @@ -110,7 +176,6 @@ export const createFont = ({ embedItalic, embedBoldItalic, }: FontOptions): XmlComponent => - // http://www.datypic.com/sc/ooxml/e-w_font-1.html new BuilderElement({ name: "w:font", attributes: { diff --git a/src/file/fonts/index.ts b/src/file/fonts/index.ts index 4476a0a9e1..939e830c09 100644 --- a/src/file/fonts/index.ts +++ b/src/file/fonts/index.ts @@ -1 +1,6 @@ +/** + * Fonts module exports. + * + * @module + */ export { CharacterSet } from "./font"; diff --git a/src/file/fonts/obfuscate-ttf-to-odttf.ts b/src/file/fonts/obfuscate-ttf-to-odttf.ts index 0213ca7b50..7b3afad323 100644 --- a/src/file/fonts/obfuscate-ttf-to-odttf.ts +++ b/src/file/fonts/obfuscate-ttf-to-odttf.ts @@ -1,7 +1,43 @@ +/** + * Font obfuscation module for embedding fonts in WordprocessingML documents. + * + * This module implements the OOXML font obfuscation algorithm used to embed + * fonts in DOCX documents. Obfuscation is required by the OOXML specification + * to prevent simple extraction of embedded font files. + * + * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding) + * + * @module + */ + +/** Start offset for obfuscation in the font file */ const obfuscatedStartOffset = 0; +/** End offset for obfuscation (first 32 bytes are obfuscated) */ const obfuscatedEndOffset = 32; +/** Expected GUID size (32 hex characters without dashes) */ const guidSize = 32; +/** + * Obfuscates a TrueType font file for embedding in OOXML documents. + * + * The obfuscation algorithm XORs the first 32 bytes of the font file + * with a reversed byte sequence derived from the font's GUID key. + * This prevents simple extraction while maintaining font functionality. + * + * @param buf - The original font file as a byte array + * @param fontKey - The GUID key for the font (with or without dashes) + * @returns The obfuscated font data + * @throws Error if the fontKey is not a valid 32-character GUID + * + * @example + * ```typescript + * const fontData = readFileSync("font.ttf"); + * const fontKey = "00000000-0000-0000-0000-000000000000"; + * const obfuscatedData = obfuscate(fontData, fontKey); + * ``` + * + * @internal + */ export const obfuscate = (buf: Uint8Array, fontKey: string): Uint8Array => { const guid = fontKey.replace(/-/g, ""); if (guid.length !== guidSize) { diff --git a/src/file/footer-wrapper.ts b/src/file/footer-wrapper.ts index cb078f1a8a..e239cc5a51 100644 --- a/src/file/footer-wrapper.ts +++ b/src/file/footer-wrapper.ts @@ -1,3 +1,14 @@ +/** + * Footer wrapper module for WordprocessingML documents. + * + * This module provides a wrapper for document footers, managing footer content + * along with their relationships and media. Footers can be configured for + * different pages (first, even, odd, default). + * + * Reference: http://officeopenxml.com/WPfooter.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { HeaderFooterReferenceType } from "./document"; @@ -8,11 +19,35 @@ import { Paragraph } from "./paragraph"; import { Relationships } from "./relationships"; import { Table } from "./table"; +/** + * Configuration for a document footer. + * + * @property footer - The FooterWrapper instance containing the footer content + * @property type - The footer type (default, first page, even pages) + */ export type IDocumentFooter = { readonly footer: FooterWrapper; readonly type: (typeof HeaderFooterReferenceType)[keyof typeof HeaderFooterReferenceType]; }; +/** + * Wrapper for document footers. + * + * FooterWrapper combines a Footer view with its Relationships and Media, + * enabling footers to contain paragraphs, tables, images, and hyperlinks. + * Each section can have multiple footers for different page types. + * + * Reference: http://officeopenxml.com/WPfooter.php + * + * @example + * ```typescript + * const footerWrapper = new FooterWrapper(media, 1); + * footerWrapper.add(new Paragraph("Page Footer")); + * footerWrapper.add(new Table({ + * rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Cell")] })] })], + * })); + * ``` + */ export class FooterWrapper implements IViewWrapper { private readonly footer: Footer; private readonly relationships: Relationships; diff --git a/src/file/footer/footer-attributes.ts b/src/file/footer/footer-attributes.ts index 58fa0ce8dd..cc5be52484 100644 --- a/src/file/footer/footer-attributes.ts +++ b/src/file/footer/footer-attributes.ts @@ -1,6 +1,35 @@ import { XmlAttributeComponent } from "@file/xml-components"; -export class FooterAttributes extends XmlAttributeComponent<{ +/** + * XML namespace attributes for footer elements. + * + * This interface defines all XML namespace declarations that can be used in footer elements, + * including WordprocessingML, DrawingML, VML, and various Office-specific namespaces. + * + * @property wpc - WordprocessingML Canvas namespace (Word 2010+) + * @property mc - Markup Compatibility namespace + * @property o - Office namespace + * @property r - Relationships namespace + * @property m - Math namespace + * @property v - VML (Vector Markup Language) namespace + * @property wp14 - WordprocessingDrawing namespace (Word 2010+) + * @property wp - WordprocessingDrawing namespace + * @property w10 - Word 2000 namespace + * @property w - Main WordprocessingML namespace + * @property w14 - WordprocessingML namespace (Word 2010+) + * @property w15 - WordprocessingML namespace (Word 2012+) + * @property wpg - WordprocessingGroup namespace (Word 2010+) + * @property wpi - WordprocessingInk namespace (Word 2010+) + * @property wne - WordprocessingML namespace extensions + * @property wps - WordprocessingShape namespace (Word 2010+) + * @property cp - Core Properties namespace + * @property dc - Dublin Core namespace + * @property dcterms - Dublin Core Terms namespace + * @property dcmitype - Dublin Core DCMI Type namespace + * @property xsi - XML Schema Instance namespace + * @property type - XSI type attribute + */ +export type IFooterAttributesProperties = { readonly wpc?: string; readonly mc?: string; readonly o?: string; @@ -23,7 +52,23 @@ export class FooterAttributes extends XmlAttributeComponent<{ readonly dcmitype?: string; readonly xsi?: string; readonly type?: string; -}> { +}; + +/** + * Component for managing XML namespace attributes on footer elements. + * + * This class handles the serialization of namespace declarations that are required + * for proper XML validation and processing of footer content in WordprocessingML documents. + * + * @example + * ```typescript + * new FooterAttributes({ + * w: "http://schemas.openxmlformats.org/wordprocessingml/2006/main", + * r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships" + * }); + * ``` + */ +export class FooterAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { wpc: "xmlns:wpc", mc: "xmlns:mc", diff --git a/src/file/footer/footer.ts b/src/file/footer/footer.ts index b5438e546e..c35ef7bc64 100644 --- a/src/file/footer/footer.ts +++ b/src/file/footer/footer.ts @@ -16,10 +16,40 @@ import { FooterAttributes } from "./footer-attributes"; /** * Represents a footer in a WordprocessingML document. * - * A footer is the portion of the document that appears at the bottom of each page. - * Footers can contain paragraphs, tables, and other content. + * A footer is the portion of the document that appears at the bottom of each page in a section. + * Footers can contain block-level elements such as paragraphs and tables. Each section can + * have up to three different footers: first page, even pages, and odd pages. * * Reference: http://officeopenxml.com/WPfooters.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a simple footer with page numbers + * const footer = new Footer(1); + * footer.add(new Paragraph({ + * alignment: AlignmentType.CENTER, + * children: [new TextRun("Page "), PageNumber.CURRENT] + * })); + * + * // Create a footer with a table + * const footer = new Footer(2); + * footer.add(new Table({ + * rows: [ + * new TableRow({ + * children: [new TableCell({ children: [new Paragraph("Footer Content")] })] + * }) + * ] + * })); + * ``` */ export class Footer extends InitializableXmlComponent { private readonly refId: number; diff --git a/src/file/footer/index.ts b/src/file/footer/index.ts index 0df22f5218..a437594219 100644 --- a/src/file/footer/index.ts +++ b/src/file/footer/index.ts @@ -1 +1,6 @@ +/** + * Footer module exports. + * + * @module + */ export * from "./footer"; diff --git a/src/file/footnotes-wrapper.ts b/src/file/footnotes-wrapper.ts index b763865964..638980945a 100644 --- a/src/file/footnotes-wrapper.ts +++ b/src/file/footnotes-wrapper.ts @@ -1,7 +1,30 @@ +/** + * Footnotes wrapper module for WordprocessingML documents. + * + * This module provides a wrapper for managing footnotes and their + * associated relationships in a document. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { IViewWrapper } from "./document-wrapper"; import { FootNotes } from "./footnotes/footnotes"; import { Relationships } from "./relationships"; +/** + * Wrapper class for managing footnotes in a document. + * + * Encapsulates the footnotes collection and its relationships, + * implementing the IViewWrapper interface for consistent access. + * + * @example + * ```typescript + * const wrapper = new FootnotesWrapper(); + * const footnotes = wrapper.View; + * const relationships = wrapper.Relationships; + * ``` + */ export class FootnotesWrapper implements IViewWrapper { private readonly footnotess: FootNotes; private readonly relationships: Relationships; diff --git a/src/file/footnotes/footnote/footnote-attributes.ts b/src/file/footnotes/footnote/footnote-attributes.ts index 8f156b79f8..9c533287d3 100644 --- a/src/file/footnotes/footnote/footnote-attributes.ts +++ b/src/file/footnotes/footnote/footnote-attributes.ts @@ -1,7 +1,25 @@ +/** + * Footnote attributes module for WordprocessingML documents. + * + * This module defines attributes for individual footnote elements. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Represents the attributes for a footnote element. + * + * FootnoteAttributes defines the type and unique identifier for each footnote. + * + * @internal + */ export class FootnoteAttributes extends XmlAttributeComponent<{ + /** Type of footnote (separator, continuationSeparator, or normal) */ readonly type?: string; + /** Unique numeric identifier for this footnote */ readonly id: number; }> { protected readonly xmlKeys = { diff --git a/src/file/footnotes/footnote/footnote.ts b/src/file/footnotes/footnote/footnote.ts index b03005d25e..25357a558f 100644 --- a/src/file/footnotes/footnote/footnote.ts +++ b/src/file/footnotes/footnote/footnote.ts @@ -29,6 +29,10 @@ export const FootnoteType = { /** * Options for creating a Footnote. * + * @property id - Unique numeric identifier for this footnote + * @property type - Type of footnote (separator, continuationSeparator, or normal) + * @property children - Array of paragraphs that make up the footnote content + * * @see {@link Footnote} */ export type IFootnoteOptions = { @@ -58,6 +62,21 @@ export type IFootnoteOptions = { * * * ``` + * + * @example + * ```typescript + * // Create a footnote with content + * const footnote = new Footnote({ + * id: 1, + * children: [ + * new Paragraph({ + * children: [ + * new TextRun("This is the footnote content."), + * ], + * }), + * ], + * }); + * ``` */ export class Footnote extends XmlComponent { public constructor(options: IFootnoteOptions) { diff --git a/src/file/footnotes/footnote/index.ts b/src/file/footnotes/footnote/index.ts index 11d8ba33a9..8334d6ada5 100644 --- a/src/file/footnotes/footnote/index.ts +++ b/src/file/footnotes/footnote/index.ts @@ -1 +1,11 @@ +/** + * Footnote element module for WordprocessingML documents. + * + * This module exports footnote-related components including + * the Footnote class and associated run types. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ export * from "./run"; diff --git a/src/file/footnotes/footnote/run/continuation-seperator-run.ts b/src/file/footnotes/footnote/run/continuation-seperator-run.ts index 722a2bf385..3296c623de 100644 --- a/src/file/footnotes/footnote/run/continuation-seperator-run.ts +++ b/src/file/footnotes/footnote/run/continuation-seperator-run.ts @@ -1,7 +1,25 @@ +/** + * Footnote continuation separator run module for WordprocessingML documents. + * + * This module provides the run containing the continuation separator element. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { Run } from "@file/paragraph"; import { ContinuationSeperator } from "./continuation-seperator"; +/** + * Represents a footnote continuation separator run in WordprocessingML. + * + * ContinuationSeperatorRun creates a run containing the continuation + * separator element that defines the line used when footnotes continue + * from a previous page. + * + * @internal + */ export class ContinuationSeperatorRun extends Run { public constructor() { super({}); diff --git a/src/file/footnotes/footnote/run/continuation-seperator.ts b/src/file/footnotes/footnote/run/continuation-seperator.ts index ebcc5994fe..19f503be12 100644 --- a/src/file/footnotes/footnote/run/continuation-seperator.ts +++ b/src/file/footnotes/footnote/run/continuation-seperator.ts @@ -1,5 +1,28 @@ +/** + * Footnote continuation separator module for WordprocessingML documents. + * + * This module provides the continuation separator element that defines + * the line used when footnotes span multiple pages. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a footnote continuation separator in WordprocessingML. + * + * ContinuationSeperator creates the separator line that appears when + * footnotes continue from a previous page to the current page. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @internal + */ export class ContinuationSeperator extends XmlComponent { public constructor() { super("w:continuationSeparator"); diff --git a/src/file/footnotes/footnote/run/footnote-ref.ts b/src/file/footnotes/footnote/run/footnote-ref.ts index 9ec59a0a82..d5e56df47c 100644 --- a/src/file/footnotes/footnote/run/footnote-ref.ts +++ b/src/file/footnotes/footnote/run/footnote-ref.ts @@ -1,5 +1,29 @@ +/** + * Footnote reference marker module for WordprocessingML documents. + * + * This module provides the automatic footnote reference marker that appears + * at the beginning of footnote content. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a footnote reference marker in WordprocessingML. + * + * FootnoteRef creates the automatic reference mark (typically a superscript + * number) that appears at the beginning of the footnote content itself. + * This corresponds to the w:footnoteRef element in OOXML. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @internal + */ export class FootnoteRef extends XmlComponent { public constructor() { super("w:footnoteRef"); diff --git a/src/file/footnotes/footnote/run/index.ts b/src/file/footnotes/footnote/run/index.ts index 548e717bbd..5a624bef7e 100644 --- a/src/file/footnotes/footnote/run/index.ts +++ b/src/file/footnotes/footnote/run/index.ts @@ -1 +1,11 @@ +/** + * Footnote run components module for WordprocessingML documents. + * + * This module exports run-level components used in footnotes, + * including footnote reference runs. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ export * from "./reference-run"; diff --git a/src/file/footnotes/footnote/run/reference-run.ts b/src/file/footnotes/footnote/run/reference-run.ts index 25fe9edd14..65714527ed 100644 --- a/src/file/footnotes/footnote/run/reference-run.ts +++ b/src/file/footnotes/footnote/run/reference-run.ts @@ -1,7 +1,23 @@ +/** + * Footnote reference run module for WordprocessingML documents. + * + * This module provides the footnote reference marker that appears in the + * main document text to indicate a footnote. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { Run } from "@file/paragraph/run"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Represents the attributes for a footnote reference element. + * + * @internal + */ export class FootNoteReferenceRunAttributes extends XmlAttributeComponent<{ + /** Unique identifier linking to the footnote */ readonly id: number; }> { protected readonly xmlKeys = { @@ -9,6 +25,22 @@ export class FootNoteReferenceRunAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents a footnote reference element in WordprocessingML. + * + * FootnoteReference creates the link between the main document text + * and the footnote content by using a unique identifier. + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @internal + */ export class FootnoteReference extends XmlComponent { public constructor(id: number) { super("w:footnoteReference"); @@ -21,7 +53,32 @@ export class FootnoteReference extends XmlComponent { } } +/** + * Represents a footnote reference run in a WordprocessingML document. + * + * FootnoteReferenceRun creates a run containing a footnote reference marker + * (typically a superscript number) that appears in the main document text. + * Clicking this marker navigates to the corresponding footnote content. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @example + * ```typescript + * // Add a footnote reference in a paragraph + * new Paragraph({ + * children: [ + * new TextRun("This text has a footnote"), + * new FootnoteReferenceRun(1), + * ], + * }); + * ``` + */ export class FootnoteReferenceRun extends Run { + /** + * Creates a new footnote reference run. + * + * @param id - Unique identifier linking to the footnote content + */ public constructor(id: number) { super({ style: "FootnoteReference" }); diff --git a/src/file/footnotes/footnote/run/seperator-run.ts b/src/file/footnotes/footnote/run/seperator-run.ts index 9f0a12eae4..c534181325 100644 --- a/src/file/footnotes/footnote/run/seperator-run.ts +++ b/src/file/footnotes/footnote/run/seperator-run.ts @@ -1,7 +1,24 @@ +/** + * Footnote separator run module for WordprocessingML documents. + * + * This module provides the run containing the separator element. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { Run } from "@file/paragraph"; import { Seperator } from "./seperator"; +/** + * Represents a footnote separator run in WordprocessingML. + * + * SeperatorRun creates a run containing the separator element that + * defines the horizontal line between body text and footnotes. + * + * @internal + */ export class SeperatorRun extends Run { public constructor() { super({}); diff --git a/src/file/footnotes/footnote/run/seperator.ts b/src/file/footnotes/footnote/run/seperator.ts index c4a6d8d07c..b3c04e4059 100644 --- a/src/file/footnotes/footnote/run/seperator.ts +++ b/src/file/footnotes/footnote/run/seperator.ts @@ -1,5 +1,28 @@ +/** + * Footnote separator module for WordprocessingML documents. + * + * This module provides the separator element that defines the line + * separating body text from footnotes. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents a footnote separator in WordprocessingML. + * + * Seperator creates the separator line that appears between the main + * document text and the footnote area at the bottom of the page. + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @internal + */ export class Seperator extends XmlComponent { public constructor() { super("w:separator"); diff --git a/src/file/footnotes/footnotes-attributes.ts b/src/file/footnotes/footnotes-attributes.ts index 71d8d705c6..74325c930e 100644 --- a/src/file/footnotes/footnotes-attributes.ts +++ b/src/file/footnotes/footnotes-attributes.ts @@ -1,22 +1,56 @@ +/** + * Footnotes attributes module for WordprocessingML documents. + * + * This module defines XML namespace attributes for the footnotes element. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Represents the XML namespace attributes for the footnotes root element. + * + * FootnotesAttributes defines all necessary XML namespace declarations + * for the footnotes.xml part of a WordprocessingML document. + * + * @internal + */ export class FootnotesAttributes extends XmlAttributeComponent<{ + /** WordprocessingCanvas namespace */ readonly wpc?: string; + /** Markup Compatibility namespace */ readonly mc?: string; + /** Office namespace */ readonly o?: string; + /** Relationships namespace */ readonly r?: string; + /** Math namespace */ readonly m?: string; + /** VML namespace */ readonly v?: string; + /** WordprocessingDrawing 2010 namespace */ readonly wp14?: string; + /** WordprocessingDrawing namespace */ readonly wp?: string; + /** Office Word 2003 namespace */ readonly w10?: string; + /** WordprocessingML main namespace */ readonly w?: string; + /** WordprocessingML 2010 namespace */ readonly w14?: string; + /** WordprocessingML 2012 namespace */ readonly w15?: string; + /** WordprocessingGroup namespace */ readonly wpg?: string; + /** WordprocessingInk namespace */ readonly wpi?: string; + /** WordprocessingML namespace extension */ readonly wne?: string; + /** WordprocessingShape namespace */ readonly wps?: string; + /** Markup compatibility ignorable namespaces */ readonly Ignorable?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/footnotes/footnotes.ts b/src/file/footnotes/footnotes.ts index cf215d5aac..66e3c37d12 100644 --- a/src/file/footnotes/footnotes.ts +++ b/src/file/footnotes/footnotes.ts @@ -1,3 +1,13 @@ +/** + * Footnotes module for WordprocessingML documents. + * + * This module manages the collection of footnotes in a document, including + * separator and continuation separator footnotes that appear by default. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { LineRuleType, Paragraph } from "../paragraph"; @@ -6,6 +16,48 @@ import { ContinuationSeperatorRun } from "./footnote/run/continuation-seperator- import { SeperatorRun } from "./footnote/run/seperator-run"; import { FootnotesAttributes } from "./footnotes-attributes"; +/** + * Represents the footnotes collection in a WordprocessingML document. + * + * FootNotes manages all footnotes in a document and automatically creates + * the required separator and continuation separator footnotes. These special + * footnotes define the line that separates body text from footnotes and the + * line used when footnotes continue across pages. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // FootNotes is typically managed internally by the Document class + * // Users create footnotes through the Document API + * const doc = new Document({ + * sections: [{ + * children: [ + * new Paragraph({ + * children: [ + * new TextRun("Text with footnote"), + * new FootnoteReferenceRun(1), + * ], + * }), + * ], + * footnotes: { + * 1: { + * children: [new Paragraph("Footnote content")], + * }, + * }, + * }], + * }); + * ``` + */ export class FootNotes extends XmlComponent { public constructor() { super("w:footnotes"); @@ -67,6 +119,12 @@ export class FootNotes extends XmlComponent { this.root.push(spacing); } + /** + * Creates and adds a new footnote to the collection. + * + * @param id - Unique numeric identifier for the footnote + * @param paragraph - Array of paragraphs that make up the footnote content + */ public createFootNote(id: number, paragraph: readonly Paragraph[]): void { const footnote = new Footnote({ id: id, diff --git a/src/file/footnotes/index.ts b/src/file/footnotes/index.ts index 1e11cca76a..6b1e1168aa 100644 --- a/src/file/footnotes/index.ts +++ b/src/file/footnotes/index.ts @@ -1,2 +1,13 @@ +/** + * Footnotes and endnotes module for WordprocessingML documents. + * + * This module provides support for creating and managing footnotes + * in Word documents. Footnotes appear at the bottom of the page and + * are referenced from the main document text. + * + * Reference: http://officeopenxml.com/WPfootnotes.php + * + * @module + */ export * from "./footnotes"; export * from "./footnote"; diff --git a/src/file/header-wrapper.ts b/src/file/header-wrapper.ts index 880d9131b4..3583072c50 100644 --- a/src/file/header-wrapper.ts +++ b/src/file/header-wrapper.ts @@ -1,3 +1,14 @@ +/** + * Header wrapper module for WordprocessingML documents. + * + * This module provides a wrapper for document headers, managing header content + * along with their relationships and media. Headers can be configured for + * different pages (first, even, odd, default). + * + * Reference: http://officeopenxml.com/WPheader.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { HeaderFooterReferenceType } from "./document"; @@ -8,11 +19,35 @@ import { Paragraph } from "./paragraph"; import { Relationships } from "./relationships"; import { Table } from "./table"; +/** + * Configuration for a document header. + * + * @property header - The HeaderWrapper instance containing the header content + * @property type - The header type (default, first page, even pages) + */ export type IDocumentHeader = { readonly header: HeaderWrapper; readonly type: (typeof HeaderFooterReferenceType)[keyof typeof HeaderFooterReferenceType]; }; +/** + * Wrapper for document headers. + * + * HeaderWrapper combines a Header view with its Relationships and Media, + * enabling headers to contain paragraphs, tables, images, and hyperlinks. + * Each section can have multiple headers for different page types. + * + * Reference: http://officeopenxml.com/WPheader.php + * + * @example + * ```typescript + * const headerWrapper = new HeaderWrapper(media, 1); + * headerWrapper.add(new Paragraph("Page Header")); + * headerWrapper.add(new Table({ + * rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Cell")] })] })], + * })); + * ``` + */ export class HeaderWrapper implements IViewWrapper { private readonly header: Header; private readonly relationships: Relationships; diff --git a/src/file/header.ts b/src/file/header.ts index b76952d8ea..2955eeda39 100644 --- a/src/file/header.ts +++ b/src/file/header.ts @@ -1,10 +1,42 @@ +/** + * Header and footer module for WordprocessingML documents. + * + * This module provides classes for creating headers and footers + * that can be attached to document sections. + * + * Reference: http://officeopenxml.com/WPSectionHeaderFooters.php + * + * @module + */ import { Paragraph } from "./paragraph"; import { Table } from "./table"; +/** + * Options for creating a header or footer. + * + * @see {@link Header} + * @see {@link Footer} + */ export type IHeaderOptions = { + /** The content elements (paragraphs and tables) for the header/footer */ readonly children: readonly (Paragraph | Table)[]; }; +/** + * Represents a document header. + * + * Headers appear at the top of each page in a section and can contain + * paragraphs, tables, images, and other content. + * + * @example + * ```typescript + * const header = new Header({ + * children: [ + * new Paragraph({ children: [new TextRun("Company Name")] }), + * ], + * }); + * ``` + */ export class Header { public readonly options: IHeaderOptions; @@ -13,6 +45,21 @@ export class Header { } } +/** + * Represents a document footer. + * + * Footers appear at the bottom of each page in a section and can contain + * paragraphs, tables, images, and other content. + * + * @example + * ```typescript + * const footer = new Footer({ + * children: [ + * new Paragraph({ children: [new TextRun("Page "), PageNumber.CURRENT] }), + * ], + * }); + * ``` + */ export class Footer { public readonly options: IHeaderOptions; diff --git a/src/file/header/header-attributes.ts b/src/file/header/header-attributes.ts index cc3cc944d8..70a79e4164 100644 --- a/src/file/header/header-attributes.ts +++ b/src/file/header/header-attributes.ts @@ -1,6 +1,46 @@ import { XmlAttributeComponent } from "@file/xml-components"; -export class HeaderAttributes extends XmlAttributeComponent<{ +/** + * XML namespace attributes for header elements. + * + * This interface defines all XML namespace declarations that can be used in header elements, + * including WordprocessingML, DrawingML, VML, and various Office-specific namespaces. + * + * @property wpc - WordprocessingML Canvas namespace (Word 2010+) + * @property mc - Markup Compatibility namespace + * @property o - Office namespace + * @property r - Relationships namespace + * @property m - Math namespace + * @property v - VML (Vector Markup Language) namespace + * @property wp14 - WordprocessingDrawing namespace (Word 2010+) + * @property wp - WordprocessingDrawing namespace + * @property w10 - Word 2000 namespace + * @property w - Main WordprocessingML namespace + * @property w14 - WordprocessingML namespace (Word 2010+) + * @property w15 - WordprocessingML namespace (Word 2012+) + * @property wpg - WordprocessingGroup namespace (Word 2010+) + * @property wpi - WordprocessingInk namespace (Word 2010+) + * @property wne - WordprocessingML namespace extensions + * @property wps - WordprocessingShape namespace (Word 2010+) + * @property cp - Core Properties namespace + * @property dc - Dublin Core namespace + * @property dcterms - Dublin Core Terms namespace + * @property dcmitype - Dublin Core DCMI Type namespace + * @property xsi - XML Schema Instance namespace + * @property type - XSI type attribute + * @property cx - ChartEx namespace (Office 2014+) + * @property cx1 - ChartEx namespace (September 2015) + * @property cx2 - ChartEx namespace (October 2015) + * @property cx3 - ChartEx namespace (May 2016) + * @property cx4 - ChartEx namespace (May 2016) + * @property cx5 - ChartEx namespace (May 2016) + * @property cx6 - ChartEx namespace (May 2016) + * @property cx7 - ChartEx namespace (May 2016) + * @property cx8 - ChartEx namespace (May 2016) + * @property w16cid - WordprocessingML CID namespace (Word 2016+) + * @property w16se - WordprocessingML SymEx namespace (Word 2015+) + */ +export type IHeaderAttributesProperties = { readonly wpc?: string; readonly mc?: string; readonly o?: string; @@ -34,7 +74,23 @@ export class HeaderAttributes extends XmlAttributeComponent<{ readonly cx8?: string; readonly w16cid: string; readonly w16se: string; -}> { +}; + +/** + * Component for managing XML namespace attributes on header elements. + * + * This class handles the serialization of namespace declarations that are required + * for proper XML validation and processing of header content in WordprocessingML documents. + * + * @example + * ```typescript + * new HeaderAttributes({ + * w: "http://schemas.openxmlformats.org/wordprocessingml/2006/main", + * r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships" + * }); + * ``` + */ +export class HeaderAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { wpc: "xmlns:wpc", mc: "xmlns:mc", diff --git a/src/file/header/header.ts b/src/file/header/header.ts index 078d526be6..8f443b73e8 100644 --- a/src/file/header/header.ts +++ b/src/file/header/header.ts @@ -16,10 +16,37 @@ import { HeaderAttributes } from "./header-attributes"; /** * Represents a header in a WordprocessingML document. * - * A header is the portion of the document that appears at the top of each page. - * Headers can contain paragraphs, tables, and other content. + * A header is the portion of the document that appears at the top of each page in a section. + * Headers can contain block-level elements such as paragraphs and tables. Each section can + * have up to three different headers: first page, even pages, and odd pages. * * Reference: http://officeopenxml.com/WPheaders.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a simple header + * const header = new Header(1); + * header.add(new Paragraph("Company Name")); + * + * // Create a header with a table + * const header = new Header(2); + * header.add(new Table({ + * rows: [ + * new TableRow({ + * children: [new TableCell({ children: [new Paragraph("Header Content")] })] + * }) + * ] + * })); + * ``` */ export class Header extends InitializableXmlComponent { private readonly refId: number; diff --git a/src/file/header/index.ts b/src/file/header/index.ts index 49ac70fe21..14ac85946f 100644 --- a/src/file/header/index.ts +++ b/src/file/header/index.ts @@ -1 +1,6 @@ +/** + * Header module exports. + * + * @module + */ export * from "./header"; diff --git a/src/file/index.ts b/src/file/index.ts index 5f696be52e..1dbb78ad83 100644 --- a/src/file/index.ts +++ b/src/file/index.ts @@ -1,3 +1,15 @@ +/** + * File components module for WordprocessingML documents. + * + * This module exports all the building blocks needed to create DOCX documents, + * including paragraphs, tables, styles, numbering, headers/footers, and more. + * + * The main `File` class (exported as `Document` from the root) coordinates all + * these components to produce a complete OOXML document. + * + * @module + */ + export * from "./paragraph"; export * from "./table"; export * from "./file"; diff --git a/src/file/media/data.ts b/src/file/media/data.ts index 7024c74e4b..6972d4c00b 100644 --- a/src/file/media/data.ts +++ b/src/file/media/data.ts @@ -1,37 +1,73 @@ +/** + * Transformation information for media display. + * + * Contains size and orientation data for rendering an image in the document. + */ export type IMediaDataTransformation = { + /** Display dimensions in pixels */ readonly pixels: { + /** Width in pixels */ readonly x: number; + /** Height in pixels */ readonly y: number; }; + /** Display dimensions in EMUs (English Metric Units) */ readonly emus: { + /** Width in EMUs (1 inch = 914400 EMUs) */ readonly x: number; + /** Height in EMUs (1 inch = 914400 EMUs) */ readonly y: number; }; + /** Optional flip transformations */ readonly flip?: { + /** Whether to flip the image vertically */ readonly vertical?: boolean; + /** Whether to flip the image horizontally */ readonly horizontal?: boolean; }; + /** Optional rotation angle in degrees */ readonly rotation?: number; }; +/** + * Core properties shared by all media data types. + */ type CoreMediaData = { + /** File name for the media in the package */ readonly fileName: string; + /** Transformation settings for display */ readonly transformation: IMediaDataTransformation; + /** Raw image data as Buffer, Uint8Array, or ArrayBuffer */ readonly data: Buffer | Uint8Array | ArrayBuffer; }; +/** + * Regular raster image formats. + */ type RegularMediaData = { + /** Image format type */ readonly type: "jpg" | "png" | "gif" | "bmp"; }; +/** + * SVG image format with fallback support. + */ type SvgMediaData = { + /** SVG image type */ readonly type: "svg"; /** - * Required in case the Word processor does not support SVG. + * Fallback image for Word processors that do not support SVG. + * This ensures the document displays correctly in all viewers. */ readonly fallback: RegularMediaData & CoreMediaData; }; +/** + * Complete media data for an embedded image. + * + * Supports both regular raster formats (jpg, png, gif, bmp) and SVG + * with automatic fallback handling. + */ export type IMediaData = (RegularMediaData | SvgMediaData) & CoreMediaData; // Needed because of: https://github.com/s-panferov/awesome-typescript-loader/issues/432 diff --git a/src/file/media/index.ts b/src/file/media/index.ts index 3575274e26..61722266d4 100644 --- a/src/file/media/index.ts +++ b/src/file/media/index.ts @@ -1,2 +1,7 @@ +/** + * Media module exports. + * + * @module + */ export * from "./media"; export * from "./data"; diff --git a/src/file/media/media.ts b/src/file/media/media.ts index ca40aa343b..94434d794a 100644 --- a/src/file/media/media.ts +++ b/src/file/media/media.ts @@ -11,7 +11,7 @@ import { IMediaData } from "./data"; /** * Transformation options for media display. * - * Specifies how an image should be transformed when displayed. + * Specifies how an image should be transformed when displayed in the document. */ export type IMediaTransformation = { /** Display width in pixels */ @@ -20,10 +20,12 @@ export type IMediaTransformation = { readonly height: number; /** Optional flip transformations */ readonly flip?: { + /** Whether to flip the image vertically */ readonly vertical?: boolean; + /** Whether to flip the image horizontally */ readonly horizontal?: boolean; }; - /** Optional rotation in degrees */ + /** Optional rotation angle in degrees */ readonly rotation?: number; }; @@ -31,7 +33,23 @@ export type IMediaTransformation = { * Manages embedded media (images) in a document. * * Media stores all images referenced in the document and provides - * access to their data for packaging into the DOCX file. + * access to their data for packaging into the DOCX file. Each image + * is stored with a unique key for retrieval. + * + * @example + * ```typescript + * const media = new Media(); + * media.addImage("image1", { + * type: "png", + * fileName: "image1.png", + * transformation: { + * pixels: { x: 200, y: 100 }, + * emus: { x: 1828800, y: 914400 } + * }, + * data: imageBuffer + * }); + * const allImages = media.Array; + * ``` */ export class Media { // eslint-disable-next-line functional/prefer-readonly-type @@ -41,10 +59,21 @@ export class Media { this.map = new Map(); } + /** + * Adds an image to the media collection. + * + * @param key - Unique identifier for this image + * @param mediaData - Complete image data including file name, transformation, and raw data + */ public addImage(key: string, mediaData: IMediaData): void { this.map.set(key, mediaData); } + /** + * Gets all images as an array. + * + * @returns Read-only array of all media data in the collection + */ public get Array(): readonly IMediaData[] { return Array.from(this.map.values()); } diff --git a/src/file/numbering/abstract-numbering.ts b/src/file/numbering/abstract-numbering.ts index 24bd1c9842..c87f53358b 100644 --- a/src/file/numbering/abstract-numbering.ts +++ b/src/file/numbering/abstract-numbering.ts @@ -1,26 +1,29 @@ +/** + * Abstract numbering definitions module for WordprocessingML documents. + * + * Abstract numbering definitions contain the formatting and style information + * that can be shared across multiple numbering instances. + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; import { ILevelsOptions, Level } from "./level"; import { MultiLevelType } from "./multi-level-type"; -// -// -// -// -// -// -// -// -// -// -// -// - -// -// https://docs.microsoft.com/en-us/openspecs/office_standards/ms-docx/cbddeff8-01aa-4486-a48e-6a83dede4f13 +/** + * Attributes for abstract numbering definitions. + * + * @property abstractNumId - Unique identifier for the abstract numbering definition + * @property restartNumberingAfterBreak - Whether to restart numbering after section breaks + */ class AbstractNumberingAttributes extends XmlAttributeComponent<{ + /** Unique identifier for the abstract numbering definition. */ readonly abstractNumId: number; + /** Whether to restart numbering after section breaks (0 or 1). */ readonly restartNumberingAfterBreak: number; }> { protected readonly xmlKeys = { @@ -29,9 +32,60 @@ class AbstractNumberingAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents an abstract numbering definition in a WordprocessingML document. + * + * Abstract numbering definitions define the formatting and style of numbered or + * bulleted lists that can be referenced by concrete numbering instances. + * Each abstract definition can contain up to 9 levels. + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create an abstract numbering definition with multiple levels + * const abstractNumbering = new AbstractNumbering(1, [ + * { + * level: 0, + * format: LevelFormat.DECIMAL, + * text: "%1.", + * alignment: AlignmentType.LEFT, + * }, + * { + * level: 1, + * format: LevelFormat.LOWER_LETTER, + * text: "%2)", + * alignment: AlignmentType.LEFT, + * }, + * ]); + * ``` + */ export class AbstractNumbering extends XmlComponent { + /** The unique identifier for this abstract numbering definition. */ public readonly id: number; + /** + * Creates a new abstract numbering definition. + * + * @param id - Unique identifier for this abstract numbering definition + * @param levelOptions - Array of level definitions (up to 9 levels) + */ public constructor(id: number, levelOptions: readonly ILevelsOptions[]) { super("w:abstractNum"); this.root.push( diff --git a/src/file/numbering/index.ts b/src/file/numbering/index.ts index 9356d6ffa8..2737efbf38 100644 --- a/src/file/numbering/index.ts +++ b/src/file/numbering/index.ts @@ -1,3 +1,8 @@ +/** + * Numbering module exports. + * + * @module + */ export * from "./numbering"; export * from "./abstract-numbering"; export * from "./level"; diff --git a/src/file/numbering/level.ts b/src/file/numbering/level.ts index e9744e8937..48f252f0b7 100644 --- a/src/file/numbering/level.ts +++ b/src/file/numbering/level.ts @@ -1,5 +1,13 @@ -// http://officeopenxml.com/WPnumbering-numFmt.php -// http://www.datypic.com/sc/ooxml/a-w_val-57.html +/** + * Numbering level definitions module for WordprocessingML documents. + * + * This module defines the formatting and behavior of individual levels within + * a numbered or bulleted list hierarchy. + * + * Reference: http://officeopenxml.com/WPnumbering-numFmt.php + * + * @module + */ import { Attributes, NumberValueElement, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; @@ -7,146 +15,165 @@ import { AlignmentType } from "../paragraph/formatting"; import { ILevelParagraphStylePropertiesOptions, ParagraphProperties } from "../paragraph/properties"; import { IRunStylePropertiesOptions, RunProperties } from "../paragraph/run/properties"; -// TODO: Breaking change - consolidate with number-format -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// - +/** + * Number format types for list levels. + * + * Defines the various numbering formats available for list levels, including + * decimal, roman numerals, letters, and various international formats. + * + * Reference: http://officeopenxml.com/WPnumbering-numFmt.php + * + * @example + * ```typescript + * // Use decimal numbering (1, 2, 3...) + * format: LevelFormat.DECIMAL + * + * // Use lowercase roman numerals (i, ii, iii...) + * format: LevelFormat.LOWER_ROMAN + * + * // Use bullet points + * format: LevelFormat.BULLET + * ``` + */ /* eslint-disable @typescript-eslint/naming-convention */ export const LevelFormat = { + /** Decimal numbering (1, 2, 3...). */ DECIMAL: "decimal", + /** Uppercase roman numerals (I, II, III...). */ UPPER_ROMAN: "upperRoman", + /** Lowercase roman numerals (i, ii, iii...). */ LOWER_ROMAN: "lowerRoman", + /** Uppercase letters (A, B, C...). */ UPPER_LETTER: "upperLetter", + /** Lowercase letters (a, b, c...). */ LOWER_LETTER: "lowerLetter", + /** Ordinal numbers (1st, 2nd, 3rd...). */ ORDINAL: "ordinal", + /** Cardinal text (one, two, three...). */ CARDINAL_TEXT: "cardinalText", + /** Ordinal text (first, second, third...). */ ORDINAL_TEXT: "ordinalText", + /** Hexadecimal numbering. */ HEX: "hex", + /** Chicago Manual of Style numbering. */ CHICAGO: "chicago", + /** Ideograph digital numbering. */ IDEOGRAPH__DIGITAL: "ideographDigital", + /** Japanese counting system. */ JAPANESE_COUNTING: "japaneseCounting", + /** Japanese aiueo ordering. */ AIUEO: "aiueo", + /** Japanese iroha ordering. */ IROHA: "iroha", + /** Full-width decimal numbering. */ DECIMAL_FULL_WIDTH: "decimalFullWidth", + /** Half-width decimal numbering. */ DECIMAL_HALF_WIDTH: "decimalHalfWidth", + /** Japanese legal numbering. */ JAPANESE_LEGAL: "japaneseLegal", + /** Japanese digital ten thousand numbering. */ JAPANESE_DIGITAL_TEN_THOUSAND: "japaneseDigitalTenThousand", + /** Decimal numbers enclosed in circles. */ DECIMAL_ENCLOSED_CIRCLE: "decimalEnclosedCircle", + /** Full-width decimal numbering variant 2. */ DECIMAL_FULL_WIDTH2: "decimalFullWidth2", + /** Full-width aiueo ordering. */ AIUEO_FULL_WIDTH: "aiueoFullWidth", + /** Full-width iroha ordering. */ IROHA_FULL_WIDTH: "irohaFullWidth", + /** Decimal with leading zeros. */ DECIMAL_ZERO: "decimalZero", + /** Bullet points. */ BULLET: "bullet", + /** Korean ganada ordering. */ GANADA: "ganada", + /** Korean chosung ordering. */ CHOSUNG: "chosung", + /** Decimal enclosed with fullstop. */ DECIMAL_ENCLOSED_FULLSTOP: "decimalEnclosedFullstop", + /** Decimal enclosed in parentheses. */ DECIMAL_ENCLOSED_PARENTHESES: "decimalEnclosedParen", + /** Decimal enclosed in circles (Chinese). */ DECIMAL_ENCLOSED_CIRCLE_CHINESE: "decimalEnclosedCircleChinese", + /** Ideograph enclosed in circles. */ IDEOGRAPH_ENCLOSED_CIRCLE: "ideographEnclosedCircle", + /** Traditional ideograph numbering. */ IDEOGRAPH_TRADITIONAL: "ideographTraditional", + /** Ideograph zodiac numbering. */ IDEOGRAPH_ZODIAC: "ideographZodiac", + /** Traditional ideograph zodiac numbering. */ IDEOGRAPH_ZODIAC_TRADITIONAL: "ideographZodiacTraditional", + /** Taiwanese counting system. */ TAIWANESE_COUNTING: "taiwaneseCounting", + /** Traditional ideograph legal numbering. */ IDEOGRAPH_LEGAL_TRADITIONAL: "ideographLegalTraditional", + /** Taiwanese counting thousand system. */ TAIWANESE_COUNTING_THOUSAND: "taiwaneseCountingThousand", + /** Taiwanese digital numbering. */ TAIWANESE_DIGITAL: "taiwaneseDigital", + /** Chinese counting system. */ CHINESE_COUNTING: "chineseCounting", + /** Simplified Chinese legal numbering. */ CHINESE_LEGAL_SIMPLIFIED: "chineseLegalSimplified", + /** Chinese counting thousand system. */ CHINESE_COUNTING_THOUSAND: "chineseCountingThousand", + /** Korean digital numbering. */ KOREAN_DIGITAL: "koreanDigital", + /** Korean counting system. */ KOREAN_COUNTING: "koreanCounting", + /** Korean legal numbering. */ KOREAN_LEGAL: "koreanLegal", + /** Korean digital numbering variant 2. */ KOREAN_DIGITAL2: "koreanDigital2", + /** Vietnamese counting system. */ VIETNAMESE_COUNTING: "vietnameseCounting", + /** Russian lowercase numbering. */ RUSSIAN_LOWER: "russianLower", + /** Russian uppercase numbering. */ RUSSIAN_UPPER: "russianUpper", + /** No numbering. */ NONE: "none", + /** Number enclosed in dashes. */ NUMBER_IN_DASH: "numberInDash", + /** Hebrew numbering variant 1. */ HEBREW1: "hebrew1", + /** Hebrew numbering variant 2. */ HEBREW2: "hebrew2", + /** Arabic alpha numbering. */ ARABIC_ALPHA: "arabicAlpha", + /** Arabic abjad numbering. */ ARABIC_ABJAD: "arabicAbjad", + /** Hindi vowels. */ HINDI_VOWELS: "hindiVowels", + /** Hindi consonants. */ HINDI_CONSONANTS: "hindiConsonants", + /** Hindi numbers. */ HINDI_NUMBERS: "hindiNumbers", + /** Hindi counting system. */ HINDI_COUNTING: "hindiCounting", + /** Thai letters. */ THAI_LETTERS: "thaiLetters", + /** Thai numbers. */ THAI_NUMBERS: "thaiNumbers", + /** Thai counting system. */ THAI_COUNTING: "thaiCounting", + /** Thai Baht text. */ BAHT_TEXT: "bahtText", + /** Dollar text. */ DOLLAR_TEXT: "dollarText", + /** Custom numbering format. */ CUSTOM: "custom", } as const; /* eslint-enable */ +/** + * Attributes for numbering levels. + */ class LevelAttributes extends XmlAttributeComponent<{ + /** The level index (0-8). */ readonly ilvl?: number; + /** Whether this level is tentative. */ readonly tentative?: number; }> { protected readonly xmlKeys = { @@ -155,10 +182,11 @@ class LevelAttributes extends XmlAttributeComponent<{ }; } -// -// -// -// +/** + * Number format specification for a level. + * + * Specifies the numbering format to use (decimal, roman, letter, etc.). + */ class NumberFormat extends XmlComponent { public constructor(value: string) { super("w:numFmt"); @@ -170,10 +198,12 @@ class NumberFormat extends XmlComponent { } } -// -// -// -// +/** + * Level text template for displaying the numbering. + * + * The text can include placeholders like %1, %2, etc. to reference + * numbering from different levels. + */ class LevelText extends XmlComponent { public constructor(value: string) { super("w:lvlText"); @@ -185,6 +215,9 @@ class LevelText extends XmlComponent { } } +/** + * Alignment specification for level numbering. + */ class LevelJc extends XmlComponent { public constructor(value: (typeof AlignmentType)[keyof typeof AlignmentType]) { super("w:lvlJc"); @@ -196,36 +229,73 @@ class LevelJc extends XmlComponent { } } +/** + * Suffix types for list levels. + * + * Defines what follows the numbering text (tab, space, or nothing). + * + * @example + * ```typescript + * // Add a tab after the numbering + * suffix: LevelSuffix.TAB + * + * // Add a space after the numbering + * suffix: LevelSuffix.SPACE + * + * // No separator after the numbering + * suffix: LevelSuffix.NOTHING + * ``` + */ export const LevelSuffix = { + /** No separator after the numbering. */ NOTHING: "nothing", + /** Space character after the numbering. */ SPACE: "space", + /** Tab character after the numbering. */ TAB: "tab", } as const; +/** + * Options for configuring a numbering level. + * + * @property level - Level index (0-8) + * @property format - Number format type (decimal, roman, letter, etc.) + * @property text - Level text template with placeholders like %1, %2 + * @property alignment - Text alignment for the numbering + * @property start - Starting number for this level + * @property suffix - Character(s) following the numbering (tab, space, nothing) + * @property isLegalNumberingStyle - Use legal numbering style + * @property style - Run and paragraph style properties + */ export type ILevelsOptions = { + /** Level index (0-8). */ readonly level: number; + /** Number format type (decimal, roman, letter, bullet, etc.). */ readonly format?: (typeof LevelFormat)[keyof typeof LevelFormat]; + /** Level text template with placeholders like %1, %2. */ readonly text?: string; + /** Text alignment for the numbering. */ readonly alignment?: (typeof AlignmentType)[keyof typeof AlignmentType]; + /** Starting number for this level. */ readonly start?: number; + /** Character(s) following the numbering. */ readonly suffix?: (typeof LevelSuffix)[keyof typeof LevelSuffix]; + /** Use legal numbering style (e.g., 1.1.1). */ readonly isLegalNumberingStyle?: boolean; + /** Run and paragraph style properties. */ readonly style?: { + /** Run style properties for the numbering text. */ readonly run?: IRunStylePropertiesOptions; + /** Paragraph style properties for the level. */ readonly paragraph?: ILevelParagraphStylePropertiesOptions; }; }; -// -// -// -// -// -// -// -// -// -// +/** + * Suffix specification for a level. + * + * Defines what character(s) follow the numbering text. + */ class Suffix extends XmlComponent { public constructor(value: (typeof LevelSuffix)[keyof typeof LevelSuffix]) { super("w:suff"); @@ -237,37 +307,61 @@ class Suffix extends XmlComponent { } } -// http://officeopenxml.com/WPnumbering-isLgl.php -// https://docs.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.islegalnumberingstyle?view=openxml-2.8.1 +/** + * Legal numbering style flag. + * + * When enabled, creates multi-level legal numbering like 1.1.1. + * + * Reference: http://officeopenxml.com/WPnumbering-isLgl.php + */ class IsLegalNumberingStyle extends XmlComponent { public constructor() { super("w:isLgl"); } } -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// +/** + * Base class for numbering level definitions. + * + * Defines the formatting and behavior of a single level in a multi-level + * numbering scheme. Each level can have its own numbering format, text template, + * alignment, and styling. + * + * Reference: http://officeopenxml.com/WPnumbering-numFmt.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + */ export class LevelBase extends XmlComponent { private readonly paragraphProperties: ParagraphProperties; private readonly runProperties: RunProperties; + /** + * Creates a new numbering level. + * + * @param options - Level configuration options + * @throws Error if level is greater than 9 (Word limitation) + */ public constructor({ level, format, @@ -321,9 +415,47 @@ export class LevelBase extends XmlComponent { } } +/** + * Represents a numbering level within an abstract numbering definition. + * + * This is the standard level definition used in abstract numbering definitions. + * Each abstract numbering definition can contain up to 9 levels (0-8). + * + * Reference: http://officeopenxml.com/WPnumbering-numFmt.php + * + * @example + * ```typescript + * // Create a decimal numbered level + * const level = new Level({ + * level: 0, + * format: LevelFormat.DECIMAL, + * text: "%1.", + * alignment: AlignmentType.LEFT, + * start: 1, + * }); + * + * // Create a bullet level with custom styling + * const bulletLevel = new Level({ + * level: 0, + * format: LevelFormat.BULLET, + * text: "\u2022", + * alignment: AlignmentType.LEFT, + * style: { + * paragraph: { + * indent: { left: 720, hanging: 360 }, + * }, + * }, + * }); + * ``` + */ export class Level extends LevelBase { - // This is the level that sits under abstractNum. We make a - // handful of properties required + // This is the level that sits under abstractNum } +/** + * Represents a numbering level used in level overrides. + * + * This level type is used when overriding specific levels within a + * concrete numbering instance. + */ export class LevelForOverride extends LevelBase {} diff --git a/src/file/numbering/multi-level-type.ts b/src/file/numbering/multi-level-type.ts index 5055c8f6c3..d09f4a698a 100644 --- a/src/file/numbering/multi-level-type.ts +++ b/src/file/numbering/multi-level-type.ts @@ -1,20 +1,52 @@ +/** + * Multi-level type definitions for WordprocessingML documents. + * + * Defines the type of numbering structure (single-level, multi-level, or hybrid). + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; -// -// ... -// - -// -// -// -// -// -// -// -// -// -// +/** + * Represents the multi-level type of a numbering definition. + * + * The multi-level type specifies whether the numbering definition uses a single + * level, multiple levels, or a hybrid approach. + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a hybrid multi-level numbering + * const multiLevel = new MultiLevelType("hybridMultilevel"); + * + * // Create a single-level numbering + * const singleLevel = new MultiLevelType("singleLevel"); + * ``` + */ export class MultiLevelType extends XmlComponent { + /** + * Creates a new multi-level type specification. + * + * @param value - The multi-level type: "singleLevel", "multilevel", or "hybridMultilevel" + */ public constructor(value: string) { super("w:multiLevelType"); this.root.push( diff --git a/src/file/numbering/num.ts b/src/file/numbering/num.ts index 41d16d60a5..89eb9589a1 100644 --- a/src/file/numbering/num.ts +++ b/src/file/numbering/num.ts @@ -1,6 +1,20 @@ +/** + * Concrete numbering instances module for WordprocessingML documents. + * + * Concrete numbering instances reference abstract numbering definitions and + * can override specific level settings. Each paragraph references a concrete + * numbering instance to apply list formatting. + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * @module + */ import { Attributes, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; +/** + * Reference to an abstract numbering definition. + */ class AbstractNumId extends XmlComponent { public constructor(value: number) { super("w:abstractNumId"); @@ -12,41 +26,101 @@ class AbstractNumId extends XmlComponent { } } +/** + * Attributes for concrete numbering instances. + */ class NumAttributes extends XmlAttributeComponent<{ + /** The unique identifier for this numbering instance. */ readonly numId: number; }> { protected readonly xmlKeys = { numId: "w:numId" }; } +/** + * Options for overriding a specific level in a numbering instance. + * + * @property num - The level number to override (0-8) + * @property start - The starting number for this level + */ type IOverrideLevel = { + /** The level number to override (0-8). */ readonly num: number; + /** The starting number for this level. */ readonly start?: number; }; +/** + * Options for creating a concrete numbering instance. + * + * @property numId - Unique identifier for this numbering instance + * @property abstractNumId - ID of the abstract numbering definition to reference + * @property reference - Reference name for this numbering instance + * @property instance - Instance number for tracking multiple uses + * @property overrideLevels - Array of level overrides to customize specific levels + */ export type IConcreteNumberingOptions = { + /** Unique identifier for this numbering instance. */ readonly numId: number; + /** ID of the abstract numbering definition to reference. */ readonly abstractNumId: number; + /** Reference name for this numbering instance. */ readonly reference: string; + /** Instance number for tracking multiple uses. */ readonly instance: number; + /** Array of level overrides to customize specific levels. */ readonly overrideLevels?: readonly IOverrideLevel[]; }; -// -// ... -// - -// -// -// -// -// -// -// +/** + * Represents a concrete numbering instance in a WordprocessingML document. + * + * A concrete numbering instance references an abstract numbering definition and + * can override specific levels. Paragraphs reference concrete numbering instances + * to apply list formatting. + * + * Reference: http://officeopenxml.com/WPnumbering.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a concrete numbering instance + * const concreteNumbering = new ConcreteNumbering({ + * numId: 1, + * abstractNumId: 0, + * reference: "my-numbering", + * instance: 0, + * overrideLevels: [ + * { + * num: 0, + * start: 5, // Start numbering at 5 instead of 1 + * }, + * ], + * }); + * ``` + */ export class ConcreteNumbering extends XmlComponent { + /** The unique identifier for this numbering instance. */ public readonly numId: number; + /** The reference name for this numbering instance. */ public readonly reference: string; + /** The instance number for tracking multiple uses. */ public readonly instance: number; + /** + * Creates a new concrete numbering instance. + * + * @param options - Configuration options for the numbering instance + */ public constructor(options: IConcreteNumberingOptions) { super("w:num"); @@ -70,11 +144,40 @@ export class ConcreteNumbering extends XmlComponent { } } -class LevelOverrideAttributes extends XmlAttributeComponent<{ readonly ilvl: number }> { +/** + * Attributes for level overrides. + */ +class LevelOverrideAttributes extends XmlAttributeComponent<{ + /** The level number being overridden. */ + readonly ilvl: number; +}> { protected readonly xmlKeys = { ilvl: "w:ilvl" }; } +/** + * Represents a level override in a concrete numbering instance. + * + * Level overrides allow customization of specific levels within a numbering + * instance, such as changing the starting number. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export class LevelOverride extends XmlComponent { + /** + * Creates a new level override. + * + * @param levelNum - The level number to override (0-8) + * @param start - Optional starting number for the level + */ public constructor(levelNum: number, start?: number) { super("w:lvlOverride"); this.root.push(new LevelOverrideAttributes({ ilvl: levelNum })); @@ -84,11 +187,27 @@ export class LevelOverride extends XmlComponent { } } -class StartOverrideAttributes extends XmlAttributeComponent<{ readonly val: number }> { +/** + * Attributes for start override values. + */ +class StartOverrideAttributes extends XmlAttributeComponent<{ + /** The starting number value. */ + readonly val: number; +}> { protected readonly xmlKeys = { val: "w:val" }; } +/** + * Represents a start override for a numbering level. + * + * This element overrides the starting number for a specific level. + */ class StartOverride extends XmlComponent { + /** + * Creates a new start override. + * + * @param start - The starting number + */ public constructor(start: number) { super("w:startOverride"); this.root.push(new StartOverrideAttributes({ val: start })); diff --git a/src/file/numbering/numbering.ts b/src/file/numbering/numbering.ts index e677fc023d..91185ee8d5 100644 --- a/src/file/numbering/numbering.ts +++ b/src/file/numbering/numbering.ts @@ -21,11 +21,16 @@ import { DocumentAttributes } from "../document/document-attributes"; /** * Options for configuring numbering definitions. * + * @property config - Array of numbering configurations + * * @see {@link Numbering} */ export type INumberingOptions = { + /** Array of numbering configurations, each with levels and a reference name. */ readonly config: readonly { + /** Array of level definitions for this numbering configuration. */ readonly levels: readonly ILevelsOptions[]; + /** Unique reference name for this numbering configuration. */ readonly reference: string; }[]; }; @@ -35,6 +40,8 @@ export type INumberingOptions = { * * The numbering element contains abstract numbering definitions and their * concrete instances, which are referenced by paragraphs to create lists. + * Each numbering configuration includes a default bullet list and any + * custom numbering schemes defined by the user. * * Reference: http://officeopenxml.com/WPnumbering.php * @@ -51,6 +58,43 @@ export type INumberingOptions = { * * * ``` + * + * @example + * ```typescript + * // Create numbering with custom decimal list + * const numbering = new Numbering({ + * config: [ + * { + * reference: "my-decimal-list", + * levels: [ + * { + * level: 0, + * format: LevelFormat.DECIMAL, + * text: "%1.", + * alignment: AlignmentType.LEFT, + * start: 1, + * style: { + * paragraph: { + * indent: { left: 720, hanging: 360 }, + * }, + * }, + * }, + * { + * level: 1, + * format: LevelFormat.LOWER_LETTER, + * text: "%2)", + * alignment: AlignmentType.LEFT, + * style: { + * paragraph: { + * indent: { left: 1440, hanging: 360 }, + * }, + * }, + * }, + * ], + * }, + * ], + * }); + * ``` */ export class Numbering extends XmlComponent { private readonly abstractNumberingMap = new Map(); @@ -60,6 +104,14 @@ export class Numbering extends XmlComponent { private readonly abstractNumUniqueNumericId = abstractNumUniqueNumericIdGen(); private readonly concreteNumUniqueNumericId = concreteNumUniqueNumericIdGen(); + /** + * Creates a new numbering definition collection. + * + * Initializes the numbering with a default bullet list configuration and + * any custom numbering configurations provided in the options. + * + * @param options - Configuration options for numbering definitions + */ public constructor(options: INumberingOptions) { super("w:numbering"); this.root.push( @@ -195,6 +247,14 @@ export class Numbering extends XmlComponent { } } + /** + * Prepares the numbering definitions for XML serialization. + * + * Adds all abstract and concrete numbering definitions to the XML tree. + * + * @param context - The XML context + * @returns The prepared XML object + */ public prepForXml(context: IContext): IXmlableObject | undefined { for (const numbering of this.abstractNumberingMap.values()) { this.root.push(numbering); @@ -206,6 +266,16 @@ export class Numbering extends XmlComponent { return super.prepForXml(context); } + /** + * Creates a concrete numbering instance from an abstract numbering definition. + * + * This method creates a new concrete numbering instance that references an + * abstract numbering definition. It's used internally when paragraphs reference + * numbering configurations. + * + * @param reference - The reference name of the abstract numbering definition + * @param instance - The instance number for this concrete numbering + */ public createConcreteNumberingInstance(reference: string, instance: number): void { const abstractNumbering = this.abstractNumberingMap.get(reference); @@ -243,9 +313,20 @@ export class Numbering extends XmlComponent { this.concreteNumberingMap.set(fullReference, new ConcreteNumbering(concreteNumberingSettings)); } + /** + * Gets all concrete numbering instances. + * + * @returns An array of all concrete numbering instances + */ public get ConcreteNumbering(): readonly ConcreteNumbering[] { return Array.from(this.concreteNumberingMap.values()); } + + /** + * Gets all reference configurations. + * + * @returns An array of all numbering reference configurations + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public get ReferenceConfig(): readonly Record[] { return Array.from(this.referenceConfigMap.values()); diff --git a/src/file/paragraph/formatting/alignment.ts b/src/file/paragraph/formatting/alignment.ts index 9973157672..8056ccf6f6 100644 --- a/src/file/paragraph/formatting/alignment.ts +++ b/src/file/paragraph/formatting/alignment.ts @@ -84,6 +84,26 @@ export class AlignmentAttributes extends XmlAttributeComponent<{ * The jc element specifies the horizontal alignment of all text in the paragraph. * * Reference: http://officeopenxml.com/WPalignment.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * alignment: AlignmentType.CENTER, + * children: [new TextRun("Centered text")], + * }); + * + * new Paragraph({ + * alignment: AlignmentType.JUSTIFIED, + * children: [new TextRun("Justified text spreads evenly across the line")], + * }); + * ``` */ export class Alignment extends XmlComponent { public constructor(type: (typeof AlignmentType)[keyof typeof AlignmentType]) { diff --git a/src/file/paragraph/formatting/border.ts b/src/file/paragraph/formatting/border.ts index 0359b17f96..33b32a3c10 100644 --- a/src/file/paragraph/formatting/border.ts +++ b/src/file/paragraph/formatting/border.ts @@ -14,12 +14,23 @@ import { IgnoreIfEmptyXmlComponent, XmlComponent } from "@file/xml-components"; * Options for configuring paragraph borders. * * Borders can be applied to top, bottom, left, right, and between paragraphs. + * + * @property top - Border for the top edge of the paragraph + * @property bottom - Border for the bottom edge of the paragraph + * @property left - Border for the left edge of the paragraph + * @property right - Border for the right edge of the paragraph + * @property between - Border between consecutive paragraphs with the same border settings */ export type IBordersOptions = { + /** Border for the top edge of the paragraph */ readonly top?: IBorderOptions; + /** Border for the bottom edge of the paragraph */ readonly bottom?: IBorderOptions; + /** Border for the left edge of the paragraph */ readonly left?: IBorderOptions; + /** Border for the right edge of the paragraph */ readonly right?: IBorderOptions; + /** Border between consecutive paragraphs with the same border settings */ readonly between?: IBorderOptions; }; @@ -29,6 +40,31 @@ export type IBordersOptions = { * The pBdr element specifies borders that surround the paragraph. * * Reference: http://officeopenxml.com/WPborders.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * border: { + * top: { style: BorderStyle.SINGLE, size: 6, color: "FF0000" }, + * bottom: { style: BorderStyle.SINGLE, size: 6, color: "FF0000" }, + * }, + * children: [new TextRun("Paragraph with top and bottom borders")], + * }); + * ``` */ export class Border extends IgnoreIfEmptyXmlComponent { public constructor(options: IBordersOptions) { @@ -60,6 +96,25 @@ export class Border extends IgnoreIfEmptyXmlComponent { * Represents a thematic break (horizontal rule) in a WordprocessingML document. * * Creates a horizontal line across the paragraph using a bottom border. + * + * Reference: http://officeopenxml.com/WPborders.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * thematicBreak: true, + * children: [new TextRun("Paragraph with horizontal rule below")], + * }); + * ``` */ export class ThematicBreak extends XmlComponent { public constructor() { diff --git a/src/file/paragraph/formatting/break.ts b/src/file/paragraph/formatting/break.ts index 67f54e9261..5f7ce99a28 100644 --- a/src/file/paragraph/formatting/break.ts +++ b/src/file/paragraph/formatting/break.ts @@ -45,6 +45,14 @@ class Break extends XmlComponent { * * Reference: http://officeopenxml.com/WPtextSpecialContent-break.php * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * * @example * ```typescript * new Paragraph({ @@ -66,6 +74,14 @@ export class PageBreak extends Run { * * Reference: http://officeopenxml.com/WPtextSpecialContent-break.php * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * * @example * ```typescript * new Paragraph({ @@ -81,7 +97,26 @@ export class ColumnBreak extends Run { } /** - * Add page break before the paragraph if there is no one added before. + * Represents a page break before setting for paragraph properties. + * + * When applied to a paragraph, ensures the paragraph begins on a new page. + * + * Reference: http://officeopenxml.com/WPparagraphProperties.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * pageBreakBefore: true, + * children: [new TextRun("This text starts on a new page")], + * }); + * ``` */ export class PageBreakBefore extends XmlComponent { public constructor() { diff --git a/src/file/paragraph/formatting/index.ts b/src/file/paragraph/formatting/index.ts index b3f209e072..854b21d74b 100644 --- a/src/file/paragraph/formatting/index.ts +++ b/src/file/paragraph/formatting/index.ts @@ -1,3 +1,8 @@ +/** + * Paragraph formatting module exports. + * + * @module + */ export * from "./alignment"; export * from "./border"; export * from "./indent"; diff --git a/src/file/paragraph/formatting/spacing.ts b/src/file/paragraph/formatting/spacing.ts index f35a53c01a..eecebfbdc6 100644 --- a/src/file/paragraph/formatting/spacing.ts +++ b/src/file/paragraph/formatting/spacing.ts @@ -30,13 +30,26 @@ export const LineRuleType = { * Properties for configuring paragraph spacing. * * All values are in twips (twentieths of a point) unless otherwise specified. + * + * @property after - Spacing after the paragraph in twips + * @property before - Spacing before the paragraph in twips + * @property line - Line spacing value in twips (interpretation depends on lineRule) + * @property lineRule - How to interpret the line spacing value + * @property beforeAutoSpacing - Use automatic spacing before the paragraph + * @property afterAutoSpacing - Use automatic spacing after the paragraph */ export type ISpacingProperties = { + /** Spacing after the paragraph in twips */ readonly after?: number; + /** Spacing before the paragraph in twips */ readonly before?: number; + /** Line spacing value in twips (interpretation depends on lineRule) */ readonly line?: number; + /** How to interpret the line spacing value */ readonly lineRule?: (typeof LineRuleType)[keyof typeof LineRuleType]; + /** Use automatic spacing before the paragraph */ readonly beforeAutoSpacing?: boolean; + /** Use automatic spacing after the paragraph */ readonly afterAutoSpacing?: boolean; }; @@ -57,6 +70,33 @@ class SpacingAttributes extends XmlAttributeComponent { * The spacing element specifies the spacing between lines and paragraphs. * * Reference: http://officeopenxml.com/WPspacing.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * spacing: { + * before: 200, + * after: 200, + * line: 360, + * lineRule: LineRuleType.AT_LEAST, + * }, + * children: [new TextRun("Paragraph with custom spacing")], + * }); + * ``` */ export class Spacing extends XmlComponent { public constructor(options: ISpacingProperties) { diff --git a/src/file/paragraph/formatting/style.ts b/src/file/paragraph/formatting/style.ts index 7e7c976b99..1d8bc76388 100644 --- a/src/file/paragraph/formatting/style.ts +++ b/src/file/paragraph/formatting/style.ts @@ -33,6 +33,30 @@ export const HeadingLevel = { * Represents a paragraph style reference in a WordprocessingML document. * * The pStyle element specifies the paragraph style to apply to the paragraph. + * + * Reference: http://officeopenxml.com/WPstyle.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Using a built-in heading style + * new Paragraph({ + * style: HeadingLevel.HEADING_1, + * children: [new TextRun("Chapter 1")], + * }); + * + * // Using a custom style + * new Paragraph({ + * style: "MyCustomStyle", + * children: [new TextRun("Styled text")], + * }); + * ``` */ export class Style extends XmlComponent { public constructor(styleId: string) { diff --git a/src/file/paragraph/formatting/tab-stop.ts b/src/file/paragraph/formatting/tab-stop.ts index 696361cb84..058afa3479 100644 --- a/src/file/paragraph/formatting/tab-stop.ts +++ b/src/file/paragraph/formatting/tab-stop.ts @@ -12,11 +12,18 @@ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; /** * Definition for a single tab stop. * + * @property type - The type of tab stop alignment + * @property position - The position of the tab stop in twips + * @property leader - Optional leader character to fill space before the tab + * * @see {@link TabStop} */ export type TabStopDefinition = { + /** The type of tab stop alignment */ readonly type: (typeof TabStopType)[keyof typeof TabStopType]; + /** The position of the tab stop in twips */ readonly position: number | (typeof TabStopPosition)[keyof typeof TabStopPosition]; + /** Optional leader character to fill space before the tab */ readonly leader?: (typeof LeaderType)[keyof typeof LeaderType]; }; @@ -26,6 +33,27 @@ export type TabStopDefinition = { * Tab stops define the positions where text will align when a tab character is used. * * Reference: http://officeopenxml.com/WPtab.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Paragraph({ + * tabStops: [ + * { type: TabStopType.LEFT, position: 2000 }, + * { type: TabStopType.CENTER, position: 4000 }, + * { type: TabStopType.RIGHT, position: TabStopPosition.MAX, leader: LeaderType.DOT }, + * ], + * children: [new TextRun("Text\twith\ttabs")], + * }); + * ``` */ export class TabStop extends XmlComponent { public constructor(tabDefinitions: readonly TabStopDefinition[]) { @@ -105,6 +133,17 @@ export class TabAttributes extends XmlAttributeComponent<{ * Represents a single tab stop item in a WordprocessingML document. * * Reference: http://officeopenxml.com/WPtab.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @internal */ export class TabStopItem extends XmlComponent { public constructor({ type, position, leader }: TabStopDefinition) { diff --git a/src/file/paragraph/formatting/unordered-list.ts b/src/file/paragraph/formatting/unordered-list.ts index ba5c42ed74..308ba21545 100644 --- a/src/file/paragraph/formatting/unordered-list.ts +++ b/src/file/paragraph/formatting/unordered-list.ts @@ -14,6 +14,39 @@ import { Attributes, XmlComponent } from "@file/xml-components"; * for the paragraph, enabling numbered and bulleted lists. * * Reference: http://officeopenxml.com/WPnumbering.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a bulleted list item at level 0 + * new Paragraph({ + * numbering: { + * reference: "my-bullet-list", + * level: 0, + * }, + * children: [new TextRun("First item")], + * }); + * + * // Create a numbered list item at level 1 + * new Paragraph({ + * numbering: { + * reference: "my-numbered-list", + * level: 1, + * }, + * children: [new TextRun("Nested item")], + * }); + * ``` */ export class NumberProperties extends XmlComponent { public constructor(numberId: number | string, indentLevel: number) { @@ -23,6 +56,13 @@ export class NumberProperties extends XmlComponent { } } +/** + * Represents the indentation level (ilvl) for a numbered or bulleted list. + * + * The ilvl element specifies the list level (0-9) for the paragraph. + * + * @internal + */ class IndentLevel extends XmlComponent { public constructor(level: number) { super("w:ilvl"); @@ -41,6 +81,13 @@ class IndentLevel extends XmlComponent { } } +/** + * Represents the numbering definition ID (numId) for a numbered or bulleted list. + * + * The numId element specifies which numbering definition to use for the paragraph. + * + * @internal + */ class NumberId extends XmlComponent { public constructor(id: number | string) { super("w:numId"); diff --git a/src/file/paragraph/frame/frame-properties.ts b/src/file/paragraph/frame/frame-properties.ts index ea24825720..a557b85777 100644 --- a/src/file/paragraph/frame/frame-properties.ts +++ b/src/file/paragraph/frame/frame-properties.ts @@ -1,103 +1,284 @@ -// http://officeopenxml.com/WPparagraph-textFrames.php +/** + * Frame properties module for paragraph text frames in WordprocessingML documents. + * + * Frames allow paragraphs to be positioned absolutely on the page, enabling text wrapping + * and drop cap effects. They are commonly used for floating text boxes and decorative elements. + * + * Reference: http://officeopenxml.com/WPparagraph-textFrames.php + * + * @module + */ import { HorizontalPositionAlign, VerticalPositionAlign } from "@file/shared/alignment"; import { HeightRule } from "@file/table"; import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Drop cap types for paragraph frames. + * + * Drop caps are decorative large initial letters that span multiple lines at the + * beginning of a paragraph. This enum defines how the drop cap should be positioned. + */ export const DropCapType = { + /** No drop cap effect */ NONE: "none", + /** Drop cap that drops down into the paragraph text */ DROP: "drop", + /** Drop cap that extends into the margin */ MARGIN: "margin", } as const; +/** + * Frame anchor types specifying what the frame should be anchored relative to. + * + * Determines the reference point for frame positioning (horizontal and vertical). + */ export const FrameAnchorType = { + /** Anchor relative to the page margin */ MARGIN: "margin", + /** Anchor relative to the page edge */ PAGE: "page", + /** Anchor relative to the text column */ TEXT: "text", } as const; +/** + * Text wrapping types for frames. + * + * Controls how surrounding text wraps around the frame. + */ export const FrameWrap = { + /** Wrap text around the frame on all sides */ AROUND: "around", + /** Automatic wrapping based on available space */ AUTO: "auto", + /** No text wrapping */ NONE: "none", - + /** Do not allow text beside the frame */ NOT_BESIDE: "notBeside", + /** Allow text to flow through the frame */ THROUGH: "through", + /** Wrap text tightly around the frame */ TIGHT: "tight", } as const; +/** + * Base options shared by all frame types. + * + * @property anchorLock - Lock the anchor position to prevent it from moving + * @property dropCap - Drop cap effect type + * @property width - Frame width in twips + * @property height - Frame height in twips + * @property wrap - Text wrapping behavior around the frame + * @property lines - Number of lines for drop cap effect + * @property anchor - Anchor reference points for horizontal and vertical positioning + * @property space - Spacing between frame and surrounding text + * @property rule - Height rule determining how frame height is calculated + */ type IBaseFrameOptions = { + /** Lock the anchor position to prevent it from moving */ readonly anchorLock?: boolean; + /** Drop cap effect type */ readonly dropCap?: (typeof DropCapType)[keyof typeof DropCapType]; + /** Frame width in twips */ readonly width: number; + /** Frame height in twips */ readonly height: number; + /** Text wrapping behavior around the frame */ readonly wrap?: (typeof FrameWrap)[keyof typeof FrameWrap]; + /** Number of lines for drop cap effect */ readonly lines?: number; + /** Anchor reference points for horizontal and vertical positioning */ readonly anchor: { + /** Horizontal anchor reference point */ readonly horizontal: (typeof FrameAnchorType)[keyof typeof FrameAnchorType]; + /** Vertical anchor reference point */ readonly vertical: (typeof FrameAnchorType)[keyof typeof FrameAnchorType]; }; + /** Spacing between frame and surrounding text in twips */ readonly space?: { + /** Horizontal spacing in twips */ readonly horizontal: number; + /** Vertical spacing in twips */ readonly vertical: number; }; + /** Height rule determining how frame height is calculated */ readonly rule?: (typeof HeightRule)[keyof typeof HeightRule]; }; +/** + * Options for frames positioned using absolute X/Y coordinates. + * + * Use this type when you need precise control over frame positioning using + * specific coordinate values. + * + * @property type - Must be "absolute" for coordinate-based positioning + * @property position - Absolute X and Y coordinates in twips + */ export type IXYFrameOptions = { + /** Must be "absolute" for coordinate-based positioning */ readonly type: "absolute"; + /** Absolute X and Y coordinates in twips */ readonly position: { + /** Horizontal position in twips from the anchor point */ readonly x: number; + /** Vertical position in twips from the anchor point */ readonly y: number; }; } & IBaseFrameOptions; +/** + * Options for frames positioned using alignment values. + * + * Use this type when you want to position the frame relative to the anchor + * using standard alignment positions (e.g., left, center, right, top, bottom). + * + * @property type - Must be "alignment" for alignment-based positioning + * @property alignment - Horizontal and vertical alignment values + */ export type IAlignmentFrameOptions = { + /** Must be "alignment" for alignment-based positioning */ readonly type: "alignment"; + /** Horizontal and vertical alignment values */ readonly alignment: { + /** Horizontal alignment relative to the anchor */ readonly x: (typeof HorizontalPositionAlign)[keyof typeof HorizontalPositionAlign]; + /** Vertical alignment relative to the anchor */ readonly y: (typeof VerticalPositionAlign)[keyof typeof VerticalPositionAlign]; }; } & IBaseFrameOptions; -// Be wary of Typescript's Open types: -// https://stackoverflow.com/q/46370222/3481582 +/** + * Union type for all frame positioning options. + * + * A frame can be positioned using either absolute coordinates (IXYFrameOptions) + * or alignment values (IAlignmentFrameOptions). + * + * Note: Be wary of TypeScript's Open types when using discriminated unions. + * Reference: https://stackoverflow.com/q/46370222/3481582 + */ export type IFrameOptions = IXYFrameOptions | IAlignmentFrameOptions; -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// +/** + * Internal attributes type for the frame properties XML element. + * + * This type maps the high-level IFrameOptions to the actual XML attributes + * used in the OOXML format. + * + * @property anchorLock - Lock the anchor position + * @property dropCap - Drop cap effect type + * @property width - Frame width in twips + * @property height - Frame height in twips + * @property x - Absolute horizontal position in twips (for coordinate-based positioning) + * @property y - Absolute vertical position in twips (for coordinate-based positioning) + * @property wrap - Text wrapping behavior + * @property lines - Number of lines for drop cap + * @property anchorHorizontal - Horizontal anchor reference point + * @property anchorVertical - Vertical anchor reference point + * @property spaceHorizontal - Horizontal spacing in twips + * @property spaceVertical - Vertical spacing in twips + * @property rule - Height rule + * @property alignmentX - Horizontal alignment (for alignment-based positioning) + * @property alignmentY - Vertical alignment (for alignment-based positioning) + */ type FramePropertiesAttributes = { + /** Lock the anchor position */ readonly anchorLock?: boolean; + /** Drop cap effect type */ readonly dropCap?: (typeof DropCapType)[keyof typeof DropCapType]; + /** Frame width in twips */ readonly width: number; + /** Frame height in twips */ readonly height: number; + /** Absolute horizontal position in twips (for coordinate-based positioning) */ readonly x?: number; + /** Absolute vertical position in twips (for coordinate-based positioning) */ readonly y?: number; + /** Text wrapping behavior */ readonly wrap?: (typeof FrameWrap)[keyof typeof FrameWrap]; + /** Number of lines for drop cap */ readonly lines?: number; + /** Horizontal anchor reference point */ readonly anchorHorizontal?: (typeof FrameAnchorType)[keyof typeof FrameAnchorType]; + /** Vertical anchor reference point */ readonly anchorVertical?: (typeof FrameAnchorType)[keyof typeof FrameAnchorType]; + /** Horizontal spacing in twips */ readonly spaceHorizontal?: number; + /** Vertical spacing in twips */ readonly spaceVertical?: number; + /** Height rule */ readonly rule?: (typeof HeightRule)[keyof typeof HeightRule]; + /** Horizontal alignment (for alignment-based positioning) */ readonly alignmentX?: (typeof HorizontalPositionAlign)[keyof typeof HorizontalPositionAlign]; + /** Vertical alignment (for alignment-based positioning) */ readonly alignmentY?: (typeof VerticalPositionAlign)[keyof typeof VerticalPositionAlign]; }; +/** + * Creates a frame properties XML component for paragraph text frames. + * + * Frames allow paragraphs to be positioned absolutely on the page with text wrapping. + * They support both coordinate-based and alignment-based positioning, along with + * drop cap effects and various text wrapping options. + * + * Reference: http://officeopenxml.com/WPparagraph-textFrames.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Frame with absolute positioning + * createFrameProperties({ + * type: "absolute", + * position: { x: 1440, y: 1440 }, // 1 inch from anchor + * width: 2880, // 2 inches + * height: 1440, // 1 inch + * anchor: { + * horizontal: FrameAnchorType.PAGE, + * vertical: FrameAnchorType.PAGE, + * }, + * wrap: FrameWrap.AROUND, + * }); + * + * // Frame with alignment positioning and drop cap + * createFrameProperties({ + * type: "alignment", + * alignment: { + * x: HorizontalPositionAlign.LEFT, + * y: VerticalPositionAlign.TOP, + * }, + * width: 1440, + * height: 1440, + * anchor: { + * horizontal: FrameAnchorType.TEXT, + * vertical: FrameAnchorType.TEXT, + * }, + * dropCap: DropCapType.DROP, + * lines: 3, + * }); + * ``` + * + * @param options - Frame positioning and formatting options + * @returns XmlComponent representing the frame properties element + */ export const createFrameProperties = (options: IFrameOptions): XmlComponent => new BuilderElement({ name: "w:framePr", diff --git a/src/file/paragraph/frame/index.ts b/src/file/paragraph/frame/index.ts index 92a61d95ef..266e2b6796 100644 --- a/src/file/paragraph/frame/index.ts +++ b/src/file/paragraph/frame/index.ts @@ -1 +1,6 @@ +/** + * Paragraph frame module exports. + * + * @module + */ export * from "./frame-properties"; diff --git a/src/file/paragraph/index.ts b/src/file/paragraph/index.ts index c1b59e4deb..7fdbcdf3e3 100644 --- a/src/file/paragraph/index.ts +++ b/src/file/paragraph/index.ts @@ -1,3 +1,8 @@ +/** + * Paragraph module exports. + * + * @module + */ export * from "./formatting"; export * from "./paragraph"; export * from "./properties"; diff --git a/src/file/paragraph/links/bookmark-attributes.ts b/src/file/paragraph/links/bookmark-attributes.ts index c6174732dc..8d6931e9f7 100644 --- a/src/file/paragraph/links/bookmark-attributes.ts +++ b/src/file/paragraph/links/bookmark-attributes.ts @@ -1,7 +1,53 @@ +/** + * Bookmark attributes module for WordprocessingML documents. + * + * This module provides attribute components for bookmark start and end elements. + * + * Reference: http://officeopenxml.com/WPbookmark.php + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for the bookmark start element. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + */ export class BookmarkStartAttributes extends XmlAttributeComponent<{ + /** Unique numeric identifier for the bookmark */ readonly id: number; + /** Name of the bookmark used for reference */ readonly name: string; }> { protected readonly xmlKeys = { @@ -10,7 +56,26 @@ export class BookmarkStartAttributes extends XmlAttributeComponent<{ }; } +/** + * Attributes for the bookmark end element. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + */ export class BookmarkEndAttributes extends XmlAttributeComponent<{ + /** Unique numeric identifier matching the bookmark start */ readonly id: number; }> { protected readonly xmlKeys = { diff --git a/src/file/paragraph/links/bookmark.ts b/src/file/paragraph/links/bookmark.ts index 92a9ea104d..1e395f75c7 100644 --- a/src/file/paragraph/links/bookmark.ts +++ b/src/file/paragraph/links/bookmark.ts @@ -14,20 +14,55 @@ import { bookmarkUniqueNumericIdGen } from "@util/convenience-functions"; import { ParagraphChild } from "../paragraph"; import { BookmarkEndAttributes, BookmarkStartAttributes } from "./bookmark-attributes"; +/** + * Options for creating a bookmark. + * + * @property id - The bookmark name used for reference + * @property children - Array of paragraph children contained within the bookmark range + */ +export type IBookmarkOptions = { + /** The bookmark name used for reference */ + readonly id: string; + /** Array of paragraph children contained within the bookmark range */ + readonly children: readonly ParagraphChild[]; +}; + /** * Represents a bookmark in a WordprocessingML document. * * A bookmark identifies a location or range of content that can be referenced - * elsewhere, such as from a hyperlink or table of contents. + * elsewhere, such as from a hyperlink or table of contents. The bookmark consists + * of a start marker, content, and an end marker. * * Reference: http://officeopenxml.com/WPbookmark.php * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * * @example * ```typescript + * // Create a bookmark around a heading * new Bookmark({ * id: "section1", * children: [new TextRun("Section 1 Heading")], * }); + * + * // Link to the bookmark from elsewhere + * new InternalHyperlink({ + * children: [new TextRun("Go to Section 1")], + * anchor: "section1", + * }); * ``` */ export class Bookmark { @@ -37,7 +72,7 @@ export class Bookmark { public readonly children: readonly ParagraphChild[]; public readonly end: BookmarkEnd; - public constructor(options: { readonly id: string; readonly children: readonly ParagraphChild[] }) { + public constructor(options: IBookmarkOptions) { const linkId = this.bookmarkUniqueNumericId(); this.start = new BookmarkStart(options.id, linkId); @@ -47,7 +82,12 @@ export class Bookmark { } /** - * Represents the start of a bookmark range. + * Represents the start marker of a bookmark range. + * + * This element marks the beginning of a bookmarked region in the document. + * It must be paired with a corresponding BookmarkEnd element with the same id. + * + * Reference: http://officeopenxml.com/WPbookmark.php * * ## XSD Schema * ```xml @@ -61,6 +101,11 @@ export class Bookmark { * * * ``` + * + * @example + * ```typescript + * new BookmarkStart("myBookmark", 1); + * ``` */ export class BookmarkStart extends XmlComponent { public constructor(id: string, linkId: number) { @@ -75,11 +120,29 @@ export class BookmarkStart extends XmlComponent { } /** - * Represents the end of a bookmark range. + * Represents the end marker of a bookmark range. + * + * This element marks the end of a bookmarked region in the document. + * It must be paired with a corresponding BookmarkStart element with the same id. + * + * Reference: http://officeopenxml.com/WPbookmark.php * * ## XSD Schema * ```xml * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new BookmarkEnd(1); * ``` */ export class BookmarkEnd extends XmlComponent { diff --git a/src/file/paragraph/links/hyperlink-attributes.ts b/src/file/paragraph/links/hyperlink-attributes.ts index 28c884ceba..3e59926883 100644 --- a/src/file/paragraph/links/hyperlink-attributes.ts +++ b/src/file/paragraph/links/hyperlink-attributes.ts @@ -1,11 +1,46 @@ +/** + * Hyperlink attributes module for WordprocessingML documents. + * + * This module provides attribute components for hyperlink elements. + * + * Reference: http://officeopenxml.com/WPhyperlink.php + * + * @module + */ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Properties for hyperlink attributes. + * + * @property id - Relationship ID for external hyperlinks + * @property anchor - Bookmark name for internal hyperlinks + * @property history - Whether to add this link to the document's history + */ export type IHyperlinkAttributesProperties = { + /** Relationship ID for external hyperlinks */ readonly id?: string; + /** Bookmark name for internal hyperlinks */ readonly anchor?: string; + /** Whether to add this link to the document's history (1 for true, 0 for false) */ readonly history: number; }; +/** + * Attributes for the hyperlink element. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + */ export class HyperlinkAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { id: "r:id", diff --git a/src/file/paragraph/links/hyperlink.ts b/src/file/paragraph/links/hyperlink.ts index 2698238c99..533cf346f5 100644 --- a/src/file/paragraph/links/hyperlink.ts +++ b/src/file/paragraph/links/hyperlink.ts @@ -15,6 +15,8 @@ import { HyperlinkAttributes, IHyperlinkAttributesProperties } from "./hyperlink /** * Hyperlink type enumeration. + * + * Defines the types of hyperlinks supported in WordprocessingML documents. */ export const HyperlinkType = { /** Internal hyperlink to a bookmark within the document */ @@ -24,12 +26,53 @@ export const HyperlinkType = { } as const; /** - * Represents a hyperlink in a WordprocessingML document. + * Options for creating an internal hyperlink. * - * The hyperlink element specifies a hyperlink that can be either internal - * (to a bookmark) or external (to a URL). + * @property children - Array of paragraph children (usually TextRun elements) that form the hyperlink text + * @property anchor - Name of the bookmark to link to within the document + */ +export type IInternalHyperlinkOptions = { + /** Array of paragraph children that form the hyperlink text */ + readonly children: readonly ParagraphChild[]; + /** Name of the bookmark to link to within the document */ + readonly anchor: string; +}; + +/** + * Options for creating an external hyperlink. + * + * @property children - Array of paragraph children (usually TextRun elements) that form the hyperlink text + * @property link - URL to link to outside the document + */ +export type IExternalHyperlinkOptions = { + /** Array of paragraph children that form the hyperlink text */ + readonly children: readonly ParagraphChild[]; + /** URL to link to outside the document */ + readonly link: string; +}; + +/** + * Represents a concrete hyperlink in a WordprocessingML document. + * + * This class is the low-level implementation of hyperlinks used internally. + * Use InternalHyperlink or ExternalHyperlink for creating hyperlinks in documents. * * Reference: http://officeopenxml.com/WPhyperlink.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` */ export class ConcreteHyperlink extends XmlComponent { public readonly linkId: string; @@ -56,16 +99,39 @@ export class ConcreteHyperlink extends XmlComponent { /** * Represents an internal hyperlink to a bookmark within the document. * + * Internal hyperlinks use the anchor attribute to reference a bookmark by name. + * The bookmark must exist in the document for the hyperlink to function. + * + * Reference: http://officeopenxml.com/WPhyperlink.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * * @example * ```typescript + * // Create a bookmark + * new Bookmark({ + * id: "section1", + * children: [new TextRun("Section 1")], + * }); + * + * // Link to the bookmark * new InternalHyperlink({ - * children: [new TextRun("Go to Section 1")], + * children: [new TextRun({ text: "Go to Section 1", style: "Hyperlink" })], * anchor: "section1", * }); * ``` */ export class InternalHyperlink extends ConcreteHyperlink { - public constructor(options: { readonly children: readonly ParagraphChild[]; readonly anchor: string }) { + public constructor(options: IInternalHyperlinkOptions) { super(options.children, uniqueId(), options.anchor); } } @@ -73,21 +139,33 @@ export class InternalHyperlink extends ConcreteHyperlink { /** * Represents an external hyperlink to a URL outside the document. * + * External hyperlinks create a relationship to an external resource (URL). + * The relationship is created during document preparation and the hyperlink + * is converted to a ConcreteHyperlink with the relationship ID. + * + * Reference: http://officeopenxml.com/WPhyperlink.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * * @example * ```typescript * new ExternalHyperlink({ - * children: [new TextRun("Visit Example")], + * children: [new TextRun({ text: "Visit Example", style: "Hyperlink" })], * link: "https://example.com", * }); * ``` */ export class ExternalHyperlink extends XmlComponent { - public constructor( - public readonly options: { - readonly children: readonly ParagraphChild[]; - readonly link: string; - }, - ) { + public constructor(public readonly options: IExternalHyperlinkOptions) { super("w:externalHyperlink"); } } diff --git a/src/file/paragraph/links/index.ts b/src/file/paragraph/links/index.ts index a0e39eb16e..6ce46699e7 100644 --- a/src/file/paragraph/links/index.ts +++ b/src/file/paragraph/links/index.ts @@ -1,3 +1,8 @@ +/** + * Links module exports. + * + * @module + */ export * from "./hyperlink"; export * from "./bookmark"; export * from "./numbered-item-ref"; diff --git a/src/file/paragraph/links/numbered-item-ref.ts b/src/file/paragraph/links/numbered-item-ref.ts index 1691d8ff7a..dc6269055b 100644 --- a/src/file/paragraph/links/numbered-item-ref.ts +++ b/src/file/paragraph/links/numbered-item-ref.ts @@ -1,6 +1,20 @@ +/** + * Numbered item reference module for WordprocessingML documents. + * + * This module provides cross-references to numbered items (such as + * numbered paragraphs, list items, or headings) within a document. + * + * Reference: https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oi29500/7088a8ce-e784-49d4-94b8-cba6ef8fce78 + * + * @module + */ import { SimpleField } from "../run/simple-field"; -// https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oi29500/7088a8ce-e784-49d4-94b8-cba6ef8fce78 +/** + * Format options for numbered item references. + * + * Specifies how the paragraph number should be displayed when referenced. + */ export enum NumberedItemReferenceFormat { NONE = "none", /** @@ -41,6 +55,18 @@ const SWITCH_MAP: Record = { /** * Creates a field/cross reference to a numbered item in the document. + * + * The REF field displays the text or page number of a bookmarked paragraph, + * particularly useful for referencing numbered headings or list items. + * + * @example + * ```typescript + * // Reference a numbered heading + * new NumberedItemReference("heading_1_bookmark", "1.2.3", { + * hyperlink: true, + * referenceFormat: NumberedItemReferenceFormat.FULL_CONTEXT, + * }); + * ``` */ export class NumberedItemReference extends SimpleField { public constructor( diff --git a/src/file/paragraph/links/outline-level.ts b/src/file/paragraph/links/outline-level.ts index f5eebd1018..72df229055 100644 --- a/src/file/paragraph/links/outline-level.ts +++ b/src/file/paragraph/links/outline-level.ts @@ -1,6 +1,38 @@ -// http://officeopenxml.com/WPparagraph.php +/** + * Outline level module for WordprocessingML documents. + * + * This module provides the outline level element which specifies + * the outline level of a paragraph for document outline/TOC purposes. + * + * Reference: http://officeopenxml.com/WPparagraph.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; +/** + * Represents an outline level for a paragraph. + * + * The outline level determines the paragraph's position in the document + * outline and affects table of contents generation. Level 0 corresponds + * to Heading 1, level 1 to Heading 2, etc. + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Set outline level to 0 (Heading 1) + * new OutlineLevel(0); + * + * // Set outline level to 2 (Heading 3) + * new OutlineLevel(2); + * ``` + */ export class OutlineLevel extends XmlComponent { public constructor(public readonly level: number) { super("w:outlineLvl"); diff --git a/src/file/paragraph/links/pageref-field-instruction.ts b/src/file/paragraph/links/pageref-field-instruction.ts index da1ca03bfb..d79d0f1b6d 100644 --- a/src/file/paragraph/links/pageref-field-instruction.ts +++ b/src/file/paragraph/links/pageref-field-instruction.ts @@ -1,9 +1,40 @@ +/** + * Page reference field instruction module for WordprocessingML documents. + * + * This module provides the field instruction element for page references, + * which displays the page number of a bookmarked location. + * + * Reference: http://officeopenxml.com/WPfields.php + * + * @module + */ import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; import { IPageReferenceOptions } from "./pageref"; import { TextAttributes } from "../run/text-attributes"; +/** + * Represents a PAGEREF field instruction. + * + * The PAGEREF field inserts the page number of the page containing + * the specified bookmark. It can optionally create a hyperlink + * and display relative positioning (e.g., "on the previous page"). + * + * @example + * ```typescript + * // Basic page reference + * new PageReferenceFieldInstruction("figure_1"); + * + * // Page reference with hyperlink and relative position + * new PageReferenceFieldInstruction("table_1", { + * hyperlink: true, + * useRelativePosition: true, + * }); + * ``` + * + * @internal + */ export class PageReferenceFieldInstruction extends XmlComponent { public constructor(bookmarkId: string, options: IPageReferenceOptions = {}) { super("w:instrText"); diff --git a/src/file/paragraph/links/pageref.ts b/src/file/paragraph/links/pageref.ts index 9305f0f305..6a1cd2b722 100644 --- a/src/file/paragraph/links/pageref.ts +++ b/src/file/paragraph/links/pageref.ts @@ -1,10 +1,23 @@ -// See https://www.ecma-international.org/publications/standards/Ecma-376.htm (at Part 1, Page 1234) +/** + * Page reference module for WordprocessingML documents. + * + * This module provides page reference elements for cross-referencing + * the page number of a bookmarked location. + * + * Reference: https://www.ecma-international.org/publications/standards/Ecma-376.htm (Part 1, Page 1234) + * + * @module + */ import { Begin, End } from "@file/paragraph/run/field"; import { Run } from "../run"; import { PageReferenceFieldInstruction } from "./pageref-field-instruction"; -// Options according to https://www.ecma-international.org/publications/standards/Ecma-376.htm (at Part 1, Page 1234) +/** + * Options for page reference fields. + * + * @see {@link PageReference} + */ export type IPageReferenceOptions = { /** * \h option - Creates a hyperlink to the bookmarked paragraph. @@ -20,6 +33,27 @@ export type IPageReferenceOptions = { readonly useRelativePosition?: boolean; }; +/** + * Represents a page reference (PAGEREF) field. + * + * The PAGEREF field displays the page number of the page containing + * the specified bookmark, useful for cross-references like "see page 5". + * + * @example + * ```typescript + * // Simple page reference + * new PageReference("figure_1_bookmark"); + * + * // With hyperlink + * new PageReference("table_2", { hyperlink: true }); + * + * // With relative position (e.g., "above" or "on page 5") + * new PageReference("section_3", { + * hyperlink: true, + * useRelativePosition: true, + * }); + * ``` + */ export class PageReference extends Run { public constructor(bookmarkId: string, options: IPageReferenceOptions = {}) { super({ diff --git a/src/file/paragraph/math/bar/index.ts b/src/file/paragraph/math/bar/index.ts index c524bfc3cf..38bef35f25 100644 --- a/src/file/paragraph/math/bar/index.ts +++ b/src/file/paragraph/math/bar/index.ts @@ -1,2 +1,7 @@ +/** + * Math bar module exports. + * + * @module + */ export * from "./math-bar"; export * from "./math-bar-properties"; diff --git a/src/file/paragraph/math/bar/math-bar-pos.ts b/src/file/paragraph/math/bar/math-bar-pos.ts index f91ee0cf13..8565e167ab 100644 --- a/src/file/paragraph/math/bar/math-bar-pos.ts +++ b/src/file/paragraph/math/bar/math-bar-pos.ts @@ -1,8 +1,37 @@ -// https://www.datypic.com/sc/ooxml/e-m_pos-1.html +/** + * Math Bar Position module for Office MathML. + * + * This module provides the position property for bar structures. + * + * Reference: https://www.datypic.com/sc/ooxml/e-m_pos-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -type MathBarPosOptions = { readonly val: string }; +/** + * Options for creating a bar position element. + */ +type MathBarPosOptions = { + /** Position value: "top" for overline, "bot" for underline */ + readonly val: string; +}; +/** + * Creates a position element for bar structures. + * + * This element specifies whether the bar appears above (top) or below (bot) + * the base expression. + * + * Reference: https://www.datypic.com/sc/ooxml/e-m_pos-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathBarPos = ({ val }: MathBarPosOptions): XmlComponent => new BuilderElement({ name: "m:pos", diff --git a/src/file/paragraph/math/bar/math-bar-properties.ts b/src/file/paragraph/math/bar/math-bar-properties.ts index 90e91642ec..0e02244ec3 100644 --- a/src/file/paragraph/math/bar/math-bar-properties.ts +++ b/src/file/paragraph/math/bar/math-bar-properties.ts @@ -1,8 +1,34 @@ -// https://www.datypic.com/sc/ooxml/e-m_barPr-1.html +/** + * Math Bar Properties module for Office MathML. + * + * This module provides properties for bar (overline/underline) structures in math equations. + * + * Reference: https://www.datypic.com/sc/ooxml/e-m_barPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createMathBarPos } from "./math-bar-pos"; +/** + * Creates properties for a math bar structure. + * + * This element specifies properties for the bar object, + * primarily the position (top for overline, bottom for underline). + * + * Reference: https://www.datypic.com/sc/ooxml/e-m_barPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const createMathBarProperties = ({ type }: { readonly type: string }): XmlComponent => new BuilderElement({ name: "m:barPr", diff --git a/src/file/paragraph/math/brackets/index.ts b/src/file/paragraph/math/brackets/index.ts index e6559cde29..6fb93ef887 100644 --- a/src/file/paragraph/math/brackets/index.ts +++ b/src/file/paragraph/math/brackets/index.ts @@ -1,3 +1,8 @@ +/** + * Math brackets module exports. + * + * @module + */ export * from "./math-round-brackets"; export * from "./math-square-brackets"; export * from "./math-curly-brackets"; diff --git a/src/file/paragraph/math/brackets/math-beginning-character.ts b/src/file/paragraph/math/brackets/math-beginning-character.ts index c590411e0e..c5bf56508c 100644 --- a/src/file/paragraph/math/brackets/math-beginning-character.ts +++ b/src/file/paragraph/math/brackets/math-beginning-character.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_begChr-1.html +/** + * Math Beginning Character module for Office MathML. + * + * This module provides the beginning (opening) character for bracket delimiters. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_begChr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -type MathBeginningCharacterOptions = { readonly character: string }; +/** + * Options for creating a beginning character element. + */ +type MathBeginningCharacterOptions = { + /** The opening bracket character */ + readonly character: string; +}; +/** + * Creates a beginning character element for bracket delimiters. + * + * This element specifies the opening/beginning character for a delimiter object, + * such as "(", "[", "{", or "⟨". + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_begChr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathBeginningCharacter = ({ character }: MathBeginningCharacterOptions): XmlComponent => new BuilderElement({ name: "m:begChr", diff --git a/src/file/paragraph/math/brackets/math-bracket-properties.ts b/src/file/paragraph/math/brackets/math-bracket-properties.ts index c80fae1648..1e4368490d 100644 --- a/src/file/paragraph/math/brackets/math-bracket-properties.ts +++ b/src/file/paragraph/math/brackets/math-bracket-properties.ts @@ -1,11 +1,52 @@ -// http://www.datypic.com/sc/ooxml/e-m_dPr-1.html +/** + * Math Bracket Properties module for Office MathML. + * + * This module provides properties for bracket delimiters in math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_dPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createMathBeginningCharacter } from "./math-beginning-character"; import { createMathEndingCharacter } from "./math-ending-char"; -type MathBracketPropertiesOptions = { readonly characters?: { readonly beginningCharacter: string; readonly endingCharacter: string } }; +/** + * Options for creating math bracket properties. + */ +type MathBracketPropertiesOptions = { + /** Optional custom characters for bracket delimiters */ + readonly characters?: { + /** The opening/beginning bracket character */ + readonly beginningCharacter: string; + /** The closing/ending bracket character */ + readonly endingCharacter: string; + }; +}; +/** + * Creates bracket properties for math delimiter objects. + * + * This element specifies properties for the delimiter object, + * including custom beginning and ending characters. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_dPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + */ export const createMathBracketProperties = ({ characters }: MathBracketPropertiesOptions): XmlComponent => new BuilderElement({ name: "m:dPr", diff --git a/src/file/paragraph/math/brackets/math-ending-char.ts b/src/file/paragraph/math/brackets/math-ending-char.ts index 9634e26c8e..4ac497a4d1 100644 --- a/src/file/paragraph/math/brackets/math-ending-char.ts +++ b/src/file/paragraph/math/brackets/math-ending-char.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_endChr-1.html +/** + * Math Ending Character module for Office MathML. + * + * This module provides the ending (closing) character for bracket delimiters. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_endChr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -type MathEndingCharacterOptions = { readonly character: string }; +/** + * Options for creating an ending character element. + */ +type MathEndingCharacterOptions = { + /** The closing bracket character */ + readonly character: string; +}; +/** + * Creates an ending character element for bracket delimiters. + * + * This element specifies the closing/ending character for a delimiter object, + * such as ")", "]", "}", or "⟩". + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_endChr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathEndingCharacter = ({ character }: MathEndingCharacterOptions): XmlComponent => new BuilderElement({ name: "m:endChr", diff --git a/src/file/paragraph/math/fraction/index.ts b/src/file/paragraph/math/fraction/index.ts index c8af438329..1815be2b67 100644 --- a/src/file/paragraph/math/fraction/index.ts +++ b/src/file/paragraph/math/fraction/index.ts @@ -1,3 +1,8 @@ +/** + * Math fraction module exports. + * + * @module + */ export * from "./math-fraction"; export * from "./math-denominator"; export * from "./math-numerator"; diff --git a/src/file/paragraph/math/function/index.ts b/src/file/paragraph/math/function/index.ts index 58243c2710..f3922ef1ec 100644 --- a/src/file/paragraph/math/function/index.ts +++ b/src/file/paragraph/math/function/index.ts @@ -1,3 +1,8 @@ +/** + * Math function module exports. + * + * @module + */ export * from "./math-function"; export * from "./math-function-name"; export * from "./math-function-properties"; diff --git a/src/file/paragraph/math/function/math-function-name.ts b/src/file/paragraph/math/function/math-function-name.ts index 1a02f4ccb2..1d37e75c8e 100644 --- a/src/file/paragraph/math/function/math-function-name.ts +++ b/src/file/paragraph/math/function/math-function-name.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_fName-1.html +/** + * Math Function Name module for Office MathML. + * + * This module provides the function name element for function structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_fName-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; +/** + * Represents a function name in a math equation. + * + * MathFunctionName contains the function name (e.g., sin, cos, log) + * that appears before the function argument. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_fName-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @internal + */ export class MathFunctionName extends XmlComponent { public constructor(children: readonly MathComponent[]) { super("m:fName"); diff --git a/src/file/paragraph/math/function/math-function-properties.ts b/src/file/paragraph/math/function/math-function-properties.ts index b380e4f6f0..1ba169deb5 100644 --- a/src/file/paragraph/math/function/math-function-properties.ts +++ b/src/file/paragraph/math/function/math-function-properties.ts @@ -1,6 +1,33 @@ -// http://www.datypic.com/sc/ooxml/e-m_radPr-1.html +/** + * Math Function Properties module for Office MathML. + * + * This module provides properties for function structures in math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_funcPr-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents properties for a math function structure. + * + * This element specifies properties for the function object, + * such as function name alignment and spacing. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_funcPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @internal + */ export class MathFunctionProperties extends XmlComponent { public constructor() { super("m:funcPr"); diff --git a/src/file/paragraph/math/index.ts b/src/file/paragraph/math/index.ts index b42ec908f6..1f4fc8e12c 100644 --- a/src/file/paragraph/math/index.ts +++ b/src/file/paragraph/math/index.ts @@ -1,3 +1,8 @@ +/** + * Math module exports. + * + * @module + */ export * from "./math"; export * from "./math-run"; export * from "./fraction"; diff --git a/src/file/paragraph/math/n-ary/index.ts b/src/file/paragraph/math/n-ary/index.ts index 81a5c23957..0c8b308310 100644 --- a/src/file/paragraph/math/n-ary/index.ts +++ b/src/file/paragraph/math/n-ary/index.ts @@ -1,3 +1,8 @@ +/** + * Math n-ary module exports. + * + * @module + */ export * from "./math-accent-character"; export * from "./math-base"; export * from "./math-limit-location"; diff --git a/src/file/paragraph/math/n-ary/math-accent-character.ts b/src/file/paragraph/math/n-ary/math-accent-character.ts index 9887ca8a7b..82406422a2 100644 --- a/src/file/paragraph/math/n-ary/math-accent-character.ts +++ b/src/file/paragraph/math/n-ary/math-accent-character.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_chr-1.html +/** + * Math Accent Character module for Office MathML. + * + * This module provides the accent character for n-ary operators. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_chr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -type MathAccentCharacterOptions = { readonly accent: string }; +/** + * Options for creating an accent character element. + */ +type MathAccentCharacterOptions = { + /** The n-ary operator character (e.g., "∑", "∫", "∏") */ + readonly accent: string; +}; +/** + * Creates an accent character element for n-ary operators. + * + * This element specifies the character used for the n-ary operator, + * such as summation (∑), integral (∫), or product (∏) symbols. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_chr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathAccentCharacter = ({ accent }: MathAccentCharacterOptions): XmlComponent => new BuilderElement({ name: "m:chr", diff --git a/src/file/paragraph/math/n-ary/math-limit-location.ts b/src/file/paragraph/math/n-ary/math-limit-location.ts index b7de16c002..ee5a382ace 100644 --- a/src/file/paragraph/math/n-ary/math-limit-location.ts +++ b/src/file/paragraph/math/n-ary/math-limit-location.ts @@ -1,8 +1,38 @@ -// http://www.datypic.com/sc/ooxml/e-m_limLoc-1.html +/** + * Math Limit Location module for Office MathML. + * + * This module provides the limit location property for n-ary operators. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limLoc-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -type MathLimitLocationOptions = { readonly value?: string }; +/** + * Options for creating a limit location element. + */ +type MathLimitLocationOptions = { + /** Location: "undOvr" (under/over) or "subSup" (subscript/superscript). Defaults to "undOvr". */ + readonly value?: string; +}; +/** + * Creates a limit location element for n-ary operators. + * + * This element specifies where limits appear relative to the operator: + * - "undOvr": limits appear directly above and below the operator + * - "subSup": limits appear as superscript and subscript + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limLoc-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathLimitLocation = ({ value }: MathLimitLocationOptions): XmlComponent => new BuilderElement>({ name: "m:limLoc", diff --git a/src/file/paragraph/math/n-ary/math-limit-lower.ts b/src/file/paragraph/math/n-ary/math-limit-lower.ts index c5706d69a7..30817cca89 100644 --- a/src/file/paragraph/math/n-ary/math-limit-lower.ts +++ b/src/file/paragraph/math/n-ary/math-limit-lower.ts @@ -1,15 +1,58 @@ -// http://www.datypic.com/sc/ooxml/e-m_limLow-1.html +/** + * Math Lower Limit module for Office MathML. + * + * This module provides the lower limit structure for math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limLow-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; import { createMathBase } from "./math-base"; import { MathLimit } from "./math-limit"; +/** + * Options for creating a MathLimitLower. + * + * @see {@link MathLimitLower} + */ export type IMathLimitLowerOptions = { + /** The base expression */ readonly children: readonly MathComponent[]; + /** The limit expression that appears below the base */ readonly limit: readonly MathComponent[]; }; +/** + * Represents a lower limit structure in a math equation. + * + * MathLimitLower displays content with a limit underneath, + * commonly used for limits in calculus (e.g., lim with x→0 below). + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limLow-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // lim with x→0 underneath + * new MathLimitLower({ + * children: [new MathRun("lim")], + * limit: [new MathRun("x→0")], + * }); + * ``` + */ export class MathLimitLower extends XmlComponent { public constructor(options: IMathLimitLowerOptions) { super("m:limLow"); diff --git a/src/file/paragraph/math/n-ary/math-limit-upper.ts b/src/file/paragraph/math/n-ary/math-limit-upper.ts index 61bffc074e..d74617cf5c 100644 --- a/src/file/paragraph/math/n-ary/math-limit-upper.ts +++ b/src/file/paragraph/math/n-ary/math-limit-upper.ts @@ -1,15 +1,58 @@ -// http://www.datypic.com/sc/ooxml/e-m_limUpp-1.html +/** + * Math Upper Limit module for Office MathML. + * + * This module provides the upper limit structure for math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limUpp-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; import { createMathBase } from "./math-base"; import { MathLimit } from "./math-limit"; +/** + * Options for creating a MathLimitUpper. + * + * @see {@link MathLimitUpper} + */ export type IMathLimitUpperOptions = { + /** The base expression */ readonly children: readonly MathComponent[]; + /** The limit expression that appears above the base */ readonly limit: readonly MathComponent[]; }; +/** + * Represents an upper limit structure in a math equation. + * + * MathLimitUpper displays content with a limit above, + * commonly used for mathematical notation like lim with conditions above. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_limUpp-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Expression with limit above + * new MathLimitUpper({ + * children: [new MathRun("max")], + * limit: [new MathRun("x∈S")], + * }); + * ``` + */ export class MathLimitUpper extends XmlComponent { public constructor(options: IMathLimitUpperOptions) { super("m:limUpp"); diff --git a/src/file/paragraph/math/n-ary/math-limit.ts b/src/file/paragraph/math/n-ary/math-limit.ts index 0827ff80a4..5687e82a7b 100644 --- a/src/file/paragraph/math/n-ary/math-limit.ts +++ b/src/file/paragraph/math/n-ary/math-limit.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_lim-1.html +/** + * Math Limit module for Office MathML. + * + * This module provides the limit element for under/over limit structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_lim-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; +/** + * Represents a limit in a math equation. + * + * MathLimit is used within limit structures to specify the limit + * expression that appears above or below the base. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_lim-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @internal + */ export class MathLimit extends XmlComponent { public constructor(children: readonly MathComponent[]) { super("m:lim"); diff --git a/src/file/paragraph/math/n-ary/math-n-ary-properties.ts b/src/file/paragraph/math/n-ary/math-n-ary-properties.ts index 779c811bda..5199adc797 100644 --- a/src/file/paragraph/math/n-ary/math-n-ary-properties.ts +++ b/src/file/paragraph/math/n-ary/math-n-ary-properties.ts @@ -1,4 +1,12 @@ -// http://www.datypic.com/sc/ooxml/e-m_naryPr-1.html +/** + * Math N-Ary Properties module for Office MathML. + * + * This module provides properties for n-ary operators (sum, integral, etc.) in math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_naryPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { createMathAccentCharacter } from "./math-accent-character"; @@ -6,13 +14,42 @@ import { createMathLimitLocation } from "./math-limit-location"; import { createMathSubScriptHide } from "./math-sub-script-hide"; import { createMathSuperScriptHide } from "./math-super-script-hide"; +/** + * Options for creating n-ary properties. + */ type MathNAryPropertiesOptions = { + /** The n-ary operator character (e.g., "∑" for sum, "∫" for integral) */ readonly accent: string; + /** Whether the n-ary has a superscript (upper limit) */ readonly hasSuperScript: boolean; + /** Whether the n-ary has a subscript (lower limit) */ readonly hasSubScript: boolean; + /** Location of limits: "undOvr" (under/over) or "subSup" (subscript/superscript) */ readonly limitLocationVal?: string; }; +/** + * Creates properties for n-ary operator structures. + * + * This element specifies properties for n-ary objects like summations + * and integrals, including the operator character and limit positioning. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_naryPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + */ export const createMathNAryProperties = ({ accent, hasSuperScript, diff --git a/src/file/paragraph/math/n-ary/math-sub-script-hide.ts b/src/file/paragraph/math/n-ary/math-sub-script-hide.ts index 1680caf97d..edc974bb10 100644 --- a/src/file/paragraph/math/n-ary/math-sub-script-hide.ts +++ b/src/file/paragraph/math/n-ary/math-sub-script-hide.ts @@ -1,6 +1,29 @@ -// http://www.datypic.com/sc/ooxml/e-m_subHide-1.html +/** + * Math SubScript Hide module for Office MathML. + * + * This module provides the element to hide subscripts in n-ary operators. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_subHide-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates a subscript hide element for n-ary operators. + * + * This element indicates that the subscript (lower limit) should be hidden + * in n-ary operators when no subscript is provided. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_subHide-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathSubScriptHide = (): XmlComponent => new BuilderElement<{ readonly hide: number }>({ name: "m:subHide", diff --git a/src/file/paragraph/math/n-ary/math-sub-script.ts b/src/file/paragraph/math/n-ary/math-sub-script.ts index b1fbf4708a..84c306a59e 100644 --- a/src/file/paragraph/math/n-ary/math-sub-script.ts +++ b/src/file/paragraph/math/n-ary/math-sub-script.ts @@ -1,12 +1,43 @@ -// http://www.datypic.com/sc/ooxml/e-m_sub-3.html +/** + * Math SubScript Element module for Office MathML. + * + * This module provides the subscript element for n-ary operators and other structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sub-3.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; +/** + * Options for creating a subscript element. + */ type MathSubScriptElementOptions = { + /** The content of the subscript */ readonly children: readonly MathComponent[]; }; +/** + * Creates a subscript element for math structures. + * + * This element contains the subscript content, used in n-ary operators, + * script objects, and other structures that support subscripts. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sub-3.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export const createMathSubScriptElement = ({ children }: MathSubScriptElementOptions): XmlComponent => new BuilderElement({ name: "m:sub", diff --git a/src/file/paragraph/math/n-ary/math-super-script-hide.ts b/src/file/paragraph/math/n-ary/math-super-script-hide.ts index 9af37c18ef..37363a82d3 100644 --- a/src/file/paragraph/math/n-ary/math-super-script-hide.ts +++ b/src/file/paragraph/math/n-ary/math-super-script-hide.ts @@ -1,6 +1,29 @@ -// http://www.datypic.com/sc/ooxml/e-m_subHide-1.html +/** + * Math SuperScript Hide module for Office MathML. + * + * This module provides the element to hide superscripts in n-ary operators. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_supHide-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates a superscript hide element for n-ary operators. + * + * This element indicates that the superscript (upper limit) should be hidden + * in n-ary operators when no superscript is provided. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_supHide-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + */ export const createMathSuperScriptHide = (): XmlComponent => new BuilderElement<{ readonly hide: number }>({ name: "m:supHide", diff --git a/src/file/paragraph/math/n-ary/math-super-script.ts b/src/file/paragraph/math/n-ary/math-super-script.ts index 5c09d4a72e..0a52b994c8 100644 --- a/src/file/paragraph/math/n-ary/math-super-script.ts +++ b/src/file/paragraph/math/n-ary/math-super-script.ts @@ -1,12 +1,43 @@ -// http://www.datypic.com/sc/ooxml/e-m_sup-3.html +/** + * Math SuperScript Element module for Office MathML. + * + * This module provides the superscript element for n-ary operators and other structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sup-3.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; +/** + * Options for creating a superscript element. + */ type MathSuperScriptElementOptions = { + /** The content of the superscript */ readonly children: readonly MathComponent[]; }; +/** + * Creates a superscript element for math structures. + * + * This element contains the superscript content, used in n-ary operators, + * script objects, and other structures that support superscripts. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sup-3.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export const createMathSuperScriptElement = ({ children }: MathSuperScriptElementOptions): XmlComponent => new BuilderElement({ name: "m:sup", diff --git a/src/file/paragraph/math/radical/index.ts b/src/file/paragraph/math/radical/index.ts index 78240ccd13..3f67d46c0f 100644 --- a/src/file/paragraph/math/radical/index.ts +++ b/src/file/paragraph/math/radical/index.ts @@ -1,3 +1,8 @@ +/** + * Math radical module exports. + * + * @module + */ export * from "./math-degree"; export * from "./math-radical"; export * from "./math-radical-properties"; diff --git a/src/file/paragraph/math/radical/math-degree-hide.ts b/src/file/paragraph/math/radical/math-degree-hide.ts index ab04bd2be4..f757f27b4b 100644 --- a/src/file/paragraph/math/radical/math-degree-hide.ts +++ b/src/file/paragraph/math/radical/math-degree-hide.ts @@ -1,10 +1,38 @@ -// http://www.datypic.com/sc/ooxml/e-m_degHide-1.html +/** + * Math Degree Hide module for Office MathML. + * + * This module provides the element to hide the degree in radical structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_degHide-1.html + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * @internal + */ class MathDegreeHideAttributes extends XmlAttributeComponent<{ readonly hide: number }> { protected readonly xmlKeys = { hide: "m:val" }; } +/** + * Represents a property to hide the degree in a radical. + * + * MathDegreeHide is used in radical properties to hide the degree, + * typically for square roots where the degree (2) is not displayed. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_degHide-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @internal + */ export class MathDegreeHide extends XmlComponent { public constructor() { super("m:degHide"); diff --git a/src/file/paragraph/math/radical/math-degree.ts b/src/file/paragraph/math/radical/math-degree.ts index b9e3e0f647..eaf7bd6c4b 100644 --- a/src/file/paragraph/math/radical/math-degree.ts +++ b/src/file/paragraph/math/radical/math-degree.ts @@ -1,8 +1,37 @@ -// http://www.datypic.com/sc/ooxml/e-m_deg-1.html +/** + * Math Degree module for Office MathML. + * + * This module provides the degree element for radical structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_deg-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; +/** + * Represents the degree of a radical (root) in a math equation. + * + * MathDegree specifies the degree of the root, such as 3 for cube root. + * For square roots, this element is typically hidden. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_deg-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @internal + */ export class MathDegree extends XmlComponent { public constructor(children?: readonly MathComponent[]) { super("m:deg"); diff --git a/src/file/paragraph/math/radical/math-radical-properties.ts b/src/file/paragraph/math/radical/math-radical-properties.ts index 923b975793..4648509845 100644 --- a/src/file/paragraph/math/radical/math-radical-properties.ts +++ b/src/file/paragraph/math/radical/math-radical-properties.ts @@ -1,8 +1,36 @@ -// http://www.datypic.com/sc/ooxml/e-m_radPr-1.html +/** + * Math Radical Properties module for Office MathML. + * + * This module provides properties for radical (root) structures in math equations. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_radPr-1.html + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { MathDegreeHide } from "./math-degree-hide"; +/** + * Represents properties for a radical structure. + * + * This element specifies properties for the radical object, + * such as whether to hide the degree (for square roots). + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_radPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @internal + */ export class MathRadicalProperties extends XmlComponent { public constructor(hasDegree: boolean) { super("m:radPr"); diff --git a/src/file/paragraph/math/script/index.ts b/src/file/paragraph/math/script/index.ts index a83e54975e..f864dc4e15 100644 --- a/src/file/paragraph/math/script/index.ts +++ b/src/file/paragraph/math/script/index.ts @@ -1,3 +1,8 @@ +/** + * Math script module exports. + * + * @module + */ export * from "./super-script"; export * from "./sub-script"; export * from "./sub-super-script"; diff --git a/src/file/paragraph/math/script/pre-sub-super-script/index.ts b/src/file/paragraph/math/script/pre-sub-super-script/index.ts index 8660a75017..d693816ca6 100644 --- a/src/file/paragraph/math/script/pre-sub-super-script/index.ts +++ b/src/file/paragraph/math/script/pre-sub-super-script/index.ts @@ -1,2 +1,7 @@ +/** + * Math pre-sub-super-script module exports. + * + * @module + */ export * from "./math-pre-sub-super-script-function"; export * from "./math-pre-sub-super-script-function-properties"; diff --git a/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function-properties.ts b/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function-properties.ts index ab1bc48bd5..29a8dfc9e1 100644 --- a/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function-properties.ts +++ b/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function-properties.ts @@ -1,6 +1,30 @@ -// http://www.datypic.com/sc/ooxml/e-m_sPrePr-1.html +/** + * Math Pre-Sub-Super-Script Properties module for Office MathML. + * + * This module provides properties for pre-script structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sPrePr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates properties for a pre-subscript and pre-superscript structure. + * + * This element specifies properties for the pre-script object. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sPrePr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + */ export const createMathPreSubSuperScriptProperties = (): XmlComponent => new BuilderElement({ name: "m:sPrePr", diff --git a/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function.ts b/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function.ts index 4fdb62d812..d3709ca0b2 100644 --- a/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function.ts +++ b/src/file/paragraph/math/script/pre-sub-super-script/math-pre-sub-super-script-function.ts @@ -1,16 +1,63 @@ -// http://www.datypic.com/sc/ooxml/e-m_sPre-1.html +/** + * Math Pre-Sub-Super-Script module for Office MathML. + * + * This module provides pre-scripts with both subscript and superscript, + * where the scripts appear before (to the left of) the base. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sPre-1.html + * + * @module + */ import { BuilderElement } from "@file/xml-components"; import { createMathPreSubSuperScriptProperties } from "./math-pre-sub-super-script-function-properties"; import type { MathComponent } from "../../math-component"; import { createMathBase, createMathSubScriptElement, createMathSuperScriptElement } from "../../n-ary"; +/** + * Options for creating a MathPreSubSuperScript. + * + * @see {@link MathPreSubSuperScript} + */ export type IMathPreSubSuperScriptOptions = { + /** The base expression */ readonly children: readonly MathComponent[]; + /** The pre-subscript expression (appears lower-left of base) */ readonly subScript: readonly MathComponent[]; + /** The pre-superscript expression (appears upper-left of base) */ readonly superScript: readonly MathComponent[]; }; +/** + * Represents a pre-subscript and pre-superscript expression in a math equation. + * + * MathPreSubSuperScript displays a base with both subscript and superscript + * positioned before (to the left of) the base, commonly used in tensor notation. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sPre-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Pre-scripts for tensor notation + * new MathPreSubSuperScript({ + * children: [new MathRun("T")], + * subScript: [new MathRun("i")], + * superScript: [new MathRun("j")], + * }); + * ``` + */ export class MathPreSubSuperScript extends BuilderElement { public constructor({ children, subScript, superScript }: IMathPreSubSuperScriptOptions) { super({ diff --git a/src/file/paragraph/math/script/sub-script/index.ts b/src/file/paragraph/math/script/sub-script/index.ts index 0f1c27fe51..57ab801dbb 100644 --- a/src/file/paragraph/math/script/sub-script/index.ts +++ b/src/file/paragraph/math/script/sub-script/index.ts @@ -1,2 +1,7 @@ +/** + * Math sub-script module exports. + * + * @module + */ export * from "./math-sub-script-function"; export * from "./math-sub-script-function-properties"; diff --git a/src/file/paragraph/math/script/sub-script/math-sub-script-function-properties.ts b/src/file/paragraph/math/script/sub-script/math-sub-script-function-properties.ts index 37457ea1ae..b561f89889 100644 --- a/src/file/paragraph/math/script/sub-script/math-sub-script-function-properties.ts +++ b/src/file/paragraph/math/script/sub-script/math-sub-script-function-properties.ts @@ -1,6 +1,30 @@ -// http://www.datypic.com/sc/ooxml/e-m_sSubPr-1.html +/** + * Math SubScript Properties module for Office MathML. + * + * This module provides properties for subscript structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSubPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates properties for a subscript structure. + * + * This element specifies properties for the subscript object. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSubPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + */ export const createMathSubScriptProperties = (): XmlComponent => new BuilderElement({ name: "m:sSubPr", diff --git a/src/file/paragraph/math/script/sub-super-script/index.ts b/src/file/paragraph/math/script/sub-super-script/index.ts index 88ddeb69fa..228a653d8f 100644 --- a/src/file/paragraph/math/script/sub-super-script/index.ts +++ b/src/file/paragraph/math/script/sub-super-script/index.ts @@ -1,2 +1,7 @@ +/** + * Math sub-super-script module exports. + * + * @module + */ export * from "./math-sub-super-script-function"; export * from "./math-sub-super-script-function-properties"; diff --git a/src/file/paragraph/math/script/sub-super-script/math-sub-super-script-function-properties.ts b/src/file/paragraph/math/script/sub-super-script/math-sub-super-script-function-properties.ts index e5002ded21..c7002f1b72 100644 --- a/src/file/paragraph/math/script/sub-super-script/math-sub-super-script-function-properties.ts +++ b/src/file/paragraph/math/script/sub-super-script/math-sub-super-script-function-properties.ts @@ -1,6 +1,31 @@ -// http://www.datypic.com/sc/ooxml/e-m_sSubSupPr-1.html +/** + * Math Sub-Super-Script Properties module for Office MathML. + * + * This module provides properties for combined subscript and superscript structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSubSupPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates properties for a combined subscript and superscript structure. + * + * This element specifies properties for the subscript-superscript object. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSubSupPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const createMathSubSuperScriptProperties = (): XmlComponent => new BuilderElement({ name: "m:sSubSupPr", diff --git a/src/file/paragraph/math/script/super-script/index.ts b/src/file/paragraph/math/script/super-script/index.ts index 2864fe9ac5..43bf194b1f 100644 --- a/src/file/paragraph/math/script/super-script/index.ts +++ b/src/file/paragraph/math/script/super-script/index.ts @@ -1,2 +1,7 @@ +/** + * Math super-script module exports. + * + * @module + */ export * from "./math-super-script-function"; export * from "./math-super-script-function-properties"; diff --git a/src/file/paragraph/math/script/super-script/math-super-script-function-properties.ts b/src/file/paragraph/math/script/super-script/math-super-script-function-properties.ts index 732df2b6f0..15218f437d 100644 --- a/src/file/paragraph/math/script/super-script/math-super-script-function-properties.ts +++ b/src/file/paragraph/math/script/super-script/math-super-script-function-properties.ts @@ -1,6 +1,30 @@ -// http://www.datypic.com/sc/ooxml/e-m_sSupPr-1.html +/** + * Math SuperScript Properties module for Office MathML. + * + * This module provides properties for superscript structures. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSupPr-1.html + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates properties for a superscript structure. + * + * This element specifies properties for the superscript object. + * + * Reference: http://www.datypic.com/sc/ooxml/e-m_sSupPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + */ export const createMathSuperScriptProperties = (): XmlComponent => new BuilderElement({ name: "m:sSupPr", diff --git a/src/file/paragraph/properties.ts b/src/file/paragraph/properties.ts index 30cf442c14..65665d01ce 100644 --- a/src/file/paragraph/properties.ts +++ b/src/file/paragraph/properties.ts @@ -33,12 +33,19 @@ import { OutlineLevel } from "./links"; * These properties are used when defining paragraph styles within numbering level definitions. */ export type ILevelParagraphStylePropertiesOptions = { + /** Paragraph text alignment (left, right, center, justified, etc.) */ readonly alignment?: (typeof AlignmentType)[keyof typeof AlignmentType]; + /** Whether to display a horizontal line (thematic break) below the paragraph */ readonly thematicBreak?: boolean; + /** Whether to ignore spacing before/after when adjacent paragraphs have the same style */ readonly contextualSpacing?: boolean; + /** Position in twips for a right-aligned tab stop */ readonly rightTabStop?: number; + /** Position in twips for a left-aligned tab stop */ readonly leftTabStop?: number; + /** Indentation settings for the paragraph */ readonly indent?: IIndentAttributesProperties; + /** Spacing before/after paragraph and between lines */ readonly spacing?: ISpacingProperties; /** * Specifies that the paragraph (or at least part of it) should be rendered on the same page as the next paragraph when possible. If multiple paragraphs are to be kept together but they exceed a page, then the set of paragraphs begin on a new page and page breaks are used thereafter as needed. @@ -48,6 +55,7 @@ export type ILevelParagraphStylePropertiesOptions = { * Specifies that all lines of the paragraph are to be kept on a single page when possible. */ readonly keepLines?: boolean; + /** Outline level for table of contents and document outline (0-9) */ readonly outlineLevel?: number; }; @@ -58,13 +66,20 @@ export type ILevelParagraphStylePropertiesOptions = { * border, shading, and numbering options in addition to level properties. */ export type IParagraphStylePropertiesOptions = { + /** Border settings for the paragraph */ readonly border?: IBordersOptions; + /** Background shading/fill color for the paragraph */ readonly shading?: IShadingAttributesProperties; + /** Numbering configuration for lists, or false to remove numbering */ readonly numbering?: | { + /** Reference ID of the numbering definition to use */ readonly reference: string; + /** Level in the numbering hierarchy (0-8) */ readonly level: number; + /** Instance number for multiple lists with same reference */ readonly instance?: number; + /** Whether this is a custom numbering definition */ readonly custom?: boolean; } | false; @@ -79,19 +94,32 @@ export type IParagraphStylePropertiesOptions = { * Reference: http://officeopenxml.com/WPparagraphProperties.php */ export type IParagraphPropertiesOptions = { + /** Heading level (Heading1, Heading2, etc.) - applies predefined heading style */ readonly heading?: (typeof HeadingLevel)[keyof typeof HeadingLevel]; + /** Whether to render text right-to-left for bidirectional languages */ readonly bidirectional?: boolean; + /** Whether to insert a page break before this paragraph */ readonly pageBreakBefore?: boolean; + /** Custom tab stop positions and alignments */ readonly tabStops?: readonly TabStopDefinition[]; + /** Style ID to apply to this paragraph */ readonly style?: string; + /** Bullet list configuration */ readonly bullet?: { + /** Indentation level for the bullet (0-8) */ readonly level: number; }; + /** Whether to prevent single lines at top/bottom of page (widow/orphan control) */ readonly widowControl?: boolean; + /** Frame properties for positioning the paragraph */ readonly frame?: IFrameOptions; + /** Whether to suppress line numbers for this paragraph */ readonly suppressLineNumbers?: boolean; + /** Whether to allow word wrapping */ readonly wordWrap?: boolean; + /** Whether to allow punctuation to extend beyond text margins */ readonly overflowPunctuation?: boolean; + /** Character scaling percentage (e.g., 200 for 200%) */ readonly scale?: number; /** * This element specifies whether inter-character spacing shall automatically be adjusted between regions of numbers and regions of East Asian text in the current paragraph. These regions shall be determined by the Unicode character values of the text content within the paragraph. @@ -99,6 +127,7 @@ export type IParagraphPropertiesOptions = { */ readonly autoSpaceEastAsianText?: boolean; /** + * Run properties to apply to all runs in the paragraph. * Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.3.1.29. */ readonly run?: IRunOptions; @@ -126,6 +155,87 @@ export type IParagraphPropertiesOptions = { * * * ``` + * + * The base type CT_PPrBase contains: + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Basic paragraph with alignment + * new ParagraphProperties({ + * alignment: AlignmentType.CENTER, + * }); + * + * // Formatted paragraph with spacing and indentation + * new ParagraphProperties({ + * alignment: AlignmentType.JUSTIFIED, + * spacing: { before: 200, after: 200, line: 360 }, + * indent: { left: 720, right: 720 }, + * }); + * + * // Heading with outline level + * new ParagraphProperties({ + * heading: HeadingLevel.HEADING_1, + * outlineLevel: 0, + * keepNext: true, + * }); + * + * // Numbered list item + * new ParagraphProperties({ + * numbering: { + * reference: "my-numbering", + * level: 0, + * instance: 0, + * }, + * }); + * + * // Paragraph with borders and shading + * new ParagraphProperties({ + * border: { + * top: { style: BorderStyle.SINGLE, size: 6, color: "000000" }, + * bottom: { style: BorderStyle.SINGLE, size: 6, color: "000000" }, + * }, + * shading: { fill: "EEEEEE" }, + * }); + * ``` */ export class ParagraphProperties extends IgnoreIfEmptyXmlComponent { // eslint-disable-next-line functional/prefer-readonly-type @@ -267,10 +377,24 @@ export class ParagraphProperties extends IgnoreIfEmptyXmlComponent { } } + /** + * Adds a property element to the paragraph properties. + * + * @param item - The XML component to add to the paragraph properties + */ public push(item: XmlComponent): void { this.root.push(item); } + /** + * Prepares the paragraph properties for XML serialization. + * + * This method creates concrete numbering instances for any numbering references + * before the properties are converted to XML. + * + * @param context - The XML context containing document and file information + * @returns The prepared XML object, or undefined if the component should be ignored + */ public prepForXml(context: IContext): IXmlableObject | undefined { if (context.viewWrapper instanceof DocumentWrapper) { for (const reference of this.numberingReferences) { diff --git a/src/file/paragraph/run/break.ts b/src/file/paragraph/run/break.ts index d36ef9ff64..39d78fccaf 100644 --- a/src/file/paragraph/run/break.ts +++ b/src/file/paragraph/run/break.ts @@ -1,30 +1,63 @@ -// http://officeopenxml.com/WPtextSpecialContent-break.php +/** + * Break module for WordprocessingML documents. + * + * This module provides support for line breaks within a run. A break element + * represents a line break (line feed) within text content. + * + * Reference: http://officeopenxml.com/WPtextSpecialContent-break.php + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; -// -// ... -// - -// -// -// -// - -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// +/** + * Represents a line break in a WordprocessingML document. + * + * The Break element inserts a line break (carriage return/line feed) within a run. + * This forces text to continue on the next line without starting a new paragraph. + * + * Reference: http://officeopenxml.com/WPtextSpecialContent-break.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Add line breaks in a run + * new Run({ + * children: [ + * "First line", + * new Break(), + * "Second line", + * new Break(), + * "Third line", + * ], + * }); + * ``` + */ export class Break extends XmlComponent { public constructor() { super("w:br"); diff --git a/src/file/paragraph/run/comment-run.ts b/src/file/paragraph/run/comment-run.ts index c65aaded1f..7afed86bea 100644 --- a/src/file/paragraph/run/comment-run.ts +++ b/src/file/paragraph/run/comment-run.ts @@ -1,19 +1,53 @@ +/** + * Comment module for WordprocessingML documents. + * + * This module provides support for comments (annotations) in documents. Comments + * consist of comment ranges (start/end markers), comment references, and the + * actual comment content. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { FileChild } from "@file/file-child"; import { Relationships } from "@file/relationships"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Options for creating a single comment. + * + * @property id - Unique identifier for the comment + * @property children - Content of the comment (typically paragraphs) + * @property initials - Initials of the comment author + * @property author - Name of the comment author + * @property date - Date and time the comment was created + */ export type ICommentOptions = { + /** Unique identifier for the comment */ readonly id: number; + /** Content of the comment (typically paragraphs) */ readonly children: readonly FileChild[]; + /** Initials of the comment author */ readonly initials?: string; + /** Name of the comment author */ readonly author?: string; + /** Date and time the comment was created */ readonly date?: Date; }; +/** + * Options for creating a comments container. + * + * @property children - Array of comment definitions + */ export type ICommentsOptions = { + /** Array of comment definitions */ readonly children: readonly ICommentOptions[]; }; +/** + * @internal + */ class CommentAttributes extends XmlAttributeComponent<{ readonly id: number; readonly initials?: string; @@ -23,9 +57,16 @@ class CommentAttributes extends XmlAttributeComponent<{ protected readonly xmlKeys = { id: "w:id", initials: "w:initials", author: "w:author", date: "w:date" }; } +/** + * @internal + */ class CommentRangeAttributes extends XmlAttributeComponent<{ readonly id: number }> { protected readonly xmlKeys = { id: "w:id" }; } + +/** + * @internal + */ class RootCommentsAttributes extends XmlAttributeComponent<{ readonly "xmlns:cx"?: string; readonly "xmlns:cx1"?: string; @@ -94,6 +135,26 @@ class RootCommentsAttributes extends XmlAttributeComponent<{ }; } +/** + * Represents the start of a comment range in a WordprocessingML document. + * + * Marks the beginning of a region of text that is associated with a comment. + * Must be paired with a CommentRangeEnd with the same ID. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new CommentRangeStart(0); + * ``` + */ export class CommentRangeStart extends XmlComponent { public constructor(id: number) { super("w:commentRangeStart"); @@ -102,6 +163,26 @@ export class CommentRangeStart extends XmlComponent { } } +/** + * Represents the end of a comment range in a WordprocessingML document. + * + * Marks the end of a region of text that is associated with a comment. + * Must be paired with a CommentRangeStart with the same ID. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new CommentRangeEnd(0); + * ``` + */ export class CommentRangeEnd extends XmlComponent { public constructor(id: number) { super("w:commentRangeEnd"); @@ -110,6 +191,26 @@ export class CommentRangeEnd extends XmlComponent { } } +/** + * Represents a reference to a comment in a WordprocessingML document. + * + * This element is placed within a run to create a link to a comment. + * It should be placed after the CommentRangeEnd element. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new CommentReference(0); + * ``` + */ export class CommentReference extends XmlComponent { public constructor(id: number) { super("w:commentReference"); @@ -118,6 +219,37 @@ export class CommentReference extends XmlComponent { } } +/** + * Represents a single comment in a WordprocessingML document. + * + * Contains the actual content of a comment, including author information + * and the comment text (typically paragraphs). + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Comment({ + * id: 0, + * author: "John Doe", + * initials: "JD", + * children: [new Paragraph("This is a comment")], + * }); + * ``` + */ export class Comment extends XmlComponent { public constructor({ id, initials, author, date = new Date(), children }: ICommentOptions) { super("w:comment"); @@ -136,6 +268,43 @@ export class Comment extends XmlComponent { } } } + +/** + * Represents the comments container in a WordprocessingML document. + * + * This is the root element for the comments.xml file that stores all + * comment definitions in the document. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Comments({ + * children: [ + * { + * id: 0, + * author: "John Doe", + * children: [new Paragraph("First comment")], + * }, + * { + * id: 1, + * author: "Jane Smith", + * children: [new Paragraph("Second comment")], + * }, + * ], + * }); + * ``` + */ export class Comments extends XmlComponent { private readonly relationships: Relationships; diff --git a/src/file/paragraph/run/emphasis-mark.ts b/src/file/paragraph/run/emphasis-mark.ts index 6fab5f74fb..7a3eef6873 100644 --- a/src/file/paragraph/run/emphasis-mark.ts +++ b/src/file/paragraph/run/emphasis-mark.ts @@ -1,9 +1,44 @@ +/** + * Emphasis mark module for WordprocessingML run properties. + * + * This module provides support for East Asian emphasis marks, which are + * characters placed above or below text to emphasize it. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; +/** + * Emphasis mark types. + * + * Defines the types of emphasis marks that can be applied to text. + * Emphasis marks are commonly used in East Asian typography. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + */ export const EmphasisMarkType = { + /** Dot emphasis mark */ DOT: "dot", } as const; +/** + * Base class for emphasis mark elements. + * + * @internal + */ export abstract class BaseEmphasisMark extends XmlComponent { protected constructor(emphasisMarkType: (typeof EmphasisMarkType)[keyof typeof EmphasisMarkType]) { super("w:em"); @@ -15,12 +50,46 @@ export abstract class BaseEmphasisMark extends XmlComponent { } } +/** + * Represents an emphasis mark in a WordprocessingML document. + * + * Emphasis marks are characters (typically dots or circles) placed above or below + * text to emphasize it. This is commonly used in East Asian typography. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Apply dot emphasis mark + * new EmphasisMark(EmphasisMarkType.DOT); + * + * // Default to dot + * new EmphasisMark(); + * ``` + */ export class EmphasisMark extends BaseEmphasisMark { public constructor(emphasisMarkType: (typeof EmphasisMarkType)[keyof typeof EmphasisMarkType] = EmphasisMarkType.DOT) { super(emphasisMarkType); } } +/** + * Represents a dot emphasis mark. + * + * Convenience class for applying a dot emphasis mark to text. + * + * @example + * ```typescript + * new DotEmphasisMark(); + * ``` + */ export class DotEmphasisMark extends BaseEmphasisMark { public constructor() { super(EmphasisMarkType.DOT); diff --git a/src/file/paragraph/run/empty-children.ts b/src/file/paragraph/run/empty-children.ts index b72ba255d6..fba0da00e5 100644 --- a/src/file/paragraph/run/empty-children.ts +++ b/src/file/paragraph/run/empty-children.ts @@ -1,125 +1,219 @@ +/** + * Empty children module for WordprocessingML run elements. + * + * This module provides support for various empty (self-closing) elements that can + * appear within a run. These elements represent special characters, references, + * and separators that don't require additional content. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { EmptyElement } from "@file/xml-components"; +// XSD Schema reference for EG_RunInnerContent group: // -// ... -// -// -// -// -// -// -// -// -// -// -// -// -// -// ... -// -// -// -// ... -// -// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// // +/** + * Represents a non-breaking hyphen character. + * + * Inserts a hyphen that prevents line breaking at that position. + */ export class NoBreakHyphen extends EmptyElement { public constructor() { super("w:noBreakHyphen"); } } +/** + * Represents a soft hyphen (optional hyphen) character. + * + * Inserts a hyphen that only appears when a word is broken across lines. + */ export class SoftHyphen extends EmptyElement { public constructor() { super("w:softHyphen"); } } +/** + * Represents the current day in short format (e.g., "1", "15"). + * + * Inserts a dynamic field showing the day portion of the current date. + */ export class DayShort extends EmptyElement { public constructor() { super("w:dayShort"); } } +/** + * Represents the current month in short format (e.g., "1", "12"). + * + * Inserts a dynamic field showing the month portion of the current date. + */ export class MonthShort extends EmptyElement { public constructor() { super("w:monthShort"); } } +/** + * Represents the current year in short format (e.g., "24"). + * + * Inserts a dynamic field showing the year portion of the current date in two digits. + */ export class YearShort extends EmptyElement { public constructor() { super("w:yearShort"); } } +/** + * Represents the current day in long format (e.g., "01", "15"). + * + * Inserts a dynamic field showing the day portion of the current date with leading zeros. + */ export class DayLong extends EmptyElement { public constructor() { super("w:dayLong"); } } +/** + * Represents the current month in long format (e.g., "January", "December"). + * + * Inserts a dynamic field showing the full month name of the current date. + */ export class MonthLong extends EmptyElement { public constructor() { super("w:monthLong"); } } +/** + * Represents the current year in long format (e.g., "2024"). + * + * Inserts a dynamic field showing the year portion of the current date in four digits. + */ export class YearLong extends EmptyElement { public constructor() { super("w:yearLong"); } } +/** + * Represents a reference to an annotation (comment). + * + * Used internally within comment ranges to mark comment references. + */ export class AnnotationReference extends EmptyElement { public constructor() { super("w:annotationRef"); } } +/** + * Represents a reference to a footnote. + * + * Used within footnote content to refer back to the footnote marker. + */ export class FootnoteReferenceElement extends EmptyElement { public constructor() { super("w:footnoteRef"); } } +/** + * Represents a reference to an endnote. + * + * Used within endnote content to refer back to the endnote marker. + */ export class EndnoteReference extends EmptyElement { public constructor() { super("w:endnoteRef"); } } +/** + * Represents a separator line for footnotes or endnotes. + * + * Used to create the separator line between document content and footnotes/endnotes. + */ export class Separator extends EmptyElement { public constructor() { super("w:separator"); } } +/** + * Represents a continuation separator for footnotes or endnotes. + * + * Used when footnotes/endnotes continue across multiple pages. + */ export class ContinuationSeparator extends EmptyElement { public constructor() { super("w:continuationSeparator"); } } +/** + * Represents a page number field element. + * + * Inserts the current page number at this position. + */ export class PageNumberElement extends EmptyElement { public constructor() { super("w:pgNum"); } } +/** + * Represents a carriage return character. + * + * Inserts a carriage return, which may be rendered differently than a standard line break. + */ export class CarriageReturn extends EmptyElement { public constructor() { super("w:cr"); } } +/** + * Represents a tab character. + * + * Inserts a tab stop, advancing to the next tab position in the paragraph. + */ export class Tab extends EmptyElement { public constructor() { super("w:tab"); } } +/** + * Represents the last rendered page break location. + * + * Used internally by Word to track where page breaks occurred in the last rendering. + * This is typically generated by Word and not created manually. + */ export class LastRenderedPageBreak extends EmptyElement { public constructor() { super("w:lastRenderedPageBreak"); diff --git a/src/file/paragraph/run/field.ts b/src/file/paragraph/run/field.ts index 959d598636..e13d620d7a 100644 --- a/src/file/paragraph/run/field.ts +++ b/src/file/paragraph/run/field.ts @@ -1,11 +1,30 @@ +/** + * Field module for WordprocessingML documents. + * + * This module provides support for complex fields, which are regions of text + * that can contain dynamic content such as page numbers, dates, or mail merge fields. + * Fields are delimited by field character elements (begin, separate, end). + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Field character types that delimit field regions. + * + * @internal + */ const FieldCharacterType = { BEGIN: "begin", END: "end", SEPARATE: "separate", } as const; +/** + * @internal + */ class FidCharAttrs extends XmlAttributeComponent<{ readonly type: (typeof FieldCharacterType)[keyof typeof FieldCharacterType]; readonly dirty?: boolean; @@ -13,6 +32,34 @@ class FidCharAttrs extends XmlAttributeComponent<{ protected readonly xmlKeys = { type: "w:fldCharType", dirty: "w:dirty" }; } +/** + * Represents the beginning of a complex field in a WordprocessingML document. + * + * The Begin element marks the start of a field. A field consists of a begin character, + * field instructions, an optional separate character, field result, and an end character. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally by field implementations + * new Begin(); + * ``` + */ export class Begin extends XmlComponent { public constructor(dirty?: boolean) { super("w:fldChar"); @@ -20,6 +67,28 @@ export class Begin extends XmlComponent { } } +/** + * Represents the separator between field code and field result in a complex field. + * + * The Separate element divides the field code (instructions) from the field result + * (the computed value). It appears between the field code and the field result. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally by field implementations + * new Separate(); + * ``` + */ export class Separate extends XmlComponent { public constructor(dirty?: boolean) { super("w:fldChar"); @@ -27,6 +96,28 @@ export class Separate extends XmlComponent { } } +/** + * Represents the end of a complex field in a WordprocessingML document. + * + * The End element marks the end of a field. Every field that begins with a Begin + * element must be terminated with an End element. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally by field implementations + * new End(); + * ``` + */ export class End extends XmlComponent { public constructor(dirty?: boolean) { super("w:fldChar"); diff --git a/src/file/paragraph/run/formatting.ts b/src/file/paragraph/run/formatting.ts index 50c14ac568..7ad688b18a 100644 --- a/src/file/paragraph/run/formatting.ts +++ b/src/file/paragraph/run/formatting.ts @@ -1,6 +1,36 @@ +/** + * Run formatting module for WordprocessingML documents. + * + * This module provides character-level formatting elements including + * spacing, color, and highlighting. + * + * Reference: http://officeopenxml.com/WPtextFormatting.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; import { UniversalMeasure, hexColorValue, signedTwipsMeasureValue } from "@util/values"; +/** + * Represents character spacing (tracking) in a run. + * + * Adjusts the space between characters in the text. + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new CharacterSpacing(20); // 20 twips (1 point) + * new CharacterSpacing("0.5pt"); // Half point + * ``` + * + * @internal + */ export class CharacterSpacing extends XmlComponent { public constructor(value: number | UniversalMeasure) { super("w:spacing"); @@ -12,12 +42,27 @@ export class CharacterSpacing extends XmlComponent { } } -// -// -// -// -// -// +/** + * Represents text color in a run. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Color("FF0000"); // Red text + * new Color("auto"); // Automatic color + * ``` + * + * @internal + */ export class Color extends XmlComponent { public constructor(color: string) { super("w:color"); @@ -29,27 +74,42 @@ export class Color extends XmlComponent { } } -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// +/** + * Represents text highlighting in a run. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new Highlight("yellow"); // Yellow highlight + * new Highlight("cyan"); // Cyan highlight + * ``` + * + * @internal + */ export class Highlight extends XmlComponent { public constructor(color: string) { super("w:highlight"); @@ -61,6 +121,14 @@ export class Highlight extends XmlComponent { } } +/** + * Represents text highlighting for complex scripts. + * + * Used for highlighting text in complex script languages + * (e.g., Arabic, Hebrew, Thai). + * + * @internal + */ export class HighlightComplexScript extends XmlComponent { public constructor(color: string) { super("w:highlightCs"); diff --git a/src/file/paragraph/run/index.ts b/src/file/paragraph/run/index.ts index f459256c59..8762125cdb 100644 --- a/src/file/paragraph/run/index.ts +++ b/src/file/paragraph/run/index.ts @@ -1,3 +1,8 @@ +/** + * Run module exports. + * + * @module + */ export * from "./run"; export * from "./properties"; export * from "./text-run"; diff --git a/src/file/paragraph/run/language.ts b/src/file/paragraph/run/language.ts index 4b9088ac28..72ee6fb65d 100644 --- a/src/file/paragraph/run/language.ts +++ b/src/file/paragraph/run/language.ts @@ -1,16 +1,67 @@ +/** + * Language module for WordprocessingML run properties. + * + * This module provides support for specifying the language of text content, + * which affects spell checking, grammar checking, and hyphenation. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; -// -// -// -// -// +/** + * Options for language settings. + * + * Specifies the language for different text types within a run. + * Language codes should follow RFC 1766 (e.g., "en-US", "fr-FR", "ja-JP"). + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @property value - Language for Latin and complex script text (e.g., "en-US") + * @property eastAsia - Language for East Asian text (e.g., "ja-JP", "zh-CN") + * @property bidirectional - Language for bidirectional text (e.g., "ar-SA", "he-IL") + */ export type ILanguageOptions = { + /** Language for Latin and complex script text (RFC 1766 format, e.g., "en-US") */ readonly value?: string; + /** Language for East Asian text (RFC 1766 format, e.g., "ja-JP") */ readonly eastAsia?: string; + /** Language for bidirectional text (RFC 1766 format, e.g., "ar-SA") */ readonly bidirectional?: string; }; +/** + * Creates a language component for run properties. + * + * This function creates a language element that specifies the language for text content. + * The language setting affects spell checking, grammar checking, and hyphenation. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @param options - Language options for different text types + * @returns XmlComponent representing the language element + * + * @example + * ```typescript + * // Set language for English (US) + * createLanguageComponent({ value: "en-US" }); + * + * // Set different languages for different scripts + * createLanguageComponent({ + * value: "en-US", + * eastAsia: "ja-JP", + * bidirectional: "ar-SA", + * }); + * ``` + */ export const createLanguageComponent = (options: ILanguageOptions): XmlComponent => new BuilderElement<{ readonly value?: string; diff --git a/src/file/paragraph/run/page-number.ts b/src/file/paragraph/run/page-number.ts index 2789b23995..9770c7bc3a 100644 --- a/src/file/paragraph/run/page-number.ts +++ b/src/file/paragraph/run/page-number.ts @@ -1,8 +1,30 @@ +/** + * Page number field instruction module for WordprocessingML documents. + * + * This module provides field instruction elements for displaying + * page numbers, page counts, and section information. + * + * Reference: http://officeopenxml.com/WPfields.php + * + * @module + */ import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; import { TextAttributes } from "./text-attributes"; +/** + * Represents a PAGE field instruction. + * + * Displays the current page number in the document. + * + * @example + * ```typescript + * new Run({ children: [new Begin(true), new Page(), new End()] }); + * ``` + * + * @internal + */ export class Page extends XmlComponent { public constructor() { super("w:instrText"); @@ -11,6 +33,13 @@ export class Page extends XmlComponent { } } +/** + * Represents a NUMPAGES field instruction. + * + * Displays the total number of pages in the document. + * + * @internal + */ export class NumberOfPages extends XmlComponent { public constructor() { super("w:instrText"); @@ -19,6 +48,13 @@ export class NumberOfPages extends XmlComponent { } } +/** + * Represents a SECTIONPAGES field instruction. + * + * Displays the total number of pages in the current section. + * + * @internal + */ export class NumberOfPagesSection extends XmlComponent { public constructor() { super("w:instrText"); @@ -27,6 +63,13 @@ export class NumberOfPagesSection extends XmlComponent { } } +/** + * Represents a SECTION field instruction. + * + * Displays the current section number. + * + * @internal + */ export class CurrentSection extends XmlComponent { public constructor() { super("w:instrText"); diff --git a/src/file/paragraph/run/positional-tab.ts b/src/file/paragraph/run/positional-tab.ts index bb8c6fc217..c2b2875664 100644 --- a/src/file/paragraph/run/positional-tab.ts +++ b/src/file/paragraph/run/positional-tab.ts @@ -1,57 +1,137 @@ +/** + * Positional tab module for WordprocessingML documents. + * + * This module provides support for positional tabs, which are absolute position + * tab stops used primarily in paragraphs with bidirectional text. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; -// -// -// -// -// -// -// +/** + * Positional tab alignment types. + * + * Specifies how text is aligned at the positional tab stop. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export const PositionalTabAlignment = { + /** Left-aligned tab */ LEFT: "left", + /** Center-aligned tab */ CENTER: "center", + /** Right-aligned tab */ RIGHT: "right", } as const; -// -// -// -// -// -// +/** + * Positional tab relative positioning types. + * + * Specifies what the positional tab position is relative to. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const PositionalTabRelativeTo = { + /** Position relative to margin */ MARGIN: "margin", + /** Position relative to indent */ INDENT: "indent", } as const; -// -// -// -// -// -// -// -// -// +/** + * Positional tab leader character types. + * + * Specifies the character used to fill the space before the tab. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + */ export const PositionalTabLeader = { + /** No leader character */ NONE: "none", + /** Dot leader (...) */ DOT: "dot", + /** Hyphen leader (---) */ HYPHEN: "hyphen", + /** Underscore leader (___) */ UNDERSCORE: "underscore", + /** Middle dot leader (···) */ MIDDLE_DOT: "middleDot", } as const; +/** + * Options for creating a PositionalTab. + * + * @property alignment - How text is aligned at the tab stop + * @property relativeTo - What the tab position is relative to + * @property leader - Character used to fill space before the tab + */ export type PositionalTabOptions = { + /** How text is aligned at the tab stop */ readonly alignment: (typeof PositionalTabAlignment)[keyof typeof PositionalTabAlignment]; + /** What the tab position is relative to */ readonly relativeTo: (typeof PositionalTabRelativeTo)[keyof typeof PositionalTabRelativeTo]; + /** Character used to fill space before the tab */ readonly leader: (typeof PositionalTabLeader)[keyof typeof PositionalTabLeader]; }; -// -// -// -// -// +/** + * Represents a positional tab in a WordprocessingML document. + * + * A positional tab is an absolute position tab stop that is typically used + * in bidirectional text scenarios. Unlike normal tabs, positional tabs specify + * an exact alignment and position within the paragraph. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a centered positional tab + * new PositionalTab({ + * alignment: PositionalTabAlignment.CENTER, + * relativeTo: PositionalTabRelativeTo.MARGIN, + * leader: PositionalTabLeader.DOT, + * }); + * ``` + */ export class PositionalTab extends XmlComponent { public constructor(options: PositionalTabOptions) { super("w:ptab"); diff --git a/src/file/paragraph/run/run-fonts.ts b/src/file/paragraph/run/run-fonts.ts index d6a184c934..4c1d5e9da2 100644 --- a/src/file/paragraph/run/run-fonts.ts +++ b/src/file/paragraph/run/run-fonts.ts @@ -1,13 +1,41 @@ +/** + * Run fonts module for WordprocessingML documents. + * + * This module provides support for specifying fonts for different character sets + * within a run. Fonts can be specified separately for ASCII, complex script (CS), + * East Asian, and high ANSI character ranges. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Options for font attributes across different character sets. + * + * @property ascii - Font for ASCII characters (0x00-0x7F) + * @property cs - Font for complex script characters + * @property eastAsia - Font for East Asian characters + * @property hAnsi - Font for high ANSI characters (0x80-0xFF) + * @property hint - Hint for font selection algorithm + */ export type IFontAttributesProperties = { + /** Font for ASCII characters (0x00-0x7F) */ readonly ascii?: string; + /** Font for complex script characters */ readonly cs?: string; + /** Font for East Asian characters */ readonly eastAsia?: string; + /** Font for high ANSI characters (0x80-0xFF) */ readonly hAnsi?: string; + /** Hint for font selection algorithm */ readonly hint?: string; }; +/** + * @internal + */ class RunFontAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { ascii: "w:ascii", @@ -18,6 +46,44 @@ class RunFontAttributes extends XmlAttributeComponent }; } +/** + * Represents font settings for a run in a WordprocessingML document. + * + * The RunFonts element specifies which fonts should be used for different character + * ranges in a run. This allows documents to use different fonts for ASCII, complex + * script, East Asian, and high ANSI characters. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Use same font for all character sets + * new RunFonts("Arial"); + * + * // Specify different fonts for different character sets + * new RunFonts({ + * ascii: "Arial", + * eastAsia: "MS Mincho", + * cs: "Arial", + * hAnsi: "Arial", + * }); + * ``` + */ export class RunFonts extends XmlComponent { public constructor(name: string, hint?: string); public constructor(attrs: string | IFontAttributesProperties); diff --git a/src/file/paragraph/run/script.ts b/src/file/paragraph/run/script.ts index 66840882bc..c6497fe163 100644 --- a/src/file/paragraph/run/script.ts +++ b/src/file/paragraph/run/script.ts @@ -1,5 +1,34 @@ +/** + * Subscript and superscript module for WordprocessingML documents. + * + * This module provides vertical alignment elements for subscript + * and superscript text formatting. + * + * Reference: http://officeopenxml.com/WPtextFormatting.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; +/** + * Abstract base class for vertical text alignment. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @internal + */ export abstract class VerticalAlign extends XmlComponent { public constructor(type: string) { super("w:vertAlign"); @@ -11,12 +40,40 @@ export abstract class VerticalAlign extends XmlComponent { } } +/** + * Represents superscript text formatting. + * + * Raises text above the baseline, commonly used for exponents + * and ordinal indicators. + * + * @example + * ```typescript + * // In run properties for superscript text + * new SuperScript(); + * ``` + * + * @internal + */ export class SuperScript extends VerticalAlign { public constructor() { super("superscript"); } } +/** + * Represents subscript text formatting. + * + * Lowers text below the baseline, commonly used for chemical + * formulas and footnote references. + * + * @example + * ```typescript + * // In run properties for subscript text + * new SubScript(); + * ``` + * + * @internal + */ export class SubScript extends VerticalAlign { public constructor() { super("subscript"); diff --git a/src/file/paragraph/run/sequential-identifier-instruction.ts b/src/file/paragraph/run/sequential-identifier-instruction.ts index 4de568aebc..2fe6ce88f6 100644 --- a/src/file/paragraph/run/sequential-identifier-instruction.ts +++ b/src/file/paragraph/run/sequential-identifier-instruction.ts @@ -1,9 +1,35 @@ -// http://officeopenxml.com/WPfieldInstructions.php +/** + * Sequential identifier instruction module for WordprocessingML documents. + * + * This module provides the SEQ field instruction for creating + * auto-numbered sequences like figure numbers, table numbers, etc. + * + * Reference: http://officeopenxml.com/WPfieldInstructions.php + * + * @module + */ import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; import { TextAttributes } from "./text-attributes"; +/** + * Represents a SEQ field instruction. + * + * The SEQ field inserts an automatically incrementing sequence number, + * useful for numbering figures, tables, equations, or custom sequences. + * + * @example + * ```typescript + * // Create a figure number sequence + * new SequentialIdentifierInstruction("Figure"); + * + * // Create a table number sequence + * new SequentialIdentifierInstruction("Table"); + * ``` + * + * @internal + */ export class SequentialIdentifierInstruction extends XmlComponent { public constructor(identifier: string) { super("w:instrText"); diff --git a/src/file/paragraph/run/sequential-identifier.ts b/src/file/paragraph/run/sequential-identifier.ts index 4dc9c98ef8..9f9ba7bff8 100644 --- a/src/file/paragraph/run/sequential-identifier.ts +++ b/src/file/paragraph/run/sequential-identifier.ts @@ -1,8 +1,48 @@ +/** + * Sequential identifier module for WordprocessingML documents. + * + * This module provides support for SEQ (sequence) fields, which are used to + * automatically number items in a document such as figures, tables, and equations. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { Run } from "@file/paragraph/run"; import { Begin, End, Separate } from "@file/paragraph/run/field"; import { SequentialIdentifierInstruction } from "./sequential-identifier-instruction"; +/** + * Represents a sequential identifier field in a WordprocessingML document. + * + * SequentialIdentifier creates a SEQ field that automatically numbers items in a document. + * Each identifier maintains its own sequence, allowing you to have separate numbering + * for figures, tables, equations, etc. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a figure number + * new SequentialIdentifier("Figure"); + * + * // Create a table number + * new SequentialIdentifier("Table"); + * + * // Create an equation number + * new SequentialIdentifier("Equation"); + * ``` + */ export class SequentialIdentifier extends Run { public constructor(identifier: string) { super({}); diff --git a/src/file/paragraph/run/simple-field.ts b/src/file/paragraph/run/simple-field.ts index 1a4e7a9b60..ee11732ee4 100644 --- a/src/file/paragraph/run/simple-field.ts +++ b/src/file/paragraph/run/simple-field.ts @@ -1,12 +1,55 @@ -// http://www.datypic.com/sc/ooxml/e-w_fldSimple-1.html +/** + * Simple field module for WordprocessingML documents. + * + * This module provides support for simple fields, which are self-contained field + * elements that include both the field code and optional cached result in a single element. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_fldSimple-1.html + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { TextRun } from "./text-run"; +/** + * @internal + */ class FldSimpleAttrs extends XmlAttributeComponent<{ readonly instr: string }> { protected readonly xmlKeys = { instr: "w:instr" }; } +/** + * Represents a simple field in a WordprocessingML document. + * + * A simple field (fldSimple) contains both the field code and the optional cached value + * in a single element, unlike complex fields which use separate begin/end markers. + * Simple fields are typically used for fields that don't require complex nesting. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_fldSimple-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Simple field with instruction + * new SimpleField("DATE"); + * + * // Simple field with cached value + * new SimpleField("DATE", "2024-01-01"); + * ``` + */ export class SimpleField extends XmlComponent { public constructor(instruction: string, cachedValue?: string) { super("w:fldSimple"); @@ -17,6 +60,21 @@ export class SimpleField extends XmlComponent { } } +/** + * Represents a mail merge field in a WordprocessingML document. + * + * SimpleMailMergeField is a specialized simple field for mail merge operations. + * It creates a MERGEFIELD that will be populated with data during mail merge. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @example + * ```typescript + * // Creates a merge field for "FirstName" + * new SimpleMailMergeField("FirstName"); + * // Renders as: MERGEFIELD FirstName with placeholder «FirstName» + * ``` + */ export class SimpleMailMergeField extends SimpleField { public constructor(fieldName: string) { super(` MERGEFIELD ${fieldName} `, `«${fieldName}»`); diff --git a/src/file/paragraph/run/text-attributes.ts b/src/file/paragraph/run/text-attributes.ts index 42b87753f9..9a0dc22dc1 100644 --- a/src/file/paragraph/run/text-attributes.ts +++ b/src/file/paragraph/run/text-attributes.ts @@ -1,6 +1,27 @@ +/** + * Text attributes module for WordprocessingML documents. + * + * This module provides XML attributes for text elements, + * particularly the xml:space attribute for whitespace handling. + * + * @module + */ import { SpaceType } from "@file/shared"; import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Represents text element attributes. + * + * Used to set the xml:space attribute which controls + * whitespace preservation in text content. + * + * @example + * ```typescript + * new TextAttributes({ space: SpaceType.PRESERVE }); + * ``` + * + * @internal + */ export class TextAttributes extends XmlAttributeComponent<{ readonly space: (typeof SpaceType)[keyof typeof SpaceType]; }> { diff --git a/src/file/paragraph/run/underline.ts b/src/file/paragraph/run/underline.ts index 59379bf928..4680adce7a 100644 --- a/src/file/paragraph/run/underline.ts +++ b/src/file/paragraph/run/underline.ts @@ -1,27 +1,118 @@ +/** + * Underline module for WordprocessingML documents. + * + * This module provides support for underlining text with various styles and colors. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * @module + */ import { Attributes, XmlComponent } from "@file/xml-components"; import { hexColorValue } from "@util/values"; +/** + * Underline style types for text. + * + * Defines the various underline patterns that can be applied to text runs. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + */ export const UnderlineType = { + /** Single underline */ SINGLE: "single", + /** Underline words only (not spaces) */ WORDS: "words", + /** Double underline */ DOUBLE: "double", + /** Thick single underline */ THICK: "thick", + /** Dotted underline */ DOTTED: "dotted", + /** Heavy dotted underline */ DOTTEDHEAVY: "dottedHeavy", + /** Dashed underline */ DASH: "dash", + /** Heavy dashed underline */ DASHEDHEAVY: "dashedHeavy", + /** Long dashed underline */ DASHLONG: "dashLong", + /** Heavy long dashed underline */ DASHLONGHEAVY: "dashLongHeavy", + /** Dot-dash underline */ DOTDASH: "dotDash", + /** Heavy dot-dash underline */ DASHDOTHEAVY: "dashDotHeavy", + /** Dot-dot-dash underline */ DOTDOTDASH: "dotDotDash", + /** Heavy dot-dot-dash underline */ DASHDOTDOTHEAVY: "dashDotDotHeavy", + /** Wave underline */ WAVE: "wave", + /** Heavy wave underline */ WAVYHEAVY: "wavyHeavy", + /** Double wave underline */ WAVYDOUBLE: "wavyDouble", + /** No underline */ NONE: "none", } as const; +/** + * Represents underline formatting for a run in a WordprocessingML document. + * + * The Underline element specifies the style and optional color of underline + * formatting applied to text. + * + * Reference: http://officeopenxml.com/WPrun.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Simple single underline + * new Underline(); + * + * // Double underline + * new Underline(UnderlineType.DOUBLE); + * + * // Red wavy underline + * new Underline(UnderlineType.WAVE, "FF0000"); + * ``` + */ export class Underline extends XmlComponent { public constructor(underlineType: (typeof UnderlineType)[keyof typeof UnderlineType] = UnderlineType.SINGLE, color?: string) { super("w:u"); diff --git a/src/file/relationships/attributes.ts b/src/file/relationships/attributes.ts index fbf13a8ef8..6f133731e4 100644 --- a/src/file/relationships/attributes.ts +++ b/src/file/relationships/attributes.ts @@ -1,6 +1,19 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for the Relationships element. + * + * Defines the XML namespace for the relationships part. + * + * @example + * ```typescript + * new RelationshipsAttributes({ + * xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" + * }); + * ``` + */ export class RelationshipsAttributes extends XmlAttributeComponent<{ + /** XML namespace for relationships */ readonly xmlns: string; }> { protected readonly xmlKeys = { diff --git a/src/file/relationships/index.ts b/src/file/relationships/index.ts index 8233ccd5d7..1d1b86202b 100644 --- a/src/file/relationships/index.ts +++ b/src/file/relationships/index.ts @@ -1 +1,6 @@ +/** + * Relationships module exports. + * + * @module + */ export * from "./relationships"; diff --git a/src/file/relationships/relationship/relationship-attributes.ts b/src/file/relationships/relationship/relationship-attributes.ts index c2d0daaf44..06d8cc7235 100644 --- a/src/file/relationships/relationship/relationship-attributes.ts +++ b/src/file/relationships/relationship/relationship-attributes.ts @@ -1,9 +1,27 @@ import { XmlAttributeComponent } from "@file/xml-components"; +/** + * Attributes for a Relationship element. + * + * Defines the properties of a single relationship between package parts. + * + * @example + * ```typescript + * new RelationshipAttributes({ + * id: "rId1", + * type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + * target: "media/image1.png" + * }); + * ``` + */ export class RelationshipAttributes extends XmlAttributeComponent<{ + /** Unique identifier for this relationship (e.g., "rId1") */ readonly id: string; + /** Relationship type URI defining the kind of relationship */ readonly type: string; + /** Path to the target part or URI for external targets */ readonly target: string; + /** Optional mode indicating if target is external to the package */ readonly targetMode?: string; }> { protected readonly xmlKeys = { diff --git a/src/file/relationships/relationship/relationship.ts b/src/file/relationships/relationship/relationship.ts index 8cfa46f142..1678edfb2c 100644 --- a/src/file/relationships/relationship/relationship.ts +++ b/src/file/relationships/relationship/relationship.ts @@ -2,6 +2,12 @@ import { XmlComponent } from "@file/xml-components"; import { RelationshipAttributes } from "./relationship-attributes"; +/** + * Supported relationship type URIs. + * + * These URIs define the type of relationship between parts in an OPC package. + * Each type corresponds to a specific kind of document component or resource. + */ export type RelationshipType = | "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" | "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" @@ -21,10 +27,31 @@ export type RelationshipType = | "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" | "http://schemas.openxmlformats.org/officeDocument/2006/relationships/font"; +/** + * Target mode types for relationships. + * + * Indicates whether a relationship target is external to the package. + */ export const TargetModeType = { + /** Target is external to the package (e.g., hyperlink to a URL) */ EXTERNAL: "External", } as const; +/** + * Represents a single relationship between parts in an OPC package. + * + * A relationship defines a typed connection from a source part to a target part, + * identified by a unique ID within the relationships collection. + * + * @example + * ```typescript + * // Internal relationship to an image + * new Relationship("rId1", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "media/image1.png"); + * + * // External relationship to a hyperlink + * new Relationship("rId2", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "https://example.com", TargetModeType.EXTERNAL); + * ``` + */ export class Relationship extends XmlComponent { public constructor( id: string, diff --git a/src/file/relationships/relationships.ts b/src/file/relationships/relationships.ts index c28a000bb6..51a1bcfab2 100644 --- a/src/file/relationships/relationships.ts +++ b/src/file/relationships/relationships.ts @@ -20,6 +20,16 @@ import { Relationship, RelationshipType, TargetModeType } from "./relationship/r * linking the main document to its headers, footers, images, etc. * * Reference: http://officeopenxml.com/anatomyofOOXML.php + * + * @example + * ```typescript + * const relationships = new Relationships(); + * relationships.createRelationship( + * 1, + * "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + * "media/image1.png" + * ); + * ``` */ export class Relationships extends XmlComponent { public constructor() { @@ -31,6 +41,15 @@ export class Relationships extends XmlComponent { ); } + /** + * Creates a new relationship to another part in the package. + * + * @param id - Unique identifier for this relationship (will be prefixed with "rId") + * @param type - Relationship type URI (e.g., image, header, hyperlink) + * @param target - Path to the target part + * @param targetMode - Optional mode indicating if target is external + * @returns The created Relationship instance + */ public createRelationship( id: number | string, type: RelationshipType, @@ -43,6 +62,10 @@ export class Relationships extends XmlComponent { return relationship; } + /** + * Gets the count of relationships in this collection. + * Excludes the attributes element from the count. + */ public get RelationshipCount(): number { return this.root.length - 1; } diff --git a/src/file/settings/compatibility-setting/compatibility-setting.ts b/src/file/settings/compatibility-setting/compatibility-setting.ts index b75a494a47..55dbeb5997 100644 --- a/src/file/settings/compatibility-setting/compatibility-setting.ts +++ b/src/file/settings/compatibility-setting/compatibility-setting.ts @@ -1,3 +1,13 @@ +/** + * Compatibility setting module for WordprocessingML documents. + * + * This module provides the compatibility mode version setting that controls + * which Word version's behavior the document should emulate. + * + * Reference: https://docs.microsoft.com/en-us/openspecs/office_standards/ms-docx/90138c4d-eb18-4edc-aa6c-dfb799cb1d0d + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; // Currently, this is hard-coded for Microsoft word compatSettings. @@ -10,6 +20,14 @@ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; // // +/** + * Attributes for the compatibility setting element. + * + * Defines the name, URI, and value for a compatibility setting. + * For Microsoft Word, this is typically used to set the compatibility mode version. + * + * @internal + */ export class CompatibilitySettingAttributes extends XmlAttributeComponent<{ readonly version: number; readonly name: string; @@ -22,8 +40,38 @@ export class CompatibilitySettingAttributes extends XmlAttributeComponent<{ }; } -// https://docs.microsoft.com/en-us/openspecs/office_standards/ms-docx/90138c4d-eb18-4edc-aa6c-dfb799cb1d0d - +/** + * Represents a single compatibility setting in a WordprocessingML document. + * + * Currently hard-coded to set Microsoft Word compatibility mode version. + * This controls which Word version's formatting and layout behavior the document emulates. + * + * Common version values: + * - 11: Word 2003 + * - 12: Word 2007 + * - 14: Word 2010 + * - 15: Word 2013+ + * + * Reference: https://docs.microsoft.com/en-us/openspecs/office_standards/ms-docx/90138c4d-eb18-4edc-aa6c-dfb799cb1d0d + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Set compatibility mode to Word 2013+ + * new CompatibilitySetting(15); + * + * // Set compatibility mode to Word 2010 + * new CompatibilitySetting(14); + * ``` + */ export class CompatibilitySetting extends XmlComponent { public constructor(version: number) { super("w:compatSetting"); diff --git a/src/file/settings/compatibility.ts b/src/file/settings/compatibility.ts index fdda107967..e87e8f083f 100644 --- a/src/file/settings/compatibility.ts +++ b/src/file/settings/compatibility.ts @@ -1,4 +1,13 @@ -// http://www.datypic.com/sc/ooxml/e-w_compat-1.html +/** + * Compatibility module for WordprocessingML documents. + * + * This module provides compatibility settings that control how Word + * handles documents created in older versions or other word processors. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_compat-1.html + * + * @module + */ import { OnOffElement, XmlComponent } from "@file/xml-components"; import { CompatibilitySetting } from "./compatibility-setting/compatibility-setting"; @@ -75,7 +84,16 @@ import { CompatibilitySetting } from "./compatibility-setting/compatibility-sett // // +/** + * Options for configuring document compatibility settings. + * + * These settings control how Word processes and displays documents to match + * behavior from older Word versions or other word processors like WordPerfect. + * + * @see {@link Compatibility} + */ export type ICompatibilityOptions = { + /** Word compatibility mode version (e.g., 15 for Word 2013+) */ readonly version?: number; /** Use Simplified Rules For Table Border Conflicts */ readonly useSingleBorderforContiguousCells?: boolean; @@ -209,6 +227,45 @@ export type ICompatibilityOptions = { readonly cachedColumnBalance?: boolean; }; +/** + * Represents compatibility settings in a WordprocessingML document. + * + * Compatibility settings control document rendering and layout behavior + * to match older Word versions or other word processors. This ensures + * documents maintain consistent appearance across different applications. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_compat-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Set compatibility mode to Word 2013+ + * new Compatibility({ + * version: 15, + * }); + * + * // Enable specific compatibility options + * new Compatibility({ + * version: 15, + * usePrinterMetrics: true, + * doNotSnapToGridInCell: true, + * }); + * ``` + */ export class Compatibility extends XmlComponent { public constructor(options: ICompatibilityOptions) { super("w:compat"); diff --git a/src/file/settings/index.ts b/src/file/settings/index.ts index dcf101b0c6..39d0cf83d1 100644 --- a/src/file/settings/index.ts +++ b/src/file/settings/index.ts @@ -1 +1,6 @@ +/** + * Settings module exports. + * + * @module + */ export * from "./settings"; diff --git a/src/file/settings/settings.ts b/src/file/settings/settings.ts index ccf12d0201..35e5c001f2 100644 --- a/src/file/settings/settings.ts +++ b/src/file/settings/settings.ts @@ -14,6 +14,11 @@ import { Compatibility, ICompatibilityOptions } from "./compatibility"; /** * Attributes for the settings element with XML namespace declarations. + * + * Defines the XML namespaces required for the settings.xml document part. + * These namespaces enable compatibility features, markup compatibility, + * and various Office-specific extensions. + * * @internal */ export class SettingsAttributes extends XmlAttributeComponent<{ @@ -205,6 +210,44 @@ export type IHyphenationOptions = { * compatibility mode, track changes, hyphenation, and more. * * Reference: http://officeopenxml.com/WPsettings.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Basic settings with track changes enabled + * new Settings({ + * trackRevisions: true, + * evenAndOddHeaders: true, + * }); + * + * // Settings with compatibility mode and hyphenation + * new Settings({ + * compatibility: { + * version: 15, // Word 2013+ + * }, + * hyphenation: { + * autoHyphenation: true, + * consecutiveHyphenLimit: 2, + * }, + * }); + * ``` */ export class Settings extends XmlComponent { public constructor(options: ISettingsOptions) { diff --git a/src/file/shading/index.ts b/src/file/shading/index.ts index 05d9d8d841..ca75a690dd 100644 --- a/src/file/shading/index.ts +++ b/src/file/shading/index.ts @@ -1 +1,6 @@ +/** + * Shading module exports. + * + * @module + */ export * from "./shading"; diff --git a/src/file/shared/index.ts b/src/file/shared/index.ts index 7edbd8d752..0e7bd327de 100644 --- a/src/file/shared/index.ts +++ b/src/file/shared/index.ts @@ -1,3 +1,8 @@ +/** + * Shared module exports. + * + * @module + */ export * from "./alignment"; export * from "./number-format"; export * from "./space-type"; diff --git a/src/file/shared/number-format.ts b/src/file/shared/number-format.ts index 06adfbb827..8bbf54cf4f 100644 --- a/src/file/shared/number-format.ts +++ b/src/file/shared/number-format.ts @@ -1,71 +1,46 @@ -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// +/** + * Number format module for WordprocessingML documents. + * + * This module provides number format constants for page numbers, + * list numbering, and other numbered elements. + * + * Reference: http://officeopenxml.com/WPnumbering-numFmt.php + * + * @module + */ +/** + * Number format types for page numbers and list numbering. + * + * Provides international number formats including decimal, Roman numerals, + * alphabetic, and various Asian numbering systems. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Arabic numerals (1, 2, 3) + * NumberFormat.DECIMAL; + * + * // Roman numerals (I, II, III) + * NumberFormat.UPPER_ROMAN; + * + * // Letters (a, b, c) + * NumberFormat.LOWER_LETTER; + * ``` + */ export const NumberFormat = { DECIMAL: "decimal", UPPER_ROMAN: "upperRoman", diff --git a/src/file/shared/space-type.ts b/src/file/shared/space-type.ts index 77062e39c8..03043cbc73 100644 --- a/src/file/shared/space-type.ts +++ b/src/file/shared/space-type.ts @@ -1,3 +1,26 @@ +/** + * Space type module for WordprocessingML documents. + * + * This module provides the xml:space attribute values for + * controlling whitespace handling in text elements. + * + * @module + */ + +/** + * XML space handling modes. + * + * Controls how whitespace is handled in text elements. + * + * @example + * ```typescript + * // Preserve whitespace (spaces, newlines) + * SpaceType.PRESERVE; + * + * // Default whitespace handling + * SpaceType.DEFAULT; + * ``` + */ export const SpaceType = { DEFAULT: "default", PRESERVE: "preserve", diff --git a/src/file/styles/defaults/document-defaults.ts b/src/file/styles/defaults/document-defaults.ts index fe1b9aa5fb..d48face08a 100644 --- a/src/file/styles/defaults/document-defaults.ts +++ b/src/file/styles/defaults/document-defaults.ts @@ -1,3 +1,10 @@ +/** + * Document defaults module for WordprocessingML styles. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { IParagraphStylePropertiesOptions } from "@file/paragraph/properties"; import { IRunStylePropertiesOptions } from "@file/paragraph/run/properties"; import { XmlComponent } from "@file/xml-components"; @@ -5,11 +12,51 @@ import { XmlComponent } from "@file/xml-components"; import { ParagraphPropertiesDefaults } from "./paragraph-properties"; import { RunPropertiesDefaults } from "./run-properties"; +/** + * Options for configuring document-wide default formatting. + * + * @property paragraph - Default paragraph properties applied to all paragraphs + * @property run - Default run properties applied to all text runs + */ export type IDocumentDefaultsOptions = { + /** Default paragraph properties applied to all paragraphs */ readonly paragraph?: IParagraphStylePropertiesOptions; + /** Default run properties applied to all text runs */ readonly run?: IRunStylePropertiesOptions; }; +/** + * Represents document-wide default formatting in a WordprocessingML document. + * + * Document defaults define the base formatting properties that apply to all + * paragraphs and runs in a document unless overridden by a style or direct formatting. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Set default font and spacing for the document + * new DocumentDefaults({ + * run: { + * font: "Calibri", + * size: 22 + * }, + * paragraph: { + * spacing: { after: 200, line: 276 } + * } + * }); + * ``` + */ export class DocumentDefaults extends XmlComponent { private readonly runPropertiesDefaults: RunPropertiesDefaults; private readonly paragraphPropertiesDefaults: ParagraphPropertiesDefaults; diff --git a/src/file/styles/defaults/index.ts b/src/file/styles/defaults/index.ts index 986aa6194d..6216b446d1 100644 --- a/src/file/styles/defaults/index.ts +++ b/src/file/styles/defaults/index.ts @@ -1,3 +1,10 @@ +/** + * Document defaults module for WordprocessingML styles. + * + * Exports components for defining document-wide default formatting properties. + * + * @module + */ export * from "./paragraph-properties"; export * from "./run-properties"; export * from "./document-defaults"; diff --git a/src/file/styles/defaults/paragraph-properties.ts b/src/file/styles/defaults/paragraph-properties.ts index ea8d94bf3a..3d3078167b 100644 --- a/src/file/styles/defaults/paragraph-properties.ts +++ b/src/file/styles/defaults/paragraph-properties.ts @@ -1,6 +1,31 @@ import { IParagraphStylePropertiesOptions, ParagraphProperties } from "@file/paragraph/properties"; import { XmlComponent } from "@file/xml-components"; +/** + * Represents default paragraph properties in a WordprocessingML document. + * + * This element defines the default paragraph formatting properties that apply + * to all paragraphs in the document unless overridden. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Set default paragraph spacing + * new ParagraphPropertiesDefaults({ + * spacing: { after: 200, line: 276 } + * }); + * ``` + */ export class ParagraphPropertiesDefaults extends XmlComponent { public constructor(options?: IParagraphStylePropertiesOptions) { super("w:pPrDefault"); diff --git a/src/file/styles/defaults/run-properties.ts b/src/file/styles/defaults/run-properties.ts index 650daf3a17..3f613cf8f1 100644 --- a/src/file/styles/defaults/run-properties.ts +++ b/src/file/styles/defaults/run-properties.ts @@ -1,6 +1,32 @@ import { IRunStylePropertiesOptions, RunProperties } from "@file/paragraph/run/properties"; import { XmlComponent } from "@file/xml-components"; +/** + * Represents default run properties in a WordprocessingML document. + * + * This element defines the default text run formatting properties that apply + * to all text runs in the document unless overridden by styles or direct formatting. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Set default font and size + * new RunPropertiesDefaults({ + * font: "Calibri", + * size: 22 + * }); + * ``` + */ export class RunPropertiesDefaults extends XmlComponent { public constructor(options?: IRunStylePropertiesOptions) { super("w:rPrDefault"); diff --git a/src/file/styles/external-styles-factory.ts b/src/file/styles/external-styles-factory.ts index fbc593a921..b5da20ae63 100644 --- a/src/file/styles/external-styles-factory.ts +++ b/src/file/styles/external-styles-factory.ts @@ -1,32 +1,57 @@ +/** + * External styles factory module for WordprocessingML documents. + * + * Provides functionality to import and parse styles from external XML sources. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { Element as XMLElement, xml2js } from "xml-js"; import { ImportedRootElementAttributes, ImportedXmlComponent, convertToXmlComponent } from "@file/xml-components"; import { IStylesOptions } from "./styles"; +/** + * Factory for creating styles from external XML sources. + * + * This factory parses styles from XML (typically from a styles.xml file) + * and converts them into Styles components that can be used in the document. + * + * @example + * ```typescript + * // Import styles from an external styles.xml file + * const factory = new ExternalStylesFactory(); + * const xmlData = '...'; + * const styles = factory.newInstance(xmlData); + * ``` + */ export class ExternalStylesFactory { /** - * Creates new Style based on the given styles. - * Parses the styles and convert them to XmlComponent. + * Creates new Styles based on the given XML data. + * + * Parses the styles XML and converts them to XmlComponent instances. + * * Example content from styles.xml: - * + * ```xml + * * - * * - * - * ..... + * + * ... * - * * - * - * ..... + * + * ... * - * - * Or any other element will be parsed to - * + * ... * + * ``` * - * @param externalStyles context from styles.xml + * @param xmlData - XML string containing styles data from styles.xml + * @returns Styles object containing all parsed styles + * @throws Error if styles element cannot be found in the XML */ public newInstance(xmlData: string): IStylesOptions { const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement; diff --git a/src/file/styles/factory.ts b/src/file/styles/factory.ts index 49bac14ae2..52fb761c8a 100644 --- a/src/file/styles/factory.ts +++ b/src/file/styles/factory.ts @@ -1,3 +1,12 @@ +/** + * Factory module for creating default document styles. + * + * Provides a factory class that creates pre-configured styles for common document elements. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { DocumentDefaults, IDocumentDefaultsOptions } from "./defaults"; import { FootnoteReferenceStyle, @@ -19,23 +28,77 @@ import { import { IStylesOptions } from "./styles"; import { DocumentAttributes } from "../document/document-attributes"; +/** + * Options for configuring default document styles. + * + * Allows customization of built-in styles for common document elements. + * + * @property document - Document-wide default formatting + * @property title - Title paragraph style options + * @property heading1 - Heading 1 paragraph style options + * @property heading2 - Heading 2 paragraph style options + * @property heading3 - Heading 3 paragraph style options + * @property heading4 - Heading 4 paragraph style options + * @property heading5 - Heading 5 paragraph style options + * @property heading6 - Heading 6 paragraph style options + * @property strong - Strong paragraph style options + * @property listParagraph - List paragraph style options + * @property hyperlink - Hyperlink character style options + * @property footnoteReference - Footnote reference character style options + * @property footnoteText - Footnote text paragraph style options + * @property footnoteTextChar - Footnote text character style options + */ export type IDefaultStylesOptions = { + /** Document-wide default formatting */ readonly document?: IDocumentDefaultsOptions; + /** Title paragraph style options */ readonly title?: IBaseParagraphStyleOptions; + /** Heading 1 paragraph style options */ readonly heading1?: IBaseParagraphStyleOptions; + /** Heading 2 paragraph style options */ readonly heading2?: IBaseParagraphStyleOptions; + /** Heading 3 paragraph style options */ readonly heading3?: IBaseParagraphStyleOptions; + /** Heading 4 paragraph style options */ readonly heading4?: IBaseParagraphStyleOptions; + /** Heading 5 paragraph style options */ readonly heading5?: IBaseParagraphStyleOptions; + /** Heading 6 paragraph style options */ readonly heading6?: IBaseParagraphStyleOptions; + /** Strong paragraph style options */ readonly strong?: IBaseParagraphStyleOptions; + /** List paragraph style options */ readonly listParagraph?: IBaseParagraphStyleOptions; + /** Hyperlink character style options */ readonly hyperlink?: IBaseCharacterStyleOptions; + /** Footnote reference character style options */ readonly footnoteReference?: IBaseCharacterStyleOptions; + /** Footnote text paragraph style options */ readonly footnoteText?: IBaseParagraphStyleOptions; + /** Footnote text character style options */ readonly footnoteTextChar?: IBaseCharacterStyleOptions; }; +/** + * Factory for creating default document styles. + * + * This factory creates a complete set of default styles for common document elements + * such as headings, hyperlinks, and footnotes with sensible default formatting. + * + * @example + * ```typescript + * // Create default styles with custom heading colors + * const factory = new DefaultStylesFactory(); + * const styles = factory.newInstance({ + * heading1: { + * run: { color: "FF0000", size: 32 } + * }, + * heading2: { + * run: { color: "00FF00", size: 26 } + * } + * }); + * ``` + */ export class DefaultStylesFactory { public newInstance(options: IDefaultStylesOptions = {}): IStylesOptions { const documentAttributes = new DocumentAttributes(["mc", "r", "w", "w14", "w15"], "w14 w15"); diff --git a/src/file/styles/index.ts b/src/file/styles/index.ts index e18813fbb8..1ff32c7cb3 100644 --- a/src/file/styles/index.ts +++ b/src/file/styles/index.ts @@ -1,3 +1,8 @@ +/** + * Styles module exports. + * + * @module + */ export * from "./styles"; export * from "./style/character-style"; export * from "./style/paragraph-style"; diff --git a/src/file/styles/latent-styles/exceptions.ts b/src/file/styles/latent-styles/exceptions.ts index 174d6c3421..d5beb28053 100644 --- a/src/file/styles/latent-styles/exceptions.ts +++ b/src/file/styles/latent-styles/exceptions.ts @@ -1,13 +1,32 @@ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +/** + * Properties for latent style exception attributes. + * + * @property name - The name of the style for this exception + * @property uiPriority - UI priority for displaying the style + * @property qFormat - Whether this style should appear in the quick format gallery + * @property semiHidden - Whether the style is semi-hidden in the UI + * @property unhideWhenUsed - Whether the style should unhide when used + */ export type ILatentStyleExceptionAttributesProperties = { + /** The name of the style for this exception */ readonly name?: string; + /** UI priority for displaying the style */ readonly uiPriority?: string; + /** Whether this style should appear in the quick format gallery */ readonly qFormat?: string; + /** Whether the style is semi-hidden in the UI */ readonly semiHidden?: string; + /** Whether the style should unhide when used */ readonly unhideWhenUsed?: string; }; +/** + * Represents attributes for a latent style exception. + * + * @internal + */ export class LatentStyleExceptionAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { name: "w:name", @@ -18,6 +37,36 @@ export class LatentStyleExceptionAttributes extends XmlAttributeComponent + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create an exception for Heading 1 + * new LatentStyleException({ + * name: "Heading 1", + * uiPriority: "9", + * qFormat: "1" + * }); + * ``` + */ export class LatentStyleException extends XmlComponent { public constructor(attributes: ILatentStyleExceptionAttributesProperties) { super("w:lsdException"); diff --git a/src/file/styles/latent-styles/index.ts b/src/file/styles/latent-styles/index.ts index 5fd2ec64cf..002cc495aa 100644 --- a/src/file/styles/latent-styles/index.ts +++ b/src/file/styles/latent-styles/index.ts @@ -1 +1,8 @@ +/** + * Latent styles module for WordprocessingML documents. + * + * Exports components for defining latent styles and their exceptions. + * + * @module + */ export * from "./latent-styles"; diff --git a/src/file/styles/latent-styles/latent-styles.ts b/src/file/styles/latent-styles/latent-styles.ts index e77678bf07..b417b3aa4c 100644 --- a/src/file/styles/latent-styles/latent-styles.ts +++ b/src/file/styles/latent-styles/latent-styles.ts @@ -1,7 +1,49 @@ +/** + * Latent styles module for WordprocessingML documents. + * + * Latent styles define styles that are not yet used in the document but can be + * made available when needed. This reduces file size while maintaining style definitions. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { LatentStyleException } from "./exceptions"; +/** + * Represents latent style definitions in a WordprocessingML document. + * + * Latent styles are style definitions that exist in the application's style gallery + * but are not yet instantiated in the document. This element specifies default + * properties for latent styles and can define exceptions for specific styles. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Define latent styles with exceptions + * new LatentStyles( + * new LatentStyleException({ name: "Heading 1", uiPriority: "9", qFormat: "1" }) + * ); + * ``` + */ export class LatentStyles extends XmlComponent { public constructor(latentException?: LatentStyleException) { super("w:latentStyles"); diff --git a/src/file/styles/sample/default-style.ts b/src/file/styles/sample/default-style.ts index a53693ab25..ec0f3fe021 100644 --- a/src/file/styles/sample/default-style.ts +++ b/src/file/styles/sample/default-style.ts @@ -1,3 +1,26 @@ +/** + * Sample default styles module for WordprocessingML documents. + * + * Provides legacy default style definitions for backward compatibility. + * This is an older format and new code should use DefaultStylesFactory instead. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ + +/** + * Creates a latent style exception element. + * + * @param name - The name of the style + * @param uiPriority - UI priority for displaying the style + * @param qFormat - Whether this style should appear in the quick format gallery + * @param semiHidden - Whether the style is semi-hidden in the UI + * @param unhideWhenUsed - Whether the style should unhide when used + * @returns Array of objects representing the latent style exception + * + * @internal + */ const createLsdException = ( name: string, uiPriority?: number, @@ -20,6 +43,22 @@ const createLsdException = ( ]; }; +/** + * Generates default style definitions in legacy XML format. + * + * This function creates a complete set of default styles including document defaults, + * latent styles, and common paragraph/character styles in the older object format. + * + * @deprecated This is a legacy format. New code should use DefaultStylesFactory instead. + * + * @returns Object representation of default styles in XML format + * + * @example + * ```typescript + * // Legacy usage - prefer DefaultStylesFactory for new code + * const styles = DefaultStyle(); + * ``` + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export const DefaultStyle = (): Record => { const style = { diff --git a/src/file/styles/sample/index.ts b/src/file/styles/sample/index.ts index 12a14b5a4d..6eab015be1 100644 --- a/src/file/styles/sample/index.ts +++ b/src/file/styles/sample/index.ts @@ -1 +1,6 @@ +/** + * Sample styles module exports. + * + * @module + */ export * from "./default-style"; diff --git a/src/file/styles/style/character-style.ts b/src/file/styles/style/character-style.ts index 188f574195..5fe9f0d343 100644 --- a/src/file/styles/style/character-style.ts +++ b/src/file/styles/style/character-style.ts @@ -1,15 +1,70 @@ +/** + * Character style module for WordprocessingML documents. + * + * Character styles define formatting that applies to individual text runs. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { IRunStylePropertiesOptions, RunProperties } from "@file/paragraph/run/properties"; import { IStyleOptions, Style } from "./style"; +/** + * Base options for character style configuration. + * + * @property run - Run properties (font, size, color, etc.) for this character style + */ export type IBaseCharacterStyleOptions = { + /** Run properties (font, size, color, etc.) for this character style */ readonly run?: IRunStylePropertiesOptions; } & IStyleOptions; +/** + * Options for creating a character style. + * + * @property id - Unique identifier for the character style + */ export type ICharacterStyleOptions = { + /** Unique identifier for the character style */ readonly id: string; } & IBaseCharacterStyleOptions; +/** + * Represents a character style in a WordprocessingML document. + * + * Character styles apply formatting to individual runs of text within a paragraph, + * such as font, size, color, bold, italic, and other text-level formatting. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a custom character style for highlighting + * new StyleForCharacter({ + * id: "Highlight", + * name: "Highlight Text", + * basedOn: "DefaultParagraphFont", + * run: { + * color: "FF0000", + * bold: true + * } + * }); + * ``` + */ export class StyleForCharacter extends Style { private readonly runProperties: RunProperties; diff --git a/src/file/styles/style/components.ts b/src/file/styles/style/components.ts index 36132790f0..5efe0f845b 100644 --- a/src/file/styles/style/components.ts +++ b/src/file/styles/style/components.ts @@ -1,13 +1,39 @@ -// http://officeopenxml.com/WPstyleGenProps.php +/** + * Style components module for WordprocessingML documents. + * + * Provides common elements used in style definitions. + * + * Reference: http://officeopenxml.com/WPstyleGenProps.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; +/** + * Represents component attributes with a value. + * + * @internal + */ class ComponentAttributes extends XmlAttributeComponent<{ readonly val: string | number; }> { protected readonly xmlKeys = { val: "w:val" }; } +/** + * Represents the name element of a style. + * + * This element specifies the display name of a style as shown in the user interface. + * + * Reference: http://officeopenxml.com/WPstyleGenProps.php + * + * @example + * ```typescript + * // Typically used internally by Style class + * new Name("Heading 1"); + * ``` + */ export class Name extends XmlComponent { public constructor(value: string) { super("w:name"); @@ -15,6 +41,20 @@ export class Name extends XmlComponent { } } +/** + * Represents the UI priority of a style. + * + * This element specifies the sort order priority for displaying the style in the user interface. + * Lower numbers appear first in style lists. + * + * Reference: http://officeopenxml.com/WPstyleGenProps.php + * + * @example + * ```typescript + * // Typically used internally by Style class + * new UiPriority(99); + * ``` + */ export class UiPriority extends XmlComponent { public constructor(value: number) { super("w:uiPriority"); @@ -22,6 +62,16 @@ export class UiPriority extends XmlComponent { } } +/** + * Represents table properties for table styles. + * + * @internal + */ export class TableProperties extends XmlComponent {} +/** + * Represents revision save ID for tracking document changes. + * + * @internal + */ export class RsId extends XmlComponent {} diff --git a/src/file/styles/style/default-styles.ts b/src/file/styles/style/default-styles.ts index 50a01f854e..45a575a3f7 100644 --- a/src/file/styles/style/default-styles.ts +++ b/src/file/styles/style/default-styles.ts @@ -1,9 +1,35 @@ +/** + * Default styles module for WordprocessingML documents. + * + * Provides pre-configured style classes for common document elements like headings, + * hyperlinks, and footnotes. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { LineRuleType } from "@file/paragraph"; import { UnderlineType } from "@file/paragraph/run/underline"; import { IBaseCharacterStyleOptions, StyleForCharacter } from "./character-style"; import { IBaseParagraphStyleOptions, IParagraphStyleOptions, StyleForParagraph } from "./paragraph-style"; +/** + * Base class for heading styles. + * + * Provides common configuration for heading styles, including basedOn="Normal" + * and quickFormat enabled. + * + * @example + * ```typescript + * // Typically extended by specific heading classes + * new HeadingStyle({ + * id: "CustomHeading", + * name: "Custom Heading", + * run: { bold: true, size: 28 } + * }); + * ``` + */ export class HeadingStyle extends StyleForParagraph { public constructor(options: IParagraphStyleOptions) { super({ @@ -15,6 +41,18 @@ export class HeadingStyle extends StyleForParagraph { } } +/** + * Represents the Title paragraph style. + * + * Used for document titles with larger font size and emphasis. + * + * @example + * ```typescript + * new TitleStyle({ + * run: { size: 56, bold: true } + * }); + * ``` + */ export class TitleStyle extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -25,6 +63,18 @@ export class TitleStyle extends HeadingStyle { } } +/** + * Represents the Heading 1 paragraph style. + * + * First-level heading style for major document sections. + * + * @example + * ```typescript + * new Heading1Style({ + * run: { size: 32, color: "2E74B5" } + * }); + * ``` + */ export class Heading1Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -35,6 +85,11 @@ export class Heading1Style extends HeadingStyle { } } +/** + * Represents the Heading 2 paragraph style. + * + * Second-level heading style for subsections. + */ export class Heading2Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -45,6 +100,11 @@ export class Heading2Style extends HeadingStyle { } } +/** + * Represents the Heading 3 paragraph style. + * + * Third-level heading style for sub-subsections. + */ export class Heading3Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -55,6 +115,11 @@ export class Heading3Style extends HeadingStyle { } } +/** + * Represents the Heading 4 paragraph style. + * + * Fourth-level heading style for nested sections. + */ export class Heading4Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -65,6 +130,11 @@ export class Heading4Style extends HeadingStyle { } } +/** + * Represents the Heading 5 paragraph style. + * + * Fifth-level heading style for deeply nested sections. + */ export class Heading5Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -75,6 +145,11 @@ export class Heading5Style extends HeadingStyle { } } +/** + * Represents the Heading 6 paragraph style. + * + * Sixth-level heading style for the deepest nested sections. + */ export class Heading6Style extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -85,6 +160,11 @@ export class Heading6Style extends HeadingStyle { } } +/** + * Represents the Strong paragraph style. + * + * Used for emphasizing important paragraphs with bold formatting. + */ export class StrongStyle extends HeadingStyle { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -95,6 +175,11 @@ export class StrongStyle extends HeadingStyle { } } +/** + * Represents the List Paragraph style. + * + * Used for paragraphs within numbered or bulleted lists. + */ export class ListParagraph extends StyleForParagraph { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -107,6 +192,11 @@ export class ListParagraph extends StyleForParagraph { } } +/** + * Represents the Footnote Text paragraph style. + * + * Used for the text content of footnotes with smaller font size and tighter spacing. + */ export class FootnoteText extends StyleForParagraph { public constructor(options: IBaseParagraphStyleOptions) { super({ @@ -132,6 +222,11 @@ export class FootnoteText extends StyleForParagraph { } } +/** + * Represents the Footnote Reference character style. + * + * Used for footnote reference numbers in the main text, displayed as superscript. + */ export class FootnoteReferenceStyle extends StyleForCharacter { public constructor(options: IBaseCharacterStyleOptions) { super({ @@ -147,6 +242,11 @@ export class FootnoteReferenceStyle extends StyleForCharacter { } } +/** + * Represents the Footnote Text Char character style. + * + * Character style linked to FootnoteText paragraph style for consistent formatting. + */ export class FootnoteTextChar extends StyleForCharacter { public constructor(options: IBaseCharacterStyleOptions) { super({ @@ -163,6 +263,11 @@ export class FootnoteTextChar extends StyleForCharacter { } } +/** + * Represents the Hyperlink character style. + * + * Used for hyperlinks with blue color and single underline formatting. + */ export class HyperlinkStyle extends StyleForCharacter { public constructor(options: IBaseCharacterStyleOptions) { super({ diff --git a/src/file/styles/style/index.ts b/src/file/styles/style/index.ts index abe53aa61e..193f2c6d3b 100644 --- a/src/file/styles/style/index.ts +++ b/src/file/styles/style/index.ts @@ -1,3 +1,12 @@ +/** + * Style definitions module for WordprocessingML documents. + * + * Exports components for defining paragraph styles, character styles, and common style elements. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ export * from "./style"; export * from "./paragraph-style"; export * from "./character-style"; diff --git a/src/file/styles/style/paragraph-style.ts b/src/file/styles/style/paragraph-style.ts index 7dc4eeb887..ddb7dc4b98 100644 --- a/src/file/styles/style/paragraph-style.ts +++ b/src/file/styles/style/paragraph-style.ts @@ -1,17 +1,81 @@ +/** + * Paragraph style module for WordprocessingML documents. + * + * Paragraph styles define formatting that applies to entire paragraphs. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { IParagraphStylePropertiesOptions, IRunStylePropertiesOptions, ParagraphProperties } from "@file/paragraph"; import { RunProperties } from "@file/paragraph/run/properties"; import { IStyleOptions, Style } from "./style"; +/** + * Base options for paragraph style configuration. + * + * @property paragraph - Paragraph properties (alignment, spacing, indentation, etc.) + * @property run - Run properties that apply to text within this paragraph style + */ export type IBaseParagraphStyleOptions = { + /** Paragraph properties (alignment, spacing, indentation, etc.) */ readonly paragraph?: IParagraphStylePropertiesOptions; + /** Run properties that apply to text within this paragraph style */ readonly run?: IRunStylePropertiesOptions; } & IStyleOptions; +/** + * Options for creating a paragraph style. + * + * @property id - Unique identifier for the paragraph style + */ export type IParagraphStyleOptions = { + /** Unique identifier for the paragraph style */ readonly id: string; } & IBaseParagraphStyleOptions; +/** + * Represents a paragraph style in a WordprocessingML document. + * + * Paragraph styles apply formatting to entire paragraphs, including both + * paragraph-level properties (spacing, alignment, indentation) and + * run-level properties (font, size, color) for text within the paragraph. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a custom heading style + * new StyleForParagraph({ + * id: "CustomHeading", + * name: "Custom Heading", + * basedOn: "Normal", + * paragraph: { + * spacing: { before: 240, after: 120 }, + * alignment: AlignmentType.LEFT + * }, + * run: { + * size: 28, + * bold: true, + * color: "2E74B5" + * } + * }); + * ``` + */ export class StyleForParagraph extends Style { private readonly paragraphProperties: ParagraphProperties; private readonly runProperties: RunProperties; diff --git a/src/file/styles/style/style.ts b/src/file/styles/style/style.ts index 12dbe33900..40c901501c 100644 --- a/src/file/styles/style/style.ts +++ b/src/file/styles/style/style.ts @@ -1,3 +1,12 @@ +/** + * Style definition module for WordprocessingML documents. + * + * Provides base style functionality for paragraph and character styles. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * @module + */ import { OnOffElement, StringValueElement, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { Name, UiPriority } from "./components"; @@ -33,14 +42,39 @@ import { Name, UiPriority } from "./components"; // // +/** + * Attributes for style elements. + * + * @property type - Type of style (paragraph, character, table, numbering) + * @property styleId - Unique identifier for the style + * @property default - Whether this is the default style for its type + * @property customStyle - Whether this is a custom user-defined style + */ export type IStyleAttributes = { + /** Type of style (paragraph, character, table, numbering) */ readonly type?: string; + /** Unique identifier for the style */ readonly styleId?: string; + /** Whether this is the default style for its type */ readonly default?: boolean; + /** Whether this is a custom user-defined style */ readonly customStyle?: string; }; +/** + * Options for configuring a style. + * + * @property name - Display name of the style + * @property basedOn - Style ID that this style inherits from (must be same type) + * @property next - Style to automatically apply to the next paragraph + * @property link - Linked style ID for paragraph/character style pairing + * @property uiPriority - Priority for displaying in the UI (lower numbers appear first) + * @property semiHidden - Whether the style is semi-hidden in the UI + * @property unhideWhenUsed - Whether the style should unhide when used + * @property quickFormat - Whether the style appears in the quick format gallery + */ export type IStyleOptions = { + /** Display name of the style */ readonly name?: string; /** * Specifies the style upon which the current style is based-that is, the style from which the current style inherits. It is the mechanism for implementing style inheritance. @@ -50,14 +84,25 @@ export type IStyleOptions = { * **WARNING**: You cannot set `basedOn` to be the same as `name`. This is akin to inheriting from itself. This creates a cyclic dependency and cause undesirable behavior. */ readonly basedOn?: string; + /** Style to automatically apply to the next paragraph */ readonly next?: string; + /** Linked style ID for paragraph/character style pairing */ readonly link?: string; + /** Priority for displaying in the UI (lower numbers appear first) */ readonly uiPriority?: number; + /** Whether the style is semi-hidden in the UI */ readonly semiHidden?: boolean; + /** Whether the style should unhide when used */ readonly unhideWhenUsed?: boolean; + /** Whether the style appears in the quick format gallery */ readonly quickFormat?: boolean; }; +/** + * Represents style attributes for XML serialization. + * + * @internal + */ class StyleAttributes extends XmlAttributeComponent { protected readonly xmlKeys = { type: "w:type", @@ -67,6 +112,54 @@ class StyleAttributes extends XmlAttributeComponent { }; } +/** + * Represents a base style definition in a WordprocessingML document. + * + * This is the base class for paragraph and character styles. It defines common + * style properties such as name, inheritance (basedOn), UI priority, and visibility. + * + * Reference: http://officeopenxml.com/WPstyles.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // This is typically extended by StyleForParagraph or StyleForCharacter + * // See those classes for usage examples + * ``` + */ export class Style extends XmlComponent { public constructor(attributes: IStyleAttributes, options: IStyleOptions) { super("w:style"); diff --git a/src/file/styles/styles.ts b/src/file/styles/styles.ts index b8f7c24c78..91797ae6dd 100644 --- a/src/file/styles/styles.ts +++ b/src/file/styles/styles.ts @@ -17,13 +17,24 @@ import { IParagraphStyleOptions } from "./style/paragraph-style"; /** * Options for configuring document styles. * + * @property default - Default styles for document, headings, and common elements + * @property initialStyles - Initial base XML component for styles root element + * @property paragraphStyles - Array of custom paragraph style definitions + * @property characterStyles - Array of custom character style definitions + * @property importedStyles - Array of styles imported from external sources + * * @see {@link Styles} */ export type IStylesOptions = { + /** Default styles for document, headings, and common elements */ readonly default?: IDefaultStylesOptions; + /** Initial base XML component for styles root element */ readonly initialStyles?: BaseXmlComponent; + /** Array of custom paragraph style definitions */ readonly paragraphStyles?: readonly IParagraphStyleOptions[]; + /** Array of custom character style definitions */ readonly characterStyles?: readonly ICharacterStyleOptions[]; + /** Array of styles imported from external sources */ readonly importedStyles?: readonly (XmlComponent | StyleForParagraph | StyleForCharacter | ImportedXmlComponent)[]; }; @@ -31,7 +42,8 @@ export type IStylesOptions = { * Represents the styles definitions in a WordprocessingML document. * * The styles element contains document defaults, latent styles, and - * individual style definitions for paragraphs and characters. + * individual style definitions for paragraphs and characters. Styles provide + * a way to define consistent formatting across a document. * * Reference: http://officeopenxml.com/WPstyles.php * @@ -45,6 +57,24 @@ export type IStylesOptions = { * * * ``` + * + * @example + * ```typescript + * // Create styles with custom paragraph and character styles + * new Styles({ + * paragraphStyles: [{ + * id: "CustomHeading", + * name: "Custom Heading", + * basedOn: "Normal", + * run: { bold: true, size: 28 } + * }], + * characterStyles: [{ + * id: "Highlight", + * name: "Highlight", + * run: { color: "FF0000" } + * }] + * }); + * ``` */ export class Styles extends XmlComponent { public constructor(options: IStylesOptions) { diff --git a/src/file/table-of-contents/field-instruction.ts b/src/file/table-of-contents/field-instruction.ts index e902febeb6..29a80521d7 100644 --- a/src/file/table-of-contents/field-instruction.ts +++ b/src/file/table-of-contents/field-instruction.ts @@ -1,10 +1,46 @@ -// http://officeopenxml.com/WPfieldInstructions.php +/** + * Field Instruction module for Table of Contents. + * + * This module handles the generation of TOC field instruction text + * that controls how the table of contents is built. + * + * Reference: http://officeopenxml.com/WPfieldInstructions.php + * + * @module + */ import { TextAttributes } from "@file/paragraph/run/text-attributes"; import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; import { ITableOfContentsOptions } from "./table-of-contents-properties"; +/** + * Represents a field instruction for a Table of Contents. + * + * The FieldInstruction class generates the TOC field code string that Word uses + * to determine how to build the table of contents, including which headings to include, + * formatting options, and other TOC-specific settings. + * + * Reference: http://officeopenxml.com/WPfieldInstructions.php + * + * ## XSD Schema + * ```xml + * + * ``` + * + * @example + * ```typescript + * // Basic TOC field instruction + * new FieldInstruction({ headingStyleRange: "1-3" }); + * + * // TOC with hyperlinks and custom styles + * new FieldInstruction({ + * hyperlink: true, + * headingStyleRange: "1-3", + * stylesWithLevels: [new StyleLevel("CustomStyle", 2)], + * }); + * ``` + */ export class FieldInstruction extends XmlComponent { private readonly properties: ITableOfContentsOptions; diff --git a/src/file/table-of-contents/index.ts b/src/file/table-of-contents/index.ts index f36b16b738..455c97139a 100644 --- a/src/file/table-of-contents/index.ts +++ b/src/file/table-of-contents/index.ts @@ -1,2 +1,12 @@ +/** + * Table of Contents exports. + * + * This module provides all public APIs for creating and configuring + * table of contents in WordprocessingML documents. + * + * Reference: http://officeopenxml.com/WPtableOfContents.php + * + * @module + */ export * from "./table-of-contents"; export * from "./table-of-contents-properties"; diff --git a/src/file/table-of-contents/sdt-content.ts b/src/file/table-of-contents/sdt-content.ts index b4e181522a..8c34470dbc 100644 --- a/src/file/table-of-contents/sdt-content.ts +++ b/src/file/table-of-contents/sdt-content.ts @@ -1,5 +1,37 @@ +/** + * Structured Document Tag Content module. + * + * This module represents the content container for structured document tags, + * including table of contents elements. + * + * Reference: http://officeopenxml.com/WPtableOfContents.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * Represents the content portion of a Structured Document Tag. + * + * The StructuredDocumentTagContent contains the actual content elements + * (paragraphs, tables, etc.) within a structured document tag, such as + * the paragraphs that make up a table of contents. + * + * Reference: http://officeopenxml.com/WPtableOfContents.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * const content = new StructuredDocumentTagContent(); + * content.addChildElement(new Paragraph("Content")); + * ``` + */ export class StructuredDocumentTagContent extends XmlComponent { public constructor() { super("w:sdtContent"); diff --git a/src/file/table-of-contents/sdt-properties.ts b/src/file/table-of-contents/sdt-properties.ts index ba69d5e97a..c1082de6a8 100644 --- a/src/file/table-of-contents/sdt-properties.ts +++ b/src/file/table-of-contents/sdt-properties.ts @@ -1,6 +1,54 @@ -// http://www.datypic.com/sc/ooxml/e-w_sdtPr-1.html +/** + * Structured Document Tag Properties module. + * + * This module represents the properties of a structured document tag, + * such as aliases and other metadata. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_sdtPr-1.html + * + * @module + */ import { StringValueElement, XmlComponent } from "@file/xml-components"; +/** + * Represents the properties of a Structured Document Tag. + * + * The StructuredDocumentTagProperties defines metadata for a structured document tag, + * including display names (aliases), tags, and content control types. + * + * Reference: http://www.datypic.com/sc/ooxml/e-w_sdtPr-1.html + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * ``` + * + * @example + * ```typescript + * // Create properties with an alias + * new StructuredDocumentTagProperties("Table of Contents"); + * ``` + */ export class StructuredDocumentTagProperties extends XmlComponent { public constructor(alias?: string) { super("w:sdtPr"); diff --git a/src/file/table-of-contents/table-of-contents-properties.ts b/src/file/table-of-contents/table-of-contents-properties.ts index 86aeedb823..0923d8a1b5 100644 --- a/src/file/table-of-contents/table-of-contents-properties.ts +++ b/src/file/table-of-contents/table-of-contents-properties.ts @@ -1,5 +1,24 @@ +/** + * Table of Contents Properties module. + * + * This module defines configuration options for table of contents generation, + * including field switches and style mappings. + * + * Reference: http://officeopenxml.com/WPtableOfContents.php + * + * @module + */ + +/** + * Represents a style-to-level mapping for table of contents entries. + * + * StyleLevel associates a paragraph style name with a TOC level, allowing + * custom styles to be included in the table of contents at specific levels. + */ export class StyleLevel { + /** The name of the paragraph style. */ public readonly styleName: string; + /** The TOC level (1-9) to assign to this style. */ public readonly level: number; public constructor(styleName: string, level: number) { @@ -9,12 +28,14 @@ export class StyleLevel { } /** - * Options according to this docs: - * https://www.ecma-international.org/publications/standards/Ecma-376.htm - * Part 1 - Page 1251 + * Options for configuring a Table of Contents. * - * Short Guide: - * http://officeopenxml.com/WPtableOfContents.php + * These options control which content is included in the TOC and how it is formatted. + * Options correspond to field switches in the TOC field code. + * + * Reference: + * - https://www.ecma-international.org/publications/standards/Ecma-376.htm (Part 1, Page 1251) + * - http://officeopenxml.com/WPtableOfContents.php */ export type ITableOfContentsOptions = { /** diff --git a/src/file/table/index.ts b/src/file/table/index.ts index 81ceac8b1a..f795b15643 100644 --- a/src/file/table/index.ts +++ b/src/file/table/index.ts @@ -1,3 +1,8 @@ +/** + * Table module exports. + * + * @module + */ export * from "./table"; export * from "./table-cell"; export * from "./table-properties"; diff --git a/src/file/table/table-cell-spacing.ts b/src/file/table/table-cell-spacing.ts index 73fd9fee96..cd922725c6 100644 --- a/src/file/table/table-cell-spacing.ts +++ b/src/file/table/table-cell-spacing.ts @@ -1,14 +1,29 @@ -// http://officeopenxml.com/WPtableCellSpacing.php +/** + * Table cell spacing module for WordprocessingML documents. + * + * This module provides cell spacing settings for tables, controlling + * the space between cells in a table. + * + * Reference: http://officeopenxml.com/WPtableCellSpacing.php + * + * @module + */ import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { Percentage, UniversalMeasure, measurementOrPercentValue } from "@util/values"; -// -// -// -// -// -// - +/** + * Cell spacing measurement types. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const CellSpacingType = { /** Value is in twentieths of a point */ DXA: "dxa", @@ -16,15 +31,38 @@ export const CellSpacingType = { NIL: "nil", } as const; -// -// -// -// +/** + * Properties for table cell spacing. + * + * @see {@link TableCellSpacingElement} + */ export type ITableCellSpacingProperties = { + /** The spacing value (in twips, percentage, or universal measure) */ readonly value: number | Percentage | UniversalMeasure; + /** The type of measurement (defaults to DXA/twips) */ readonly type?: (typeof CellSpacingType)[keyof typeof CellSpacingType]; }; +/** + * Represents table cell spacing in a WordprocessingML document. + * + * The tblCellSpacing element specifies the spacing between cells in a table. + * + * Reference: http://officeopenxml.com/WPtableCellSpacing.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableCellSpacingElement({ value: 100, type: CellSpacingType.DXA }); + * ``` + */ export class TableCellSpacingElement extends XmlComponent { public constructor({ type = CellSpacingType.DXA, value }: ITableCellSpacingProperties) { super("w:tblCellSpacing"); diff --git a/src/file/table/table-cell/index.ts b/src/file/table/table-cell/index.ts index 5a095cd19d..3da01b6995 100644 --- a/src/file/table/table-cell/index.ts +++ b/src/file/table/table-cell/index.ts @@ -1,2 +1,7 @@ +/** + * Table cell module exports. + * + * @module + */ export * from "./table-cell"; export * from "./table-cell-components"; diff --git a/src/file/table/table-cell/table-cell-components.ts b/src/file/table/table-cell/table-cell-components.ts index 160b54a9bf..0e198745d3 100644 --- a/src/file/table/table-cell/table-cell-components.ts +++ b/src/file/table/table-cell/table-cell-components.ts @@ -1,31 +1,74 @@ +/** + * Table cell components module for WordprocessingML documents. + * + * This module provides XML components for table cell properties including borders, + * grid span (column span), vertical merge, and text direction. + * + * Reference: http://officeopenxml.com/WPtableCell.php + * + * @module + */ import { BorderElement, IBorderOptions } from "@file/border"; import { IgnoreIfEmptyXmlComponent, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { decimalNumber } from "@util/values"; -// -// -// -// -// -// -// -// -// -// -// -// -// -// - +/** + * Options for configuring table cell borders. + * + * Defines border settings for individual edges of a table cell. Border settings + * can be specified for top, bottom, left, right, start, and end edges. + * + * @see {@link TableCellBorders} + */ export type ITableCellBorders = { + /** Border for the top edge of the cell */ readonly top?: IBorderOptions; + /** Border for the start edge (left in LTR, right in RTL) */ readonly start?: IBorderOptions; + /** Border for the left edge of the cell */ readonly left?: IBorderOptions; + /** Border for the bottom edge of the cell */ readonly bottom?: IBorderOptions; + /** Border for the end edge (right in LTR, left in RTL) */ readonly end?: IBorderOptions; + /** Border for the right edge of the cell */ readonly right?: IBorderOptions; }; +/** + * Represents table cell borders (tcBorders) in a WordprocessingML document. + * + * The tcBorders element specifies the borders for a single table cell. Each border + * can be configured independently with different styles, colors, and widths. + * + * Reference: http://officeopenxml.com/WPtableCell.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableCellBorders({ + * top: { style: BorderStyle.SINGLE, size: 6, color: "FF0000" }, + * bottom: { style: BorderStyle.SINGLE, size: 6, color: "0000FF" }, + * }); + * ``` + */ export class TableCellBorders extends IgnoreIfEmptyXmlComponent { public constructor(options: ITableCellBorders) { super("w:tcBorders"); @@ -52,18 +95,32 @@ export class TableCellBorders extends IgnoreIfEmptyXmlComponent { } /** - * Attributes fot the GridSpan element. + * Attributes for the GridSpan element. */ class GridSpanAttributes extends XmlAttributeComponent<{ readonly val: number }> { protected readonly xmlKeys = { val: "w:val" }; } -// -// ... -// -// /** - * GridSpan element. Should be used in a table cell. Pass the number of columns that this cell need to span. + * Represents a grid span (gridSpan) element in a WordprocessingML document. + * + * The gridSpan element specifies the number of logical columns this cell spans + * in the table grid. This is used to merge cells horizontally (column span). + * + * Reference: http://officeopenxml.com/WPtableCell.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Cell spanning 3 columns + * new GridSpan(3); + * ``` */ export class GridSpan extends XmlComponent { public constructor(value: number) { @@ -78,19 +135,26 @@ export class GridSpan extends XmlComponent { } /** - * Vertical merge types. + * Vertical merge types for table cells. + * + * Defines the merge behavior for vertically merged cells (row span). */ export const VerticalMergeType = { /** * Cell that is merged with upper one. + * This cell continues a vertical merge started by a cell above it. */ CONTINUE: "continue", /** * Cell that is starting the vertical merge. + * This cell begins a new vertical merge region. */ RESTART: "restart", } as const; +/** + * Attributes for the VerticalMerge element. + */ class VerticalMergeAttributes extends XmlAttributeComponent<{ readonly val: (typeof VerticalMergeType)[keyof typeof VerticalMergeType]; }> { @@ -98,7 +162,29 @@ class VerticalMergeAttributes extends XmlAttributeComponent<{ } /** - * Vertical merge element. Should be used in a table cell. + * Represents a vertical merge (vMerge) element in a WordprocessingML document. + * + * The vMerge element specifies that this cell is part of a vertically merged region. + * Cells can either restart a new merge region or continue an existing one from above. + * This is used to create row spans in tables. + * + * Reference: http://officeopenxml.com/WPtableCell.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // First cell in a vertical merge + * new VerticalMerge(VerticalMergeType.RESTART); + * + * // Subsequent cells that continue the merge + * new VerticalMerge(VerticalMergeType.CONTINUE); + * ``` */ export class VerticalMerge extends XmlComponent { public constructor(value: (typeof VerticalMergeType)[keyof typeof VerticalMergeType]) { @@ -112,12 +198,23 @@ export class VerticalMerge extends XmlComponent { } } +/** + * Text direction values for table cells. + * + * Specifies the direction in which text flows within a table cell. + */ export const TextDirection = { + /** Text flows from bottom to top, left to right */ BOTTOM_TO_TOP_LEFT_TO_RIGHT: "btLr", + /** Text flows from left to right, top to bottom (default) */ LEFT_TO_RIGHT_TOP_TO_BOTTOM: "lrTb", + /** Text flows from top to bottom, right to left */ TOP_TO_BOTTOM_RIGHT_TO_LEFT: "tbRl", } as const; +/** + * Attributes for the TDirection element. + */ class TDirectionAttributes extends XmlAttributeComponent<{ readonly val: (typeof TextDirection)[keyof typeof TextDirection]; }> { @@ -125,7 +222,25 @@ class TDirectionAttributes extends XmlAttributeComponent<{ } /** - * Text Direction within a table cell + * Represents a text direction (textDirection) element in a WordprocessingML document. + * + * The textDirection element specifies the flow of text within a table cell. This is + * useful for creating rotated text or supporting different writing systems. + * + * Reference: http://officeopenxml.com/WPtableCell.php + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Vertical text flowing from top to bottom + * new TDirection(TextDirection.TOP_TO_BOTTOM_RIGHT_TO_LEFT); + * ``` */ export class TDirection extends XmlComponent { public constructor(value: (typeof TextDirection)[keyof typeof TextDirection]) { diff --git a/src/file/table/table-cell/table-cell-properties.ts b/src/file/table/table-cell/table-cell-properties.ts index b39850c573..4e6db68424 100644 --- a/src/file/table/table-cell/table-cell-properties.ts +++ b/src/file/table/table-cell/table-cell-properties.ts @@ -30,14 +30,23 @@ import { * @see {@link TableCellProperties} */ export type ITableCellPropertiesOptions = { + /** Shading (background color/pattern) for the cell */ readonly shading?: IShadingAttributesProperties; + /** Cell margins (padding) for the cell content */ readonly margins?: ITableCellMarginOptions; + /** Vertical alignment of content within the cell */ readonly verticalAlign?: TableVerticalAlign; + /** Text direction/flow within the cell */ readonly textDirection?: (typeof TextDirection)[keyof typeof TextDirection]; + /** Vertical merge setting for the cell */ readonly verticalMerge?: (typeof VerticalMergeType)[keyof typeof VerticalMergeType]; + /** Width specification for the cell */ readonly width?: ITableWidthProperties; + /** Number of columns this cell spans (horizontal merge) */ readonly columnSpan?: number; + /** Number of rows this cell spans (vertical merge) */ readonly rowSpan?: number; + /** Border settings for the cell edges */ readonly borders?: ITableCellBorders; }; @@ -45,9 +54,52 @@ export type ITableCellPropertiesOptions = { * Represents table cell properties (tcPr) in a WordprocessingML document. * * The tcPr element specifies properties for a table cell including width, - * borders, shading, margins, text direction, and merge settings. + * borders, shading, margins, text direction, vertical alignment, and merge settings. + * These properties control the appearance and behavior of individual table cells. * * Reference: http://officeopenxml.com/WPtableCellProperties.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableCellProperties({ + * width: { size: 3000, type: WidthType.DXA }, + * shading: { fill: "EEEEEE" }, + * verticalAlign: VerticalAlign.CENTER, + * columnSpan: 2, + * }); + * ``` */ export class TableCellProperties extends IgnoreIfEmptyXmlComponent { public constructor(options: ITableCellPropertiesOptions) { diff --git a/src/file/table/table-properties/index.ts b/src/file/table/table-properties/index.ts index aefcc9e0aa..ca8a19647d 100644 --- a/src/file/table/table-properties/index.ts +++ b/src/file/table/table-properties/index.ts @@ -1,3 +1,8 @@ +/** + * Table properties module exports. + * + * @module + */ export * from "./table-properties"; export * from "./table-float-properties"; export * from "./table-layout"; diff --git a/src/file/table/table-properties/table-cell-margin.ts b/src/file/table/table-properties/table-cell-margin.ts index e862de2bf3..0d8a16657b 100644 --- a/src/file/table/table-properties/table-cell-margin.ts +++ b/src/file/table/table-properties/table-cell-margin.ts @@ -1,43 +1,75 @@ +/** + * Table cell margin module for WordprocessingML documents. + * + * This module provides cell margin settings for tables and individual cells. + * + * Reference: http://officeopenxml.com/WPtableCellProperties-Margins.php + * + * @module + */ import { TableWidthElement, WidthType } from "@file/table"; import { IgnoreIfEmptyXmlComponent } from "@file/xml-components"; +/** + * Options for configuring table cell margins. + * + * @see {@link TableCellMargin} + */ export type ITableCellMarginOptions = { + /** The unit type for margin values (defaults to DXA/twips) */ readonly marginUnitType?: (typeof WidthType)[keyof typeof WidthType]; + /** Top margin in specified units */ readonly top?: number; + /** Bottom margin in specified units */ readonly bottom?: number; + /** Left margin in specified units */ readonly left?: number; + /** Right margin in specified units */ readonly right?: number; }; -// Technically two different types, but they're identical -// -// -// -// -// -// -// -// -// -// -// - -// -// -// -// -// -// -// -// -// -// - +/** + * Element type for table cell margins. + * + * Used to differentiate between table-level and cell-level margin elements. + */ export const TableCellMarginElementType = { TABLE: "w:tblCellMar", TABLE_CELL: "w:tcMar", } as const; +/** + * Represents table cell margins in a WordprocessingML document. + * + * The tblCellMar (table level) or tcMar (cell level) element specifies + * the default cell margins for a table or individual cell. + * + * Reference: http://officeopenxml.com/WPtableCellProperties-Margins.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableCellMargin(TableCellMarginElementType.TABLE, { + * top: 100, + * bottom: 100, + * left: 100, + * right: 100, + * }); + * ``` + */ export class TableCellMargin extends IgnoreIfEmptyXmlComponent { public constructor( type: (typeof TableCellMarginElementType)[keyof typeof TableCellMarginElementType], diff --git a/src/file/table/table-properties/table-float-properties.ts b/src/file/table/table-properties/table-float-properties.ts index 9067c91842..1e0ff86c8e 100644 --- a/src/file/table/table-properties/table-float-properties.ts +++ b/src/file/table/table-properties/table-float-properties.ts @@ -1,12 +1,30 @@ +/** + * Table float properties module for WordprocessingML documents. + * + * This module provides floating table positioning options, allowing tables + * to float with text wrapping around them. + * + * Reference: http://officeopenxml.com/WPtableFloating.php + * + * @module + */ import { NextAttributeComponent, StringEnumValueElement, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, UniversalMeasure, signedTwipsMeasureValue, twipsMeasureValue } from "@util/values"; +/** + * Anchor types for floating table positioning. + * + * Specifies the base object from which positioning is determined. + */ export const TableAnchorType = { MARGIN: "margin", PAGE: "page", TEXT: "text", } as const; +/** + * Relative horizontal position values for floating tables. + */ export const RelativeHorizontalPosition = { CENTER: "center", INSIDE: "inside", @@ -15,6 +33,9 @@ export const RelativeHorizontalPosition = { RIGHT: "right", } as const; +/** + * Relative vertical position values for floating tables. + */ export const RelativeVerticalPosition = { CENTER: "center", INSIDE: "inside", @@ -24,12 +45,19 @@ export const RelativeVerticalPosition = { TOP: "top", } as const; -// -// -// -// -// -// +/** + * Table overlap behavior types. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * ``` + */ export const OverlapType = { NEVER: "never", OVERLAP: "overlap", @@ -126,19 +154,40 @@ export type ITableFloatOptions = { readonly overlap?: (typeof OverlapType)[keyof typeof OverlapType]; }; -// -// -// -// -// -// -// -// -// -// -// -// - +/** + * Represents floating table properties in a WordprocessingML document. + * + * This element specifies the positioning of a floating table, + * including anchor points, offsets, and text wrapping behavior. + * + * Reference: http://officeopenxml.com/WPtableFloating.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableFloatProperties({ + * horizontalAnchor: TableAnchorType.MARGIN, + * relativeHorizontalPosition: RelativeHorizontalPosition.CENTER, + * topFromText: 200, + * bottomFromText: 200, + * }); + * ``` + */ export class TableFloatProperties extends XmlComponent { public constructor({ horizontalAnchor, diff --git a/src/file/table/table-row/index.ts b/src/file/table/table-row/index.ts index 455c143d9a..8c6c361a14 100644 --- a/src/file/table/table-row/index.ts +++ b/src/file/table/table-row/index.ts @@ -1,3 +1,8 @@ +/** + * Table row module exports. + * + * @module + */ export * from "./table-row"; export * from "./table-row-properties"; export * from "./table-row-height"; diff --git a/src/file/table/table-row/table-row-height.ts b/src/file/table/table-row/table-row-height.ts index f1ca591cd3..c21b219d4e 100644 --- a/src/file/table/table-row/table-row-height.ts +++ b/src/file/table/table-row/table-row-height.ts @@ -1,18 +1,31 @@ +/** + * Table row height module for WordprocessingML documents. + * + * This module provides row height configuration including rules for how height should be applied. + * + * Reference: http://officeopenxml.com/WPtableRow.php + * + * @module + */ import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, twipsMeasureValue } from "@util/values"; -// -// -// -// - -// -// -// -// -// -// -// +/** + * Height rules for table rows. + * + * Specifies how the height value should be interpreted. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + */ export const HeightRule = { /** Height is determined based on the content, so value is ignored. */ AUTO: "auto", @@ -22,13 +35,41 @@ export const HeightRule = { EXACT: "exact", } as const; +/** + * Attributes for table row height element. + * + * Internal component for managing trHeight attributes. + */ export class TableRowHeightAttributes extends XmlAttributeComponent<{ + /** Height value in twips */ readonly value: number | string; + /** Height rule determining how the height value is applied */ readonly rule: (typeof HeightRule)[keyof typeof HeightRule]; }> { protected readonly xmlKeys = { value: "w:val", rule: "w:hRule" }; } +/** + * Represents table row height (trHeight) in a WordprocessingML document. + * + * The trHeight element specifies the height of a table row, along with a rule + * determining how the height should be applied. + * + * Reference: http://officeopenxml.com/WPtableRow.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * new TableRowHeight(1000, HeightRule.EXACT); + * ``` + */ export class TableRowHeight extends XmlComponent { public constructor(value: number | PositiveUniversalMeasure, rule: (typeof HeightRule)[keyof typeof HeightRule]) { super("w:trHeight"); diff --git a/src/file/table/table-row/table-row-properties.ts b/src/file/table/table-row/table-row-properties.ts index ff447f69e9..af8a0b7dd9 100644 --- a/src/file/table/table-row/table-row-properties.ts +++ b/src/file/table/table-row/table-row-properties.ts @@ -50,12 +50,18 @@ import { ITableCellSpacingProperties, TableCellSpacingElement } from "../table-c * @see {@link TableRowProperties} */ export type ITableRowPropertiesOptions = { + /** Whether the row can be split across pages (cantSplit) */ readonly cantSplit?: boolean; + /** Whether the row should be repeated as a header row on each page (tblHeader) */ readonly tableHeader?: boolean; + /** Row height configuration (trHeight) */ readonly height?: { + /** Height value in twips or as a PositiveUniversalMeasure */ readonly value: number | PositiveUniversalMeasure; + /** Height rule determining how the height value is applied */ readonly rule: (typeof HeightRule)[keyof typeof HeightRule]; }; + /** Spacing between cells in the row (tblCellSpacing) */ readonly cellSpacing?: ITableCellSpacingProperties; }; @@ -66,6 +72,18 @@ export type ITableRowPropertiesOptions = { * whether it can split across pages, and whether it's a header row. * * Reference: http://officeopenxml.com/WPtableRowProperties.php + * + * @example + * ```typescript + * new TableRowProperties({ + * cantSplit: true, + * tableHeader: true, + * height: { + * value: 1000, + * rule: HeightRule.EXACT, + * }, + * }); + * ``` */ export class TableRowProperties extends IgnoreIfEmptyXmlComponent { public constructor(options: ITableRowPropertiesOptions) { diff --git a/src/file/table/table-row/table-row.ts b/src/file/table/table-row/table-row.ts index 0934114240..8e1e628b20 100644 --- a/src/file/table/table-row/table-row.ts +++ b/src/file/table/table-row/table-row.ts @@ -1,3 +1,10 @@ +/** + * Table row module for WordprocessingML documents. + * + * Reference: http://officeopenxml.com/WPtableRow.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { TableCell } from "../table-cell"; diff --git a/src/file/textbox/index.ts b/src/file/textbox/index.ts index 013eef503a..b613c52b4c 100644 --- a/src/file/textbox/index.ts +++ b/src/file/textbox/index.ts @@ -1 +1,6 @@ +/** + * Textbox module exports. + * + * @module + */ export * from "./textbox"; diff --git a/src/file/textbox/pict-element/pict-element.ts b/src/file/textbox/pict-element/pict-element.ts index 0904ddb737..351fa48c77 100644 --- a/src/file/textbox/pict-element/pict-element.ts +++ b/src/file/textbox/pict-element/pict-element.ts @@ -1,9 +1,57 @@ +/** + * Picture element module for WordprocessingML documents. + * + * Provides functionality for creating pict (picture) elements that contain VML shapes. + * + * @module + */ import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Options for creating a picture element. + * + * @property shape - The VML shape to be contained within the picture element + */ export type IPictElement = { + /** The VML shape to be contained within the picture element */ readonly shape: XmlComponent; }; +/** + * Creates a picture element containing a VML shape. + * + * The picture element (w:pict) is a container for VML (Vector Markup Language) content + * within WordprocessingML documents, commonly used for textboxes and other drawing objects. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @param options - Configuration options containing the VML shape + * @returns An XmlComponent representing the w:pict element + * + * @example + * ```typescript + * const pictElement = createPictElement({ + * shape: createShape({ + * id: "shape1", + * children: [new TextRun("Hello")] + * }) + * }); + * ``` + */ export const createPictElement = ({ shape }: IPictElement): XmlComponent => new BuilderElement<{ readonly style?: string }>({ name: "w:pict", diff --git a/src/file/textbox/shape/shape.ts b/src/file/textbox/shape/shape.ts index 30cdac074b..8738c74b39 100644 --- a/src/file/textbox/shape/shape.ts +++ b/src/file/textbox/shape/shape.ts @@ -1,5 +1,14 @@ -// https://c-rex.net/samples/ooxml/e1/Part3/OOXML_P3_Primer_OfficeArt_topic_ID0ELU5O.html -// http://webapp.docx4java.org/OnlineDemo/ecma376/VML/shape.html +/** + * VML shape module for WordprocessingML documents. + * + * Provides functionality for creating VML shape elements with customizable styling and positioning. + * + * References: + * - https://c-rex.net/samples/ooxml/e1/Part3/OOXML_P3_Primer_OfficeArt_topic_ID0ELU5O.html + * - http://webapp.docx4java.org/OnlineDemo/ecma376/VML/shape.html + * + * @module + */ import { ParagraphChild } from "@file/paragraph"; import { BuilderElement, XmlComponent } from "@file/xml-components"; @@ -8,6 +17,10 @@ import { createVmlTextbox } from "../vml-textbox/vml-texbox"; const SHAPE_TYPE = "#_x0000_t202"; +/** + * Maps VmlShapeStyle property names to their corresponding CSS-style property names. + * Used internally for converting TypeScript-friendly property names to VML style attributes. + */ const styleToKeyMap: Record = { flip: "flip", height: "height", @@ -34,6 +47,13 @@ const styleToKeyMap: Record = { zIndex: "z-index", }; +/** + * Styling options for VML shapes. + * + * This type defines all available CSS-like styling properties for positioning, sizing, + * and configuring VML shapes in WordprocessingML documents. These properties control + * the shape's appearance, layout, and interaction with surrounding text. + */ export type VmlShapeStyle = { /** Specifies that the orientation of a shape is flipped. Default is no value. */ readonly flip?: "x" | "y" | "xy" | "yx"; @@ -83,6 +103,13 @@ export type VmlShapeStyle = { readonly zIndex?: "auto" | number; }; +/** + * Formats VmlShapeStyle object into a CSS-style string for VML shape attributes. + * + * @param style - The VmlShapeStyle object to format + * @returns A CSS-style string (e.g., "width:100pt;height:50pt;") or undefined if no style provided + * @internal + */ const formatShapeStyle = (style?: VmlShapeStyle): string | undefined => style ? Object.entries(style) @@ -90,13 +117,69 @@ const formatShapeStyle = (style?: VmlShapeStyle): string | undefined => .join(";") : undefined; +/** + * Options for creating a VML shape. + * + * @property id - Unique identifier for the shape + * @property children - Array of paragraph children to include in the shape's textbox + * @property type - VML shape type identifier (default: "#_x0000_t202" for text rectangle) + * @property style - Styling properties for the shape + */ type ShapeOptions = { + /** Unique identifier for the shape */ readonly id: string; + /** Array of paragraph children to include in the shape's textbox */ readonly children?: readonly ParagraphChild[]; + /** VML shape type identifier (default: "#_x0000_t202" for text rectangle) */ readonly type?: string; + /** Styling properties for the shape */ readonly style?: VmlShapeStyle; }; +/** + * Creates a VML shape element with textbox content. + * + * The VML shape element (v:shape) represents a vector graphics shape in WordprocessingML documents. + * This function creates shapes configured for text display (textbox shapes), which are commonly + * used for creating floating text boxes with custom positioning and styling. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @param options - Configuration options for the shape + * @returns An XmlComponent representing the v:shape element + * + * @example + * ```typescript + * const shape = createShape({ + * id: "textbox1", + * children: [new TextRun("Hello World")], + * style: { + * width: "3in", + * height: "1in", + * position: "absolute", + * left: "1in", + * top: "1in" + * } + * }); + * ``` + */ export const createShape = ({ id, children, type = SHAPE_TYPE, style }: ShapeOptions): XmlComponent => new BuilderElement< Pick & { diff --git a/src/file/textbox/texbox-content/textbox-content.ts b/src/file/textbox/texbox-content/textbox-content.ts index 0ce8af56d9..baeed60ec3 100644 --- a/src/file/textbox/texbox-content/textbox-content.ts +++ b/src/file/textbox/texbox-content/textbox-content.ts @@ -1,6 +1,37 @@ +/** + * Textbox content module for WordprocessingML documents. + * + * Provides functionality for creating textbox content elements that contain block-level content. + * + * @module + */ import { ParagraphChild } from "@file/paragraph"; import { BuilderElement, XmlComponent } from "@file/xml-components"; +/** + * Creates a textbox content element containing block-level content. + * + * The textbox content element (w:txbxContent) represents the content container within a VML textbox. + * It can contain block-level elements such as paragraphs and tables. + * + * ## XSD Schema + * ```xml + * + * + * + * ``` + * + * @param options - Configuration options + * @param options.children - Array of paragraph children to include in the textbox content + * @returns An XmlComponent representing the w:txbxContent element + * + * @example + * ```typescript + * const content = createTextboxContent({ + * children: [new TextRun("Hello World")] + * }); + * ``` + */ export const createTextboxContent = ({ children = [] }: { readonly children?: readonly ParagraphChild[] }): XmlComponent => new BuilderElement<{ readonly style?: string }>({ name: "w:txbxContent", diff --git a/src/file/textbox/textbox.ts b/src/file/textbox/textbox.ts index 36438c6a68..b15efc24cb 100644 --- a/src/file/textbox/textbox.ts +++ b/src/file/textbox/textbox.ts @@ -1,7 +1,8 @@ /** * Textbox module for WordprocessingML documents. * - * This module provides support for text boxes using VML shapes. + * This module provides support for text boxes using VML shapes. Textboxes allow for + * creating floating text containers with custom positioning and styling. * * @module */ @@ -15,18 +16,61 @@ import { VmlShapeStyle, createShape } from "./shape/shape"; /** * Options for creating a Textbox. * - * @see {@link Textbox} + * Extends paragraph options while replacing the style property with VML shape styling. + * + * @property style - VML shape style properties for positioning and sizing + * @property children - Array of child elements (text runs, hyperlinks, etc.) */ type ITextboxOptions = Omit & { - /** VML style properties for the textbox shape */ + /** VML shape style properties for the textbox (positioning, sizing, wrapping, etc.) */ readonly style?: VmlShapeStyle; }; /** * Represents a textbox in a WordprocessingML document. * - * Textbox creates a rectangular text container that can be positioned - * anywhere on the page using VML shapes. + * A Textbox creates a floating text container using VML shapes that can be positioned + * anywhere on the page. Unlike regular paragraphs, textboxes support absolute positioning, + * custom dimensions, and text wrapping control. + * + * The textbox is implemented as a paragraph containing a picture element (w:pict) with + * a VML shape (v:shape) that contains a VML textbox (v:textbox) with the actual content. + * + * ## XSD Schema + * The Textbox combines multiple OOXML elements: + * - w:p (paragraph container) + * - w:pict (picture element containing VML) + * - v:shape (VML shape with styling) + * - v:textbox (VML textbox content container) + * - w:txbxContent (WordprocessingML textbox content) + * + * @example + * ```typescript + * // Simple textbox with text + * new Textbox({ + * children: [new TextRun("Hello World")], + * style: { + * width: "3in", + * height: "1in" + * } + * }); + * + * // Positioned textbox with wrapping + * new Textbox({ + * children: [ + * new TextRun({ text: "Floating Text", bold: true }), + * new TextRun({ text: " in a textbox", break: 1 }) + * ], + * style: { + * width: "2.5in", + * height: "1.5in", + * position: "absolute", + * left: "1in", + * top: "2in", + * wrapStyle: "square" + * } + * }); + * ``` */ export class Textbox extends FileChild { public constructor({ style, children, ...rest }: ITextboxOptions) { diff --git a/src/file/textbox/types.ts b/src/file/textbox/types.ts index 20429ede76..176c9e672a 100644 --- a/src/file/textbox/types.ts +++ b/src/file/textbox/types.ts @@ -1,3 +1,20 @@ +/** + * Textbox types module. + * + * Defines common types used across textbox-related components. + * + * @module + */ import { Percentage, RelativeMeasure, UniversalMeasure } from "@util/values"; +/** + * Represents a length unit value for VML shape styling. + * + * Length units can be specified in multiple formats: + * - "auto" - Automatically calculated by the application + * - number - Numeric value (typically in points) + * - Percentage - Percentage-based measurement + * - UniversalMeasure - Measurement with explicit units (pt, cm, in, etc.) + * - RelativeMeasure - Relative measurement units + */ export type LengthUnit = "auto" | number | Percentage | UniversalMeasure | RelativeMeasure; diff --git a/src/file/textbox/vml-textbox/vml-texbox.ts b/src/file/textbox/vml-textbox/vml-texbox.ts index e97ce135ad..9c3a61833c 100644 --- a/src/file/textbox/vml-textbox/vml-texbox.ts +++ b/src/file/textbox/vml-textbox/vml-texbox.ts @@ -1,4 +1,12 @@ -// http://webapp.docx4java.org/OnlineDemo/ecma376/VML/textbox.html +/** + * VML textbox module for WordprocessingML documents. + * + * Provides functionality for creating VML textbox elements that define text containers within shapes. + * + * Reference: http://webapp.docx4java.org/OnlineDemo/ecma376/VML/textbox.html + * + * @module + */ import { ParagraphChild } from "@file/paragraph"; import { BuilderElement, XmlComponent } from "@file/xml-components"; import { InsetMode } from "@util/types"; @@ -10,17 +18,69 @@ import { LengthUnit } from "../types"; // readonly fontWeight?: "normal" | "lighter" | 100 | 200 | 300 | 400 | "bold" | "bolder" | 500 | 600 | 700 | 800 | 900; // } +/** + * Options for creating a VML textbox element. + * + * @property style - CSS-style string for textbox styling + * @property children - Array of paragraph children to include in the textbox + * @property inset - Custom inset margins for the textbox content + */ export type IVTextboxOptions = { + /** CSS-style string for textbox styling */ readonly style?: string; + /** Array of paragraph children to include in the textbox */ readonly children?: readonly ParagraphChild[]; + /** Custom inset margins for the textbox content (top, left, bottom, right) */ readonly inset?: { + /** Top inset margin */ readonly top: LengthUnit; + /** Left inset margin */ readonly left: LengthUnit; + /** Bottom inset margin */ readonly bottom: LengthUnit; + /** Right inset margin */ readonly right: LengthUnit; }; }; +/** + * Creates a VML textbox element. + * + * The VML textbox element (v:textbox) defines a text container within a VML shape. + * It supports custom styling and inset margins to control text positioning within the shape. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @param options - Configuration options for the VML textbox + * @returns An XmlComponent representing the v:textbox element + * + * @example + * ```typescript + * const vmlTextbox = createVmlTextbox({ + * style: "mso-fit-shape-to-text:t;", + * children: [new TextRun("Hello World")], + * inset: { + * top: "0.1in", + * left: "0.1in", + * bottom: "0.1in", + * right: "0.1in" + * } + * }); + * ``` + */ export const createVmlTextbox = ({ style, children, inset }: IVTextboxOptions): XmlComponent => new BuilderElement<{ readonly style?: string; readonly inset?: string; readonly insetMode?: InsetMode }>({ name: "v:textbox", diff --git a/src/file/track-revision/index.ts b/src/file/track-revision/index.ts index eb2465d8fe..dc9a61d36a 100644 --- a/src/file/track-revision/index.ts +++ b/src/file/track-revision/index.ts @@ -1,2 +1,12 @@ +/** + * Track Revision module for WordprocessingML documents. + * + * Provides components for tracking changes in documents including insertions, + * deletions, and their associated metadata (author, date, id). + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * @module + */ export * from "./track-revision-components/inserted-text-run"; export * from "./track-revision-components/deleted-text-run"; diff --git a/src/file/track-revision/track-revision-components/deleted-page-number.ts b/src/file/track-revision/track-revision-components/deleted-page-number.ts index 034335179b..b323c9d45e 100644 --- a/src/file/track-revision/track-revision-components/deleted-page-number.ts +++ b/src/file/track-revision/track-revision-components/deleted-page-number.ts @@ -1,7 +1,44 @@ +/** + * Deleted instruction text elements for field codes in track changes. + * + * Provides deleted versions of page number and page count field instructions. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * @module + */ import { TextAttributes } from "@file/paragraph/run/text-attributes"; import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; +/** + * Represents a deleted PAGE field instruction. + * + * This element contains the field instruction code for the current page number + * within a deletion. Uses w:delInstrText instead of w:instrText to mark it as + * part of a tracked deletion. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally within DeletedTextRun for page number fields + * new DeletedPage(); // Creates PAGE + * ``` + */ export class DeletedPage extends XmlComponent { public constructor() { super("w:delInstrText"); @@ -10,6 +47,34 @@ export class DeletedPage extends XmlComponent { } } +/** + * Represents a deleted NUMPAGES field instruction. + * + * This element contains the field instruction code for the total number of pages + * in the document within a deletion. Uses w:delInstrText instead of w:instrText + * to mark it as part of a tracked deletion. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally within DeletedTextRun for total pages field + * new DeletedNumberOfPages(); // Creates NUMPAGES + * ``` + */ export class DeletedNumberOfPages extends XmlComponent { public constructor() { super("w:delInstrText"); @@ -18,6 +83,34 @@ export class DeletedNumberOfPages extends XmlComponent { } } +/** + * Represents a deleted SECTIONPAGES field instruction. + * + * This element contains the field instruction code for the total number of pages + * in the current section within a deletion. Uses w:delInstrText instead of + * w:instrText to mark it as part of a tracked deletion. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally within DeletedTextRun for section pages field + * new DeletedNumberOfPagesSection(); // Creates SECTIONPAGES + * ``` + */ export class DeletedNumberOfPagesSection extends XmlComponent { public constructor() { super("w:delInstrText"); diff --git a/src/file/track-revision/track-revision-components/deleted-text-run.ts b/src/file/track-revision/track-revision-components/deleted-text-run.ts index 30fe7fbec0..35a67bae2c 100644 --- a/src/file/track-revision/track-revision-components/deleted-text-run.ts +++ b/src/file/track-revision/track-revision-components/deleted-text-run.ts @@ -1,3 +1,10 @@ +/** + * Deleted text run module for track changes. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { DeletedNumberOfPages, DeletedNumberOfPagesSection, DeletedPage } from "./deleted-page-number"; @@ -8,8 +15,63 @@ import { RunProperties } from "../../paragraph/run/properties"; import { IRunOptions, PageNumber } from "../../paragraph/run/run"; import { ChangeAttributes, IChangedAttributesProperties } from "../track-revision"; +/** + * Options for creating a deleted text run. + * + * Combines run formatting options with track change metadata. + * + * @property id - Unique identifier for this deletion + * @property author - Name of the author who deleted the text + * @property date - Date and time when the deletion was made (ISO 8601 format) + */ type IDeletedRunOptions = IRunOptions & IChangedAttributesProperties; +/** + * Represents a deleted text run in a tracked changes document. + * + * A deletion marks text that has been removed from the document as part of + * revision tracking. It wraps a text run with metadata about who made the + * deletion and when. Deleted text is typically shown with strikethrough + * formatting in applications that support track changes. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create a deleted text run + * new DeletedTextRun({ + * id: 2, + * author: "Jane Smith", + * date: "2024-01-15T11:00:00Z", + * text: "This text was removed", + * italics: true + * }); + * + * // Deleted run with page number field + * new DeletedTextRun({ + * id: 3, + * author: "John Doe", + * date: "2024-01-15T12:00:00Z", + * children: [PageNumber.CURRENT] + * }); + * ``` + */ export class DeletedTextRun extends XmlComponent { protected readonly deletedTextRunWrapper: DeletedTextRunWrapper; @@ -27,6 +89,15 @@ export class DeletedTextRun extends XmlComponent { } } +/** + * Internal wrapper for the run element within a deletion. + * + * Wraps the actual run content (text, fields, etc.) within a w:r element + * that appears inside the w:del element. Handles special cases like page + * numbers and other field codes using deleted-specific element types. + * + * @internal + */ class DeletedTextRunWrapper extends XmlComponent { public constructor(options: IRunOptions) { super("w:r"); diff --git a/src/file/track-revision/track-revision-components/deleted-text.ts b/src/file/track-revision/track-revision-components/deleted-text.ts index 7245a151d3..61f49afaeb 100644 --- a/src/file/track-revision/track-revision-components/deleted-text.ts +++ b/src/file/track-revision/track-revision-components/deleted-text.ts @@ -1,7 +1,42 @@ +/** + * Deleted text element module for track changes. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * @module + */ import { TextAttributes } from "@file/paragraph/run/text-attributes"; import { SpaceType } from "@file/shared"; import { XmlComponent } from "@file/xml-components"; +/** + * Represents deleted text content within a tracked deletion. + * + * This element contains the actual text that was deleted. Unlike regular text + * (w:t), deleted text uses the w:delText element to distinguish it as part of + * a deletion. The xml:space="preserve" attribute ensures whitespace is maintained. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Used internally within DeletedTextRun + * new DeletedText("This text was removed"); + * ``` + */ export class DeletedText extends XmlComponent { public constructor(text: string) { super("w:delText"); diff --git a/src/file/track-revision/track-revision-components/inserted-text-run.ts b/src/file/track-revision/track-revision-components/inserted-text-run.ts index 9084674590..b560adfc94 100644 --- a/src/file/track-revision/track-revision-components/inserted-text-run.ts +++ b/src/file/track-revision/track-revision-components/inserted-text-run.ts @@ -1,10 +1,63 @@ +/** + * Inserted text run module for track changes. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * @module + */ import { XmlComponent } from "@file/xml-components"; import { IRunOptions, TextRun } from "../../index"; import { ChangeAttributes, IChangedAttributesProperties } from "../track-revision"; +/** + * Options for creating an inserted text run. + * + * Combines run formatting options with track change metadata. + * + * @property id - Unique identifier for this insertion + * @property author - Name of the author who inserted the text + * @property date - Date and time when the insertion was made (ISO 8601 format) + */ type IInsertedRunOptions = IChangedAttributesProperties & IRunOptions; +/** + * Represents an inserted text run in a tracked changes document. + * + * An insertion marks text that has been added to the document as part of + * revision tracking. It wraps a standard text run with metadata about who + * made the insertion and when. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Create an inserted text run + * new InsertedTextRun({ + * id: 1, + * author: "John Doe", + * date: "2024-01-15T10:30:00Z", + * text: "This text was added", + * bold: true + * }); + * ``` + */ export class InsertedTextRun extends XmlComponent { public constructor(options: IInsertedRunOptions) { super("w:ins"); diff --git a/src/file/track-revision/track-revision.ts b/src/file/track-revision/track-revision.ts index 713f9b5b7a..b2c432ebb2 100644 --- a/src/file/track-revision/track-revision.ts +++ b/src/file/track-revision/track-revision.ts @@ -4,31 +4,54 @@ * This module provides support for tracking document revisions * (insertions, deletions, and formatting changes). * - * Reference: http://officeopenxml.com/WPtrackRevisions.php + * Reference: http://officeopenxml.com/WPtrackChanges.php * * @module */ import { XmlAttributeComponent } from "@file/xml-components"; /** - * Properties for a tracked change. + * Properties for a tracked change element. * - * @see {@link ChangeAttributes} + * These properties identify the change and its author for revision tracking. + * + * @property id - Unique identifier for this change (must be unique within the document) + * @property author - Name of the author who made the change + * @property date - Date and time when the change was made (ISO 8601 format) */ export type IChangedAttributesProperties = { - /** Unique identifier for this change */ + /** Unique identifier for this change (must be unique within the document) */ readonly id: number; - /** Author who made the change */ + /** Name of the author who made the change */ readonly author: string; - /** Date/time when the change was made (ISO 8601 format) */ + /** Date and time when the change was made (ISO 8601 format) */ readonly date: string; }; /** * Attributes for a tracked change element. * - * Used by elements like ins (insertion) and del (deletion) to - * record who made a change and when. + * Represents the common attributes (id, author, date) that appear on track change + * elements such as insertions (w:ins) and deletions (w:del). These attributes + * are part of the CT_TrackChange complex type in OOXML. + * + * Reference: http://officeopenxml.com/WPtrackChanges.php + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * + * + * + * ``` * * @internal */ diff --git a/src/file/vertical-align/index.ts b/src/file/vertical-align/index.ts index 29714c88b6..9a8133ff4e 100644 --- a/src/file/vertical-align/index.ts +++ b/src/file/vertical-align/index.ts @@ -1 +1,6 @@ +/** + * Vertical align module exports. + * + * @module + */ export * from "./vertical-align"; diff --git a/src/file/xml-components/attributes.ts b/src/file/xml-components/attributes.ts index 0af2238196..1c9cd3403a 100644 --- a/src/file/xml-components/attributes.ts +++ b/src/file/xml-components/attributes.ts @@ -1,26 +1,72 @@ +/** + * Common XML attributes module for WordprocessingML elements. + * + * This module provides a reusable Attributes class with commonly used + * WordprocessingML attribute mappings. + * + * @module + */ import { XmlAttributeComponent } from "./default-attributes"; +/** + * Common XML attributes used across WordprocessingML elements. + * + * This class provides a convenient way to add common attributes to XML elements. + * It automatically maps JavaScript-friendly property names to their corresponding + * w: (WordprocessingML) namespace prefixed XML attribute names. + * + * @example + * ```typescript + * // Create an element with a value attribute + * new Attributes({ val: "someValue" }); + * // Generates: + * + * // Multiple attributes + * new Attributes({ color: "FF0000", sz: "24" }); + * // Generates: + * ``` + */ export class Attributes extends XmlAttributeComponent<{ + /** Generic value attribute (w:val). */ readonly val?: string | number | boolean; + /** Color value (w:color). */ readonly color?: string; + /** Fill color (w:fill). */ readonly fill?: string; + /** Space preservation (w:space). */ readonly space?: string; + /** Size value (w:sz). */ readonly sz?: string; + /** Type specification (w:type). */ readonly type?: string; + /** Revision ID for run content (w:rsidR). */ readonly rsidR?: string; + /** Revision ID for run properties (w:rsidRPr). */ readonly rsidRPr?: string; + /** Revision ID for section (w:rsidSect). */ readonly rsidSect?: string; + /** Width (w:w). */ readonly w?: string; + /** Height (w:h). */ readonly h?: string; + /** Top margin/spacing (w:top). */ readonly top?: string; + /** Right margin/spacing (w:right). */ readonly right?: string; + /** Bottom margin/spacing (w:bottom). */ readonly bottom?: string; + /** Left margin/spacing (w:left). */ readonly left?: string; + /** Header margin (w:header). */ readonly header?: string; + /** Footer margin (w:footer). */ readonly footer?: string; + /** Gutter margin (w:gutter). */ readonly gutter?: string; + /** Line pitch (w:linePitch). */ readonly linePitch?: string; - readonly pos?: string | number; // Little strange. Perhaps it is normal. Need to clarify in the spec. + /** Position value (w:pos). */ + readonly pos?: string | number; }> { protected readonly xmlKeys = { val: "w:val", diff --git a/src/file/xml-components/base.ts b/src/file/xml-components/base.ts index 3b89f8fa49..d52d3fae72 100644 --- a/src/file/xml-components/base.ts +++ b/src/file/xml-components/base.ts @@ -1,20 +1,77 @@ +/** + * Base XML Component infrastructure for the docx library. + * + * This module provides the abstract base class for all XML components and the context + * object used during XML serialization. + * + * @module + */ import { IViewWrapper } from "../document-wrapper"; import { File } from "../file"; import { IXmlableObject } from "./xmlable-object"; +/** + * Context object passed through the XML tree during serialization. + * + * This context provides access to the document structure and maintains state + * during the conversion of components to XML. + * + * @property file - The root File object being serialized + * @property viewWrapper - Access to document relationships and other document parts + * @property stack - Current traversal stack of components (mutable for performance) + */ export type IContext = { + /** The root File object being serialized. */ readonly file: File; + /** Access to document relationships and other document parts. */ readonly viewWrapper: IViewWrapper; + /** Current traversal stack of components (mutable for performance). */ // eslint-disable-next-line functional/prefer-readonly-type readonly stack: IXmlableObject[]; }; +/** + * Abstract base class for all XML components in the library. + * + * BaseXmlComponent defines the minimal interface that all XML components must implement. + * It stores the XML element name (rootKey) and requires subclasses to implement + * the prepForXml method for serialization. + * + * @example + * ```typescript + * class MyElement extends BaseXmlComponent { + * constructor() { + * super("w:myElement"); + * } + * + * prepForXml(context: IContext): IXmlableObject { + * return { "w:myElement": {} }; + * } + * } + * ``` + */ export abstract class BaseXmlComponent { + /** The XML element name for this component (e.g., "w:p" for paragraph). */ protected readonly rootKey: string; + /** + * Creates a new BaseXmlComponent with the specified XML element name. + * + * @param rootKey - The XML element name (e.g., "w:p", "w:r", "w:t") + */ public constructor(rootKey: string) { this.rootKey = rootKey; } + /** + * Prepares this component for XML serialization. + * + * This method is called by the Formatter to convert the component into an object + * structure that can be serialized to XML. Subclasses must implement this to + * define their XML representation. + * + * @param context - The serialization context + * @returns The XML-serializable object, or undefined to exclude from output + */ public abstract prepForXml(context: IContext): IXmlableObject | undefined; } diff --git a/src/file/xml-components/default-attributes.ts b/src/file/xml-components/default-attributes.ts index 1d125cab3a..d3882d4673 100644 --- a/src/file/xml-components/default-attributes.ts +++ b/src/file/xml-components/default-attributes.ts @@ -1,19 +1,75 @@ +/** + * XML attribute components for the docx library. + * + * This module provides base classes for creating XML element attributes. + * Attributes are represented as special components with the "_attr" key. + * + * @module + */ import { BaseXmlComponent, IContext } from "./base"; import { IXmlAttribute, IXmlableObject } from "./xmlable-object"; +/** + * Maps TypeScript property names to their XML attribute names. + * + * This type is used to define how JavaScript-friendly property names + * are translated into namespaced XML attribute names. + */ export type AttributeMap = Record; +/** + * Simple attribute data as a key-value record. + */ export type AttributeData = Record; + +/** + * Structured attribute payload with explicit key-value mapping. + * + * This type is used by NextAttributeComponent to provide more explicit + * control over attribute name mapping. + */ export type AttributePayload = { readonly [P in keyof T]: { readonly key: string; readonly value: T[P] } }; +/** + * Base class for creating XML attributes with automatic name mapping. + * + * XmlAttributeComponent allows you to define attributes using JavaScript-friendly + * property names that are automatically mapped to XML attribute names. Subclasses + * can define an xmlKeys map to specify the transformation. + * + * @example + * ```typescript + * class MyAttributes extends XmlAttributeComponent<{ fontSize: number }> { + * protected readonly xmlKeys = { fontSize: "w:sz" }; + * } + * + * new MyAttributes({ fontSize: 24 }); + * // Generates: _attr: { "w:sz": 24 } + * ``` + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export abstract class XmlAttributeComponent> extends BaseXmlComponent { + /** Optional mapping from property names to XML attribute names. */ protected readonly xmlKeys?: AttributeMap; + /** + * Creates a new attribute component. + * + * @param root - The attribute data object + */ public constructor(private readonly root: T) { super("_attr"); } + /** + * Converts the attribute data to an XML-serializable object. + * + * This method transforms the property names using xmlKeys (if defined) + * and filters out undefined values. + * + * @param _ - Context (unused for attributes) + * @returns Object with _attr key containing the mapped attributes + */ public prepForXml(_: IContext): IXmlableObject { const attrs: Record = {}; Object.entries(this.root).forEach(([key, value]) => { @@ -27,11 +83,41 @@ export abstract class XmlAttributeComponent> exten } } +/** + * Next-generation attribute component with explicit key-value pairs. + * + * NextAttributeComponent provides an alternative approach to attributes where + * each property explicitly specifies both its XML attribute name and value. + * This gives more control but is more verbose than XmlAttributeComponent. + * + * @example + * ```typescript + * new NextAttributeComponent({ + * fontSize: { key: "w:sz", value: 24 }, + * bold: { key: "w:b", value: true } + * }); + * // Generates: _attr: { "w:sz": 24, "w:b": true } + * ``` + */ export class NextAttributeComponent extends BaseXmlComponent { + /** + * Creates a new NextAttributeComponent. + * + * @param root - Attribute payload with explicit key-value mappings + */ public constructor(private readonly root: AttributePayload) { super("_attr"); } + /** + * Converts the attribute payload to an XML-serializable object. + * + * Extracts the key and value from each property and filters out + * undefined values. + * + * @param _ - Context (unused for attributes) + * @returns Object with _attr key containing the attributes + */ public prepForXml(_: IContext): IXmlableObject { const attrs = Object.values<{ readonly key: string; readonly value: string | boolean | number }>(this.root) .filter(({ value }) => value !== undefined) diff --git a/src/file/xml-components/imported-xml-component.ts b/src/file/xml-components/imported-xml-component.ts index 712aeaa526..dbb6ec1d9d 100644 --- a/src/file/xml-components/imported-xml-component.ts +++ b/src/file/xml-components/imported-xml-component.ts @@ -1,3 +1,12 @@ +/** + * Imported XML Component module for handling external XML content. + * + * This module provides functionality to import existing XML content and convert it + * into XmlComponent trees. This is useful for incorporating XML from external sources + * or templates into generated documents. + * + * @module + */ import { Element as XmlElement, xml2js } from "xml-js"; import { IXmlableObject, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; @@ -5,11 +14,21 @@ import { IXmlableObject, XmlAttributeComponent, XmlComponent } from "@file/xml-c import { IContext } from "./base"; /** - * Converts the given xml element (in json format) into XmlComponent. + * Converts an xml-js Element into an XmlComponent tree. * - * @param element the xml element in json presentation + * This function recursively processes XML elements in JSON format (from xml-js) + * and creates a tree of ImportedXmlComponent objects that match the structure + * of the original XML. + * + * @param element - The XML element in JSON representation from xml-js + * @returns An ImportedXmlComponent tree, text string, or undefined + * + * @example + * ```typescript + * const xmlElement = xml2js('Hello'); + * const component = convertToXmlComponent(xmlElement); + * ``` */ - export const convertToXmlComponent = (element: XmlElement): ImportedXmlComponent | string | undefined => { switch (element.type) { case undefined: @@ -33,19 +52,50 @@ export const convertToXmlComponent = (element: XmlElement): ImportedXmlComponent } }; +/** + * Internal attribute component for imported XML elements. + * @internal + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any class ImportedXmlComponentAttributes extends XmlAttributeComponent { // noop } /** - * Represents imported xml component from xml file. + * XML component representing imported XML content. + * + * ImportedXmlComponent allows you to parse XML strings and incorporate them + * into the document structure. This is particularly useful when working with + * templates or when you need to include pre-existing XML fragments. + * + * @example + * ```typescript + * // Parse XML string into component tree + * const component = ImportedXmlComponent.fromXmlString( + * 'Hello World' + * ); + * + * // Manually create an imported component + * const element = new ImportedXmlComponent("w:customElement", { "w:val": "value" }); + * element.push(new ImportedXmlComponent("w:child")); + * ``` */ export class ImportedXmlComponent extends XmlComponent { /** - * Converts the xml string to a XmlComponent tree. + * Parses an XML string and converts it to an ImportedXmlComponent tree. * - * @param importedContent xml content of the imported component + * This static method is the primary way to import external XML content. + * It uses xml-js to parse the XML string into a JSON representation, + * then converts that into a tree of XmlComponent objects. + * + * @param importedContent - The XML content as a string + * @returns An ImportedXmlComponent representing the parsed XML + * + * @example + * ```typescript + * const xml = 'Hello'; + * const component = ImportedXmlComponent.fromXmlString(xml); + * ``` */ public static fromXmlString(importedContent: string): ImportedXmlComponent { const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement; @@ -54,8 +104,8 @@ export class ImportedXmlComponent extends XmlComponent { /** * Creates an ImportedXmlComponent. * - * @param rootKey the root element name - * @param _attr optional attributes for the root element + * @param rootKey - The XML element name + * @param _attr - Optional attributes for the root element */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public constructor(rootKey: string, _attr?: any) { @@ -65,20 +115,47 @@ export class ImportedXmlComponent extends XmlComponent { } } + /** + * Adds a child component or text to this element. + * + * @param xmlComponent - The child component or text string to add + */ public push(xmlComponent: XmlComponent | string): void { this.root.push(xmlComponent); } } /** - * Used for the attributes of root element that is being imported. + * Represents attributes for imported root elements. + * + * This class is used internally to handle attributes on root elements + * that are being imported from external XML. It passes through the + * attributes without transformation. + * + * @example + * ```typescript + * const attrs = new ImportedRootElementAttributes({ + * "xmlns:w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + * }); + * ``` */ export class ImportedRootElementAttributes extends XmlComponent { + /** + * Creates an ImportedRootElementAttributes component. + * + * @param _attr - The attributes object to pass through + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public constructor(private readonly _attr: any) { super(""); } + /** + * Prepares the attributes for XML serialization. + * + * @param _ - Context (unused) + * @returns Object with _attr key containing the raw attributes + */ public prepForXml(_: IContext): IXmlableObject { return { _attr: this._attr, diff --git a/src/file/xml-components/index.ts b/src/file/xml-components/index.ts index 9ad7572069..0555576e01 100644 --- a/src/file/xml-components/index.ts +++ b/src/file/xml-components/index.ts @@ -1,3 +1,11 @@ +/** + * XML Components module for building WordprocessingML document structure. + * + * This module provides the foundational infrastructure for constructing XML elements + * that make up DOCX files. These are the base building blocks used throughout the library. + * + * @module + */ export * from "./xml-component"; export * from "./attributes"; export * from "./default-attributes"; diff --git a/src/file/xml-components/initializable-xml-component.ts b/src/file/xml-components/initializable-xml-component.ts index c9d0ef4373..7d9cfadcee 100644 --- a/src/file/xml-components/initializable-xml-component.ts +++ b/src/file/xml-components/initializable-xml-component.ts @@ -1,6 +1,44 @@ +/** + * Initializable XML Component module. + * + * This module provides a base class for XML components that can be initialized + * from another component's state, useful for component reuse and composition. + * + * @module + */ import { XmlComponent } from "@file/xml-components"; +/** + * XML component that can be initialized from another component. + * + * InitializableXmlComponent extends XmlComponent to support copying the internal + * state (root array) from another component. This is useful when you need to + * create a new component that shares or extends the children of an existing component. + * + * @example + * ```typescript + * class MyElement extends InitializableXmlComponent { + * constructor(init?: MyElement) { + * super("w:myElement", init); + * // If init is provided, this.root is copied from init + * // Otherwise, this.root is an empty array + * } + * } + * + * const element1 = new MyElement(); + * element1.addChildElement(new TextRun("Hello")); + * + * const element2 = new MyElement(element1); + * // element2 now has the same children as element1 + * ``` + */ export abstract class InitializableXmlComponent extends XmlComponent { + /** + * Creates a new InitializableXmlComponent. + * + * @param rootKey - The XML element name + * @param initComponent - Optional component to copy children from + */ public constructor(rootKey: string, initComponent?: InitializableXmlComponent) { super(rootKey); diff --git a/src/file/xml-components/simple-elements.ts b/src/file/xml-components/simple-elements.ts index 842c6f9093..fb65d04cab 100644 --- a/src/file/xml-components/simple-elements.ts +++ b/src/file/xml-components/simple-elements.ts @@ -1,17 +1,47 @@ +/** + * Simple XML element types for common WordprocessingML patterns. + * + * This module provides reusable element classes for common XML patterns in OOXML, + * such as boolean elements, string values, number values, and empty elements. + * These are building blocks used throughout the library. + * + * @module + */ import { AttributeData, AttributePayload, Attributes, NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { PositiveUniversalMeasure, hpsMeasureValue } from "@util/values"; -// This represents element type CT_OnOff, which indicate a boolean value. -// -// A value of 1 or true specifies that the property shall be explicitly applied. -// This is the default value for this attribute, and is implied when the parent -// element is present, but this attribute is omitted. -// A value of 0 or false specifies that the property shall be explicitly turned off. -// -// -// -// +/** + * XML element representing a boolean on/off value (CT_OnOff). + * + * This element type is used throughout WordprocessingML to represent boolean properties. + * A value of true (or 1) means the property is enabled. A value of false (or 0) means + * it is explicitly disabled. When the value is true, the attribute is often omitted. + * + * OOXML Reference: + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * // Bold enabled (w:val omitted when true) + * new OnOffElement("w:b", true); + * // Generates: + * + * // Bold explicitly disabled + * new OnOffElement("w:b", false); + * // Generates: + * ``` + */ export class OnOffElement extends XmlComponent { + /** + * Creates an OnOffElement. + * + * @param name - The XML element name (e.g., "w:b", "w:i") + * @param val - The boolean value (defaults to true) + */ public constructor(name: string, val: boolean | undefined = true) { super(name); if (val !== true) { @@ -20,40 +50,112 @@ export class OnOffElement extends XmlComponent { } } -// This represents element type CT_HpsMeasure, which indicate an unsigned int or a measurement with unit. -// -// -// -// - -// -// -// - +/** + * XML element representing a half-point size measurement (CT_HpsMeasure). + * + * HpsMeasure elements are used for font sizes and other measurements in WordprocessingML. + * Values can be specified as numbers (interpreted as half-points) or with explicit units. + * + * OOXML Reference: + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * // Font size of 24 half-points (12pt) + * new HpsMeasureElement("w:sz", 24); + * // Generates: + * + * // Using explicit units + * new HpsMeasureElement("w:sz", "12pt"); + * ``` + */ export class HpsMeasureElement extends XmlComponent { + /** + * Creates an HpsMeasureElement. + * + * @param name - The XML element name + * @param val - The measurement value (number in half-points or string with units) + */ public constructor(name: string, val: number | PositiveUniversalMeasure) { super(name); this.root.push(new Attributes({ val: hpsMeasureValue(val) })); } } -// This represents element type CT_String, which indicate a string value. -// -// +/** + * XML element representing an empty element (CT_Empty). + * + * EmptyElement creates self-closing XML tags with no attributes or content. + * + * OOXML Reference: + * ```xml + * + * ``` + * + * @example + * ```typescript + * new EmptyElement("w:noProof"); + * // Generates: + * ``` + */ export class EmptyElement extends XmlComponent {} -// This represents element type CT_Empty, which indicate aan empty element. -// -// -// -// +/** + * XML element with a string value attribute (CT_String). + * + * StringValueElement creates elements with a single "w:val" attribute + * containing a string value. + * + * OOXML Reference: + * ```xml + * + * + * + * ``` + * + * @example + * ```typescript + * new StringValueElement("w:style", "Heading1"); + * // Generates: + * ``` + */ export class StringValueElement extends XmlComponent { + /** + * Creates a StringValueElement. + * + * @param name - The XML element name + * @param val - The string value + */ public constructor(name: string, val: string) { super(name); this.root.push(new Attributes({ val })); } } +/** + * Creates a string element using the builder pattern. + * + * This is an alternative to StringValueElement that uses BuilderElement + * for more explicit attribute naming. + * + * @param name - The XML element name + * @param value - The string value + * @returns An XmlComponent with the string value + * + * @example + * ```typescript + * createStringElement("w:pStyle", "Heading1"); + * // Generates: + * ``` + */ export const createStringElement = (name: string, value: string): XmlComponent => new BuilderElement({ name, @@ -62,41 +164,131 @@ export const createStringElement = (name: string, value: string): XmlComponent = }, }); -// This represents various number element types. +/** + * XML element with a numeric value attribute. + * + * NumberValueElement creates elements with a single "w:val" attribute + * containing a numeric value. + * + * @example + * ```typescript + * new NumberValueElement("w:ilvl", 2); + * // Generates: + * ``` + */ export class NumberValueElement extends XmlComponent { + /** + * Creates a NumberValueElement. + * + * @param name - The XML element name + * @param val - The numeric value + */ public constructor(name: string, val: number) { super(name); this.root.push(new Attributes({ val })); } } +/** + * XML element with a string enum value attribute. + * + * StringEnumValueElement is similar to StringValueElement but uses a generic + * type parameter to enforce type safety for enum values. + * + * @example + * ```typescript + * type AlignmentType = "left" | "center" | "right"; + * new StringEnumValueElement("w:jc", "center"); + * // Generates: + * ``` + */ export class StringEnumValueElement extends XmlComponent { + /** + * Creates a StringEnumValueElement. + * + * @param name - The XML element name + * @param val - The enum value + */ public constructor(name: string, val: T) { super(name); this.root.push(new Attributes({ val })); } } -// Simple nodes containing text. -// -// new StringContainer("hello", "world") -// world +/** + * XML element containing text content. + * + * StringContainer creates elements with text content (not attributes). + * This is used for elements where the value is the text node content + * rather than an attribute. + * + * @example + * ```typescript + * new StringContainer("w:author", "John Doe"); + * // Generates: John Doe + * ``` + */ export class StringContainer extends XmlComponent { + /** + * Creates a StringContainer. + * + * @param name - The XML element name + * @param val - The text content + */ public constructor(name: string, val: string) { super(name); this.root.push(val); } } +/** + * Flexible XML element builder with explicit attribute and child configuration. + * + * BuilderElement provides a structured way to create XML elements with typed + * attributes and children. It uses the NextAttributeComponent pattern for + * explicit attribute key-value mapping. + * + * @example + * ```typescript + * // Element with attributes + * new BuilderElement({ + * name: "w:spacing", + * attributes: { + * before: { key: "w:before", value: 240 }, + * after: { key: "w:after", value: 120 } + * } + * }); + * // Generates: + * + * // Element with children + * new BuilderElement({ + * name: "w:pPr", + * children: [ + * new StringValueElement("w:pStyle", "Heading1") + * ] + * }); + * ``` + */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type export class BuilderElement extends XmlComponent { + /** + * Creates a BuilderElement with the specified configuration. + * + * @param config - Element configuration + * @param config.name - The XML element name + * @param config.attributes - Optional attributes with explicit key-value pairs + * @param config.children - Optional child elements + */ public constructor({ name, attributes, children, }: { + /** The XML element name. */ readonly name: string; + /** Optional attributes with explicit key-value pairs. */ readonly attributes?: AttributePayload; + /** Optional child elements. */ readonly children?: readonly XmlComponent[]; }) { super(name); diff --git a/src/file/xml-components/xml-component.ts b/src/file/xml-components/xml-component.ts index 152a182376..ba0f6dcf38 100644 --- a/src/file/xml-components/xml-component.ts +++ b/src/file/xml-components/xml-component.ts @@ -1,8 +1,9 @@ /** - * XML Component module for docx library. + * XML Component module for the docx library. * - * This module provides the base XmlComponent class that all - * WordprocessingML elements extend from. + * This module provides the core XmlComponent class that all WordprocessingML elements + * extend from. XmlComponent manages the conversion of component trees into XML structures + * that can be serialized into DOCX files. * * @module */ @@ -11,6 +12,10 @@ import { IXmlableObject } from "./xmlable-object"; /** * Empty object singleton used for empty XML elements. + * + * This sealed object is used to generate self-closing XML tags when an element + * has no children or attributes. + * * @internal */ export const EMPTY_OBJECT = Object.seal({}); @@ -18,28 +23,75 @@ export const EMPTY_OBJECT = Object.seal({}); /** * Base class for all XML components in WordprocessingML documents. * - * XmlComponent provides the infrastructure for building XML trees - * that are serialized into the document.xml and other parts of - * the DOCX package. + * XmlComponent provides the infrastructure for building XML element trees + * that are serialized into document.xml and other parts of the DOCX package. + * It manages a collection of child components and handles the conversion to + * the intermediate object format used by the xml serialization library. + * + * @example + * ```typescript + * // Creating a custom XML component + * class MyElement extends XmlComponent { + * constructor(text: string) { + * super("w:myElement"); + * this.root.push(new Attributes({ val: text })); + * } + * } + * + * const element = new MyElement("Hello"); + * // When serialized: + * ``` */ export abstract class XmlComponent extends BaseXmlComponent { + /** + * Array of child components, text nodes, and attributes. + * + * This array forms the content of the XML element. It can contain other + * XmlComponents, string values (text nodes), or attribute components. + */ // eslint-disable-next-line functional/prefer-readonly-type, @typescript-eslint/no-explicit-any protected root: (BaseXmlComponent | string | any)[]; + /** + * Creates a new XmlComponent. + * + * @param rootKey - The XML element name (e.g., "w:p", "w:r", "w:t") + */ public constructor(rootKey: string) { super(rootKey); this.root = new Array(); } - // This method is called by the formatter to get the XML representation of this component. - // It is called recursively for all child components. - // It is a serializer to be used in the xml library. - // https://www.npmjs.com/package/xml - // Child components can override this method to customize the XML representation, or execute side effects. + /** + * Prepares this component and its children for XML serialization. + * + * This method is called by the Formatter to convert the component tree into + * an object structure compatible with the xml library (https://www.npmjs.com/package/xml). + * It recursively processes all children and handles special cases like + * attribute-only elements and empty elements. + * + * The method can be overridden by subclasses to customize XML representation + * or execute side effects during serialization (e.g., creating relationships). + * + * @param context - The serialization context containing document state + * @returns The XML-serializable object, or undefined to exclude from output + * + * @example + * ```typescript + * // Override to add custom serialization logic + * prepForXml(context: IContext): IXmlableObject | undefined { + * // Custom logic here + * return super.prepForXml(context); + * } + * ``` + */ public prepForXml(context: IContext): IXmlableObject | undefined { + // Push this component onto the stack for context-aware processing // Mutating the stack is required for performance reasons // eslint-disable-next-line functional/immutable-data context.stack.push(this); + + // Recursively prepare all children for serialization const children = this.root .map((comp) => { if (comp instanceof BaseXmlComponent) { @@ -49,20 +101,27 @@ export abstract class XmlComponent extends BaseXmlComponent { }) .filter((comp) => comp !== undefined); // Exclude undefined + // Pop this component from the stack // eslint-disable-next-line functional/immutable-data context.stack.pop(); - // If we only have a single IXmlableObject in our children array and it - // represents our attributes, use the object itself as our children to - // avoid an unneeded XML close element. - // Additionally, if the array is empty, use an empty object as our - // children in order to get an empty XML element generated. + + // Optimization: If we only have a single IXmlableObject in our children array + // and it represents attributes, use the object itself as our children to + // avoid an unneeded XML close element (generates instead + // of ). + // Additionally, if the array is empty, use an empty object to generate + // a self-closing XML element. return { [this.rootKey]: children.length ? (children.length === 1 && children[0]?._attr ? children[0] : children) : EMPTY_OBJECT, }; } /** + * Adds a child element to this component. + * * @deprecated Do not use this method. It is only used internally by the library. It will be removed in a future version. + * @param child - The child component or text string to add + * @returns This component (for chaining) */ public addChildElement(child: XmlComponent | string): XmlComponent { this.root.push(child); @@ -72,15 +131,41 @@ export abstract class XmlComponent extends BaseXmlComponent { } /** - * XML component that is excluded from output if empty. + * XML component that is excluded from output if it has no meaningful content. * - * IgnoreIfEmptyXmlComponent is useful for optional elements that - * should only appear in the XML if they contain children. + * IgnoreIfEmptyXmlComponent is useful for optional container elements that + * should only appear in the XML if they contain children or attributes. + * If the element would be empty, it returns undefined instead, causing it + * to be excluded from the output. + * + * @example + * ```typescript + * class OptionalContainer extends IgnoreIfEmptyXmlComponent { + * constructor(items?: Item[]) { + * super("w:container"); + * if (items) { + * items.forEach(item => this.root.push(item)); + * } + * } + * } + * + * const container1 = new OptionalContainer([item1, item2]); + * // Renders: ... + * + * const container2 = new OptionalContainer(); + * // Renders: nothing (excluded from output) + * ``` */ export abstract class IgnoreIfEmptyXmlComponent extends XmlComponent { + /** + * Prepares the component for XML serialization, excluding it if empty. + * + * @param context - The serialization context + * @returns The XML-serializable object, or undefined if empty + */ public prepForXml(context: IContext): IXmlableObject | undefined { const result = super.prepForXml(context); - // Ignore the object if its falsey or is an empty object (would produce + // Ignore the object if it's falsey or is an empty object (would produce // an empty XML element if allowed to be included in the output). if (result && (typeof result[this.rootKey] !== "object" || Object.keys(result[this.rootKey]).length)) { return result; diff --git a/src/file/xml-components/xmlable-object.ts b/src/file/xml-components/xmlable-object.ts index f1fcf93510..3893422ba2 100644 --- a/src/file/xml-components/xmlable-object.ts +++ b/src/file/xml-components/xmlable-object.ts @@ -1,5 +1,34 @@ +/** + * XML-serializable object types for the docx library. + * + * This module defines the core types used for representing XML structures + * in an object format that can be serialized using the xml library. + * + * @module + */ + +/** + * Attributes for an XML element. + * + * Maps attribute names to their values. Attribute values can be strings, + * numbers, or booleans, which will be converted to strings in the final XML. + */ export type IXmlAttribute = Readonly>; +/** + * Object that can be serialized to XML. + * + * This interface represents the intermediate object structure used by the xml library + * to generate the final XML output. Objects typically have a structure like: + * ``` + * { + * "w:elementName": { + * _attr: { "w:attribute": "value" }, + * // child elements or text + * } + * } + * ``` + */ // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style, @typescript-eslint/consistent-type-definitions export interface IXmlableObject extends Record { // readonly _attr?: IXmlAttribute; diff --git a/src/index.ts b/src/index.ts index 7598917d72..26c9bea1c4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,37 @@ +/** + * Main entry point for the docx library. + * + * This module provides a declarative API for creating .docx files that works + * in both Node.js and browser environments. The library generates documents + * compliant with the OOXML (Office Open XML) specification. + * + * The primary export is the `Document` class (internally named `File`), which + * serves as the main entry point for creating Word documents. + * + * @module + * + * @example + * ```typescript + * import { Document, Paragraph, TextRun, Packer } from "docx"; + * + * // Create a document + * const doc = new Document({ + * sections: [{ + * children: [ + * new Paragraph({ + * children: [ + * new TextRun({ text: "Hello World", bold: true }), + * ], + * }), + * ], + * }], + * }); + * + * // Export to buffer + * const buffer = await Packer.toBuffer(doc); + * ``` + */ + // Internally, the wrapper is a 'File', but export to the end user as a 'Document' // Use of 'File' also works export { File as Document } from "./file"; diff --git a/src/patcher/content-types-manager.ts b/src/patcher/content-types-manager.ts index 8829c3349b..8a9a4e8f4f 100644 --- a/src/patcher/content-types-manager.ts +++ b/src/patcher/content-types-manager.ts @@ -1,7 +1,29 @@ +/** + * Content types manager for OOXML [Content_Types].xml management. + * + * @module + */ import { Element } from "xml-js"; import { getFirstLevelElements } from "./util"; +/** + * Appends a content type definition to the [Content_Types].xml structure. + * + * The [Content_Types].xml file declares the MIME types for all file extensions + * in the OOXML package. This function adds a new content type if it doesn't + * already exist, ensuring that newly added media files are properly declared. + * + * @param element - The [Content_Types].xml root element + * @param contentType - The MIME type (e.g., "image/png") + * @param extension - The file extension (e.g., "png") + * + * @example + * ```typescript + * appendContentType(contentTypesElement, "image/png", "png"); + * appendContentType(contentTypesElement, "image/jpeg", "jpg"); + * ``` + */ export const appendContentType = (element: Element, contentType: string, extension: string): void => { const relationshipElements = getFirstLevelElements(element, "Types"); diff --git a/src/patcher/from-docx.ts b/src/patcher/from-docx.ts index ae1f428557..cc82c7cd28 100644 --- a/src/patcher/from-docx.ts +++ b/src/patcher/from-docx.ts @@ -1,3 +1,11 @@ +/** + * Document patching module for modifying existing .docx files. + * + * This module provides functionality to patch existing Word documents by replacing + * placeholder text with new content while preserving the original document structure. + * + * @module + */ import JSZip from "jszip"; import { Element, js2xml } from "xml-js"; @@ -18,47 +26,107 @@ import { appendRelationship, getNextRelationshipIndex } from "./relationship-man import { replacer } from "./replacer"; import { toJson } from "./util"; +/** + * Supported input data types for document patching. + * + * The patcher can accept documents in various formats including buffers, + * arrays, and streams. + */ // eslint-disable-next-line functional/prefer-readonly-type export type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream | JSZip; +/** + * Patch type enumeration. + * + * Determines how the replacement content should be inserted into the document. + */ export const PatchType = { + /** Replace entire file-level elements (e.g., whole paragraphs) */ DOCUMENT: "file", + /** Replace content within paragraphs (inline replacement) */ PARAGRAPH: "paragraph", } as const; +/** + * Patch definition for paragraph-level replacement. + * + * Replaces placeholder text with inline content (runs, hyperlinks, etc.) + * while preserving the surrounding paragraph structure. + */ type ParagraphPatch = { + /** Indicates this is a paragraph-level patch */ readonly type: typeof PatchType.PARAGRAPH; + /** Content to insert (runs, hyperlinks, images, etc.) */ readonly children: readonly ParagraphChild[]; }; +/** + * Patch definition for document-level replacement. + * + * Replaces placeholder text with block-level content (entire paragraphs, tables, etc.). + */ type FilePatch = { + /** Indicates this is a document-level patch */ readonly type: typeof PatchType.DOCUMENT; + /** Content to insert (paragraphs, tables, etc.) */ readonly children: readonly FileChild[]; }; +/** + * Internal type for tracking image relationships that need to be added. + */ type IImageRelationshipAddition = { + /** XML file path where the image is used */ readonly key: string; + /** Media data for the images */ readonly mediaDatas: readonly IMediaData[]; }; +/** + * Internal type for tracking hyperlink relationships that need to be added. + */ type IHyperlinkRelationshipAddition = { + /** XML file path where the hyperlink is used */ readonly key: string; + /** Hyperlink relationship details */ readonly hyperlink: { readonly id: string; readonly link: string }; }; +/** + * Union type representing all patch types. + */ export type IPatch = ParagraphPatch | FilePatch; +/** + * Output format types for patched documents. + */ export type PatchDocumentOutputType = OutputType; +/** + * Options for patching a document. + * + * @property outputType - Desired output format (buffer, blob, string, etc.) + * @property data - The input document to patch + * @property patches - Map of placeholder keys to patch definitions + * @property keepOriginalStyles - Whether to preserve original text formatting + * @property placeholderDelimiters - Custom delimiter characters for placeholders + * @property recursive - Whether to search for multiple occurrences of placeholders + */ export type PatchDocumentOptions = { + /** Output format type */ readonly outputType: T; + /** Input document data */ readonly data: InputDataType; + /** Mapping of placeholder keys to patch content */ readonly patches: Readonly>; + /** Preserve original formatting of replaced text (default: true) */ readonly keepOriginalStyles?: boolean; + /** Custom placeholder delimiters (default: {{ and }}) */ readonly placeholderDelimiters?: Readonly<{ readonly start: string; readonly end: string; }>; + /** Search for multiple occurrences after patching (default: true) */ readonly recursive?: boolean; }; @@ -78,6 +146,39 @@ const compareByteArrays = (a: Uint8Array, b: Uint8Array): boolean => { return true; }; +/** + * Patches an existing .docx document by replacing placeholders with new content. + * + * This function opens an existing Word document, searches for placeholder text + * (e.g., {{name}}), and replaces it with the provided content while preserving + * the original document structure and optionally the original formatting. + * + * @param options - Configuration options for patching + * @returns A promise resolving to the patched document in the specified output format + * + * @example + * ```typescript + * // Patch with paragraph content + * const buffer = await patchDocument({ + * outputType: "nodebuffer", + * data: templateBuffer, + * patches: { + * name: { + * type: PatchType.PARAGRAPH, + * children: [new TextRun({ text: "John Doe", bold: true })], + * }, + * }, + * }); + * + * // Patch with custom delimiters + * const buffer = await patchDocument({ + * outputType: "nodebuffer", + * data: templateBuffer, + * patches: { ... }, + * placeholderDelimiters: { start: "<<", end: ">>" }, + * }); + * ``` + */ export const patchDocument = async ({ outputType, data, diff --git a/src/patcher/index.ts b/src/patcher/index.ts index 786e57341f..86845f8f06 100644 --- a/src/patcher/index.ts +++ b/src/patcher/index.ts @@ -1,2 +1,7 @@ +/** + * Patcher module exports. + * + * @module + */ export * from "./from-docx"; export * from "./patch-detector"; diff --git a/src/patcher/paragraph-split-inject.ts b/src/patcher/paragraph-split-inject.ts index 28aa12621d..71b2053bea 100644 --- a/src/patcher/paragraph-split-inject.ts +++ b/src/patcher/paragraph-split-inject.ts @@ -1,3 +1,8 @@ +/** + * Paragraph split and inject utilities for run-level text replacement. + * + * @module + */ import { Element } from "xml-js"; import { createTextElementContents, patchSpaceAttribute } from "./util"; @@ -9,6 +14,24 @@ export class TokenNotFoundError extends Error { } } +/** + * Finds the index of the run element containing a specific token. + * + * Searches through all run (w:r) elements in a paragraph to find which one + * contains the specified token text. This is used to locate where new content + * should be injected during replacement operations. + * + * @param paragraphElement - The paragraph element to search + * @param token - The token text to find + * @returns The index of the run element containing the token + * @throws Error if the token is not found in any run + * + * @example + * ```typescript + * const index = findRunElementIndexWithToken(paragraph, "ɵ"); + * // Returns the index of the run containing the split token + * ``` + */ export const findRunElementIndexWithToken = (paragraphElement: Element, token: string): number => { for (let i = 0; i < (paragraphElement.elements ?? []).length; i++) { const element = paragraphElement.elements![i]; @@ -30,6 +53,25 @@ export const findRunElementIndexWithToken = (paragraphElement: Element, token: s throw new TokenNotFoundError(token); }; +// cspell:words Helloɵworld + +/** + * Splits a run element at a token position into left and right parts. + * + * Divides a run element at the location of a token, creating two separate + * runs. This allows new content to be injected between the split parts while + * preserving the original run's formatting properties. + * + * @param runElement - The run element to split + * @param token - The token text marking the split point + * @returns Object containing the left and right run elements + * + * @example + * ```typescript + * const { left, right } = splitRunElement(run, "ɵ"); + * // If run contains "Helloɵworld", left contains "Hello" and right contains "world" + * ``` + */ export const splitRunElement = (runElement: Element, token: string): { readonly left: Element; readonly right: Element } => { let splitIndex = 0; diff --git a/src/patcher/paragraph-token-replacer.ts b/src/patcher/paragraph-token-replacer.ts index 32eec3bbcc..9da04867aa 100644 --- a/src/patcher/paragraph-token-replacer.ts +++ b/src/patcher/paragraph-token-replacer.ts @@ -1,14 +1,48 @@ +/** + * Paragraph token replacer for substituting text within paragraph runs. + * + * @module + */ import { Element } from "xml-js"; import { IRenderedParagraphNode } from "./run-renderer"; import { createTextElementContents, patchSpaceAttribute } from "./util"; +/** + * Replacement modes for multi-run text replacement. + */ const ReplaceMode = { + /** Looking for the start of the replacement text */ START: 0, + /** Processing runs in the middle of the replacement text */ MIDDLE: 1, + /** Reached the end of the replacement text */ END: 2, } as const; +/** + * Replaces a token with replacement text within a paragraph's run elements. + * + * Handles the complex case where placeholder text may span multiple runs + * (text fragments) within a paragraph. Processes each run to replace the + * appropriate portion of the token, handling start, middle, and end sections. + * + * @param paragraphElement - The paragraph XML element to modify + * @param renderedParagraph - Pre-rendered paragraph structure with text positions + * @param originalText - The token text to replace (e.g., "{{name}}") + * @param replacementText - The text to replace it with (often a split token) + * @returns The modified paragraph element + * + * @example + * ```typescript + * replaceTokenInParagraphElement({ + * paragraphElement, + * renderedParagraph, + * originalText: "{{placeholder}}", + * replacementText: "ɵ", + * }); + * ``` + */ export const replaceTokenInParagraphElement = ({ paragraphElement, renderedParagraph, diff --git a/src/patcher/patch-detector.ts b/src/patcher/patch-detector.ts index eba608e258..e1d1700897 100644 --- a/src/patcher/patch-detector.ts +++ b/src/patcher/patch-detector.ts @@ -1,14 +1,48 @@ +/** + * Patch detector for discovering placeholders in document templates. + * + * @module + */ import JSZip from "jszip"; import { InputDataType } from "./from-docx"; import { traverse } from "./traverser"; import { toJson } from "./util"; +/** + * Options for patch detection. + * + * @property data - The document template to scan for placeholders + */ type PatchDetectorOptions = { readonly data: InputDataType; }; -/** Detects which patches are needed/present in a template */ +/** + * Detects all placeholders present in a document template. + * + * Scans through all XML content in a .docx file to find placeholder text + * enclosed in delimiters (default: {{placeholder}}). This is useful for + * discovering what patches a template expects before performing replacement. + * + * @param options - Patch detector configuration + * @returns Array of placeholder keys found in the document + * + * @example + * ```typescript + * const placeholders = await patchDetector({ data: templateBuffer }); + * // Returns: ["name", "date", "address"] if template contains {{name}}, {{date}}, {{address}} + * + * // Use detected placeholders to create patches + * const patches = {}; + * placeholders.forEach(key => { + * patches[key] = { + * type: PatchType.PARAGRAPH, + * children: [new TextRun(getUserData(key))], + * }; + * }); + * ``` + */ export const patchDetector = async ({ data }: PatchDetectorOptions): Promise => { const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data); const patches = new Set(); @@ -25,6 +59,12 @@ export const patchDetector = async ({ data }: PatchDetectorOptions): Promise { const pattern = /(?<=\{\{).+?(?=\}\})/gs; return text.match(pattern) ?? []; diff --git a/src/patcher/relationship-manager.ts b/src/patcher/relationship-manager.ts index 295c540662..296b7c5d16 100644 --- a/src/patcher/relationship-manager.ts +++ b/src/patcher/relationship-manager.ts @@ -1,14 +1,40 @@ +/** + * Relationship manager for OOXML .rels file management. + * + * @module + */ import { Element } from "xml-js"; import { RelationshipType, TargetModeType } from "@file/relationships/relationship/relationship"; import { getFirstLevelElements } from "./util"; +/** + * Extracts the numeric ID from a relationship ID string. + * + * @param relationshipId - Relationship ID in format "rId123" + * @returns The numeric portion of the ID + */ const getIdFromRelationshipId = (relationshipId: string): number => { const output = parseInt(relationshipId.substring(3), 10); return isNaN(output) ? 0 : output; }; +/** + * Determines the next available relationship ID number. + * + * Scans all existing relationships and returns the next sequential ID number + * to use when adding a new relationship. + * + * @param relationships - The relationships XML element + * @returns The next available relationship ID number + * + * @example + * ```typescript + * const nextId = getNextRelationshipIndex(relationshipsElement); + * // If highest existing ID is rId5, returns 6 + * ``` + */ export const getNextRelationshipIndex = (relationships: Element): number => { const relationshipElements = getFirstLevelElements(relationships, "Relationships"); @@ -19,6 +45,29 @@ export const getNextRelationshipIndex = (relationships: Element): number => { ); }; +/** + * Appends a new relationship to a .rels file structure. + * + * Relationships define connections between parts of an OOXML package, + * such as linking documents to images, hyperlinks, or other resources. + * + * @param relationships - The relationships XML element + * @param id - The relationship ID (number or string) + * @param type - The relationship type URI + * @param target - The target path or URI + * @param targetMode - Optional target mode (Internal or External) + * @returns The updated relationship elements array + * + * @example + * ```typescript + * appendRelationship( + * relationshipsElement, + * 6, + * "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + * "media/image1.png" + * ); + * ``` + */ export const appendRelationship = ( relationships: Element, id: number | string, diff --git a/src/patcher/replacer.ts b/src/patcher/replacer.ts index 5a4e503da6..c6989f465b 100644 --- a/src/patcher/replacer.ts +++ b/src/patcher/replacer.ts @@ -1,3 +1,8 @@ +/** + * Replacer module for performing placeholder substitution in XML structures. + * + * @module + */ import xml from "xml"; import { Element } from "xml-js"; @@ -14,11 +19,31 @@ const formatter = new Formatter(); const SPLIT_TOKEN = "ɵ"; +/** + * Result of a replacement operation. + * + * @property element - The modified XML element + * @property didFindOccurrence - Whether a placeholder occurrence was found and replaced + */ type IReplacerResult = { readonly element: Element; readonly didFindOccurrence: boolean; }; +/** + * Replaces placeholder text in XML with new content from a patch. + * + * This function locates placeholder text within the XML structure and performs + * the appropriate replacement based on the patch type (document or paragraph level). + * It handles splitting runs, preserving styles, and injecting the new content. + * + * @param json - The XML element structure to search + * @param patch - The patch definition containing replacement content + * @param patchText - The placeholder text to find (e.g., "{{name}}") + * @param context - The document context for formatting + * @param keepOriginalStyles - Whether to preserve original text formatting + * @returns Result containing the modified element and whether a replacement occurred + */ export const replacer = ({ json, patch, diff --git a/src/patcher/run-renderer.ts b/src/patcher/run-renderer.ts index af0482cc4c..73fb4864d8 100644 --- a/src/patcher/run-renderer.ts +++ b/src/patcher/run-renderer.ts @@ -1,7 +1,20 @@ +/** + * Run renderer for extracting text content from OOXML paragraph structures. + * + * @module + */ import { Element } from "xml-js"; import { ElementWrapper } from "./traverser"; +/** + * Rendered representation of a paragraph with its text content and structure. + * + * @property text - Complete text content of the paragraph + * @property runs - Array of run elements within the paragraph + * @property index - Position index of the paragraph among siblings + * @property pathToParagraph - Path indices from root to this paragraph + */ export type IRenderedParagraphNode = { readonly text: string; readonly runs: readonly IRenderedRunNode[]; @@ -9,22 +22,59 @@ export type IRenderedParagraphNode = { readonly pathToParagraph: readonly number[]; }; +/** + * Character position range within a paragraph. + */ type StartAndEnd = { + /** Starting character index */ readonly start: number; + /** Ending character index */ readonly end: number; }; +/** + * Text fragment within a run element. + */ type IParts = { + /** Text content of this fragment */ readonly text: string; + /** Position index within the run */ readonly index: number; } & StartAndEnd; +/** + * Rendered representation of a run element (w:r) with its text content. + * + * @property text - Complete text content of the run + * @property parts - Array of text fragments (w:t elements) within the run + * @property index - Position index of the run within the paragraph + * @property start - Starting character index in the paragraph + * @property end - Ending character index in the paragraph + */ export type IRenderedRunNode = { readonly text: string; readonly parts: readonly IParts[]; readonly index: number; } & StartAndEnd; +/** + * Renders a paragraph element into a structured representation with text content. + * + * Extracts all text content from a paragraph (w:p) element by processing its + * run (w:r) children. Calculates character positions for each text fragment + * to enable precise text replacement operations. + * + * @param node - The paragraph element wrapper to render + * @returns Rendered paragraph with text content, runs, and position information + * @throws Error if the node is not a paragraph element + * + * @example + * ```typescript + * const rendered = renderParagraphNode(paragraphWrapper); + * console.log(rendered.text); // "Hello World" + * console.log(rendered.runs.length); // 2 (if text is in separate runs) + * ``` + */ export const renderParagraphNode = (node: ElementWrapper): IRenderedParagraphNode => { if (node.element.name !== "w:p") { throw new Error(`Invalid node type: ${node.element.name}`); diff --git a/src/patcher/traverser.ts b/src/patcher/traverser.ts index 30f647fd95..b283b446cc 100644 --- a/src/patcher/traverser.ts +++ b/src/patcher/traverser.ts @@ -1,7 +1,19 @@ +/** + * XML traverser for searching paragraph content in OOXML documents. + * + * @module + */ import { Element } from "xml-js"; import { IRenderedParagraphNode, renderParagraphNode } from "./run-renderer"; +/** + * Wrapper for XML elements that tracks position in the document tree. + * + * @property element - The XML element + * @property index - Position index among siblings + * @property parent - Parent element wrapper (undefined for root) + */ export type ElementWrapper = { readonly element: Element; readonly index: number; @@ -15,6 +27,22 @@ const elementsToWrapper = (wrapper: ElementWrapper): readonly ElementWrapper[] = parent: wrapper, })) ?? []; +/** + * Traverses an XML document tree to find and render all paragraphs. + * + * Uses breadth-first search to walk through the XML structure, identifying + * all paragraph elements (w:p) and rendering their text content along with + * positional information. + * + * @param node - The root XML element to traverse + * @returns Array of rendered paragraph nodes with text content and positions + * + * @example + * ```typescript + * const paragraphs = traverse(documentElement); + * paragraphs.forEach(p => console.log(p.text)); + * ``` + */ export const traverse = (node: Element): readonly IRenderedParagraphNode[] => { let renderedParagraphs: readonly IRenderedParagraphNode[] = []; @@ -42,5 +70,22 @@ export const traverse = (node: Element): readonly IRenderedParagraphNode[] => { return renderedParagraphs; }; +/** + * Finds all paragraphs containing specific text. + * + * Traverses the document and filters paragraphs to find those containing + * the specified text string. Useful for locating placeholder text that + * needs to be replaced. + * + * @param node - The root XML element to search + * @param text - The text to search for + * @returns Array of paragraph nodes containing the text + * + * @example + * ```typescript + * const matches = findLocationOfText(documentElement, "{{name}}"); + * // Returns all paragraphs containing "{{name}}" + * ``` + */ export const findLocationOfText = (node: Element, text: string): readonly IRenderedParagraphNode[] => traverse(node).filter((p) => p.text.includes(text)); diff --git a/src/patcher/util.ts b/src/patcher/util.ts index 17159ebb12..a76489fd90 100644 --- a/src/patcher/util.ts +++ b/src/patcher/util.ts @@ -1,3 +1,8 @@ +/** + * Utility functions for XML manipulation in document patching. + * + * @module + */ import xml from "xml"; import { Element, xml2js } from "xml-js"; @@ -6,11 +11,42 @@ import { Text } from "@file/paragraph/run/run-components/text"; const formatter = new Formatter(); +/** + * Converts XML string to JSON element structure. + * + * Parses XML text into a JavaScript object representation that can be + * manipulated programmatically. Preserves spaces between elements for + * accurate text handling. + * + * @param xmlData - The XML string to parse + * @returns Parsed XML as an Element object + * + * @example + * ```typescript + * const element = toJson('Hello'); + * ``` + */ export const toJson = (xmlData: string): Element => { const xmlObj = xml2js(xmlData, { compact: false, captureSpacesBetweenElements: true }) as Element; return xmlObj; }; +/** + * Creates text element contents from a text string. + * + * Generates the XML element structure for a text node (w:t) by formatting + * a Text component and extracting its element contents. Used when creating + * new text runs during replacement operations. + * + * @param text - The text content to wrap in element structure + * @returns Array of XML elements representing the text + * + * @example + * ```typescript + * const elements = createTextElementContents("Hello World"); + * // Returns XML elements for Hello World + * ``` + */ // eslint-disable-next-line functional/prefer-readonly-type export const createTextElementContents = (text: string): Element[] => { const textJson = toJson(xml(formatter.format(new Text({ text })))); @@ -18,6 +54,22 @@ export const createTextElementContents = (text: string): Element[] => { return textJson.elements![0].elements ?? []; }; +/** + * Adds xml:space="preserve" attribute to an element. + * + * The xml:space attribute instructs XML processors to preserve whitespace + * in the element's content. This is important when text contains leading + * or trailing spaces that must be maintained. + * + * @param element - The element to patch + * @returns New element with xml:space attribute added + * + * @example + * ```typescript + * const patched = patchSpaceAttribute(textElement); + * // Adds xml:space="preserve" to maintain whitespace + * ``` + */ export const patchSpaceAttribute = (element: Element): Element => ({ ...element, attributes: { @@ -25,6 +77,22 @@ export const patchSpaceAttribute = (element: Element): Element => ({ }, }); +/** + * Retrieves first-level child elements by parent element name. + * + * Finds the first element with the specified name and returns its children. + * Used to access collections like relationship elements or content type definitions. + * + * @param relationships - The parent XML element to search + * @param id - The element name to find + * @returns Array of child elements + * + * @example + * ```typescript + * const rels = getFirstLevelElements(relationshipsXml, "Relationships"); + * // Returns array of Relationship elements + * ``` + */ // eslint-disable-next-line functional/prefer-readonly-type export const getFirstLevelElements = (relationships: Element, id: string): Element[] => relationships.elements?.filter((e) => e.name === id)[0].elements ?? []; diff --git a/src/tests/utility.ts b/src/tests/utility.ts index bfc0d90299..1a7b33a1a9 100644 --- a/src/tests/utility.ts +++ b/src/tests/utility.ts @@ -1,3 +1,17 @@ +/** + * Test utility module. + * + * Provides helper functions for unit tests. + * + * @module + * @internal + */ + +/** + * Utility class for test helpers. + * + * @internal + */ export class Utility { // eslint-disable-next-line @typescript-eslint/no-explicit-any public static jsonify(obj: object): any { diff --git a/src/util/convenience-functions.ts b/src/util/convenience-functions.ts index 6c9eb3e388..7c51da1c3f 100644 --- a/src/util/convenience-functions.ts +++ b/src/util/convenience-functions.ts @@ -1,36 +1,181 @@ +/** + * Convenience utility functions for unit conversion and unique ID generation. + * + * This module provides: + * - Unit conversion functions (millimeters/inches to TWIP) + * - Unique ID generators for various document elements + * - Hash and UUID generation utilities + * + * @module + */ import hash from "hash.js"; import { customAlphabet, nanoid } from "nanoid/non-secure"; -// Twip - twentieths of a point +/** + * Converts millimeters to TWIP (twentieths of a point). + * + * TWIP is a common unit in Office Open XML where 1 inch = 1440 TWIP. + * + * @param millimeters - The measurement in millimeters to convert + * @returns The equivalent measurement in TWIP + * + * @example + * ```typescript + * const width = convertMillimetersToTwip(25.4); // Returns 1440 (1 inch) + * ``` + */ export const convertMillimetersToTwip = (millimeters: number): number => Math.floor((millimeters / 25.4) * 72 * 20); +/** + * Converts inches to TWIP (twentieths of a point). + * + * TWIP is a common unit in Office Open XML where 1 inch = 1440 TWIP. + * + * @param inches - The measurement in inches to convert + * @returns The equivalent measurement in TWIP + * + * @example + * ```typescript + * const width = convertInchesToTwip(1); // Returns 1440 + * ``` + */ export const convertInchesToTwip = (inches: number): number => Math.floor(inches * 72 * 20); +/** + * A function that generates unique sequential numeric IDs. + */ export type UniqueNumericIdCreator = () => number; +/** + * Creates a unique numeric ID generator with sequential numbering. + * + * @param initial - The initial value to start counting from (default: 0) + * @returns A function that returns incrementing numbers on each call + * + * @example + * ```typescript + * const idGen = uniqueNumericIdCreator(10); + * console.log(idGen()); // 11 + * console.log(idGen()); // 12 + * console.log(idGen()); // 13 + * ``` + */ export const uniqueNumericIdCreator = (initial = 0): UniqueNumericIdCreator => { let currentCount = initial; return () => ++currentCount; }; +/** + * Creates a unique numeric ID generator for abstract numbering definitions. + * + * Abstract numbering definitions define the appearance and behavior of lists. + * + * @returns A function that generates sequential IDs starting from 1 + * + * @example + * ```typescript + * const idGen = abstractNumUniqueNumericIdGen(); + * const id = idGen(); // Returns 1 + * ``` + */ export const abstractNumUniqueNumericIdGen = (): UniqueNumericIdCreator => uniqueNumericIdCreator(); -// Setting initial to 1 as we have numId = 1 for "default-bullet-numbering" +/** + * Creates a unique numeric ID generator for concrete numbering instances. + * + * Concrete numbering instances reference abstract numbering definitions and are + * used to apply numbering to paragraphs. Initial value is 1 because ID 1 is + * reserved for "default-bullet-numbering". + * + * @returns A function that generates sequential IDs starting from 2 + * + * @example + * ```typescript + * const idGen = concreteNumUniqueNumericIdGen(); + * const id = idGen(); // Returns 2 (1 is reserved) + * ``` + */ export const concreteNumUniqueNumericIdGen = (): UniqueNumericIdCreator => uniqueNumericIdCreator(1); +/** + * Creates a unique numeric ID generator for document properties. + * + * @returns A function that generates sequential IDs starting from 1 + * + * @example + * ```typescript + * const idGen = docPropertiesUniqueNumericIdGen(); + * const id = idGen(); // Returns 1 + * ``` + */ export const docPropertiesUniqueNumericIdGen = (): UniqueNumericIdCreator => uniqueNumericIdCreator(); +/** + * Creates a unique numeric ID generator for bookmarks. + * + * Bookmarks are used to mark specific locations in a document for navigation + * and cross-referencing. + * + * @returns A function that generates sequential IDs starting from 1 + * + * @example + * ```typescript + * const idGen = bookmarkUniqueNumericIdGen(); + * const id = idGen(); // Returns 1 + * ``` + */ export const bookmarkUniqueNumericIdGen = (): UniqueNumericIdCreator => uniqueNumericIdCreator(); +/** + * Generates a unique lowercase alphanumeric ID using nanoid. + * + * The ID is suitable for use as a relationship ID or other unique identifier + * within a document. + * + * @returns A unique lowercase string ID + */ export const uniqueId = (): string => nanoid().toLowerCase(); +/** + * Generates a SHA-1 hash of the provided data. + * + * Useful for generating deterministic IDs based on content, such as for + * image references or revision tracking. + * + * @param data - The data to hash (Buffer, string, Uint8Array, or ArrayBuffer) + * @returns A hexadecimal string representation of the SHA-1 hash + * + * @example + * ```typescript + * const hash = hashedId("Hello World"); // Returns "0a4d55a8d778e5022fab701977c5d840bbc486d0" + * ``` + */ export const hashedId = (data: Buffer | string | Uint8Array | ArrayBuffer): string => hash .sha1() .update(data instanceof ArrayBuffer ? new Uint8Array(data) : data) .digest("hex"); +/** + * Generates a random hexadecimal string of specified length. + * + * @param count - The number of hexadecimal characters to generate + * @returns A random hexadecimal string + */ const generateUuidPart = (count: number): string => customAlphabet("1234567890abcdef", count)(); + +/** + * Generates a UUID v4-style unique identifier. + * + * The UUID follows the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + * + * @returns A UUID string + * + * @example + * ```typescript + * const uuid = uniqueUuid(); // Returns "a3bb189e-8bf9-3888-9912-ace4e6543002" + * ``` + */ export const uniqueUuid = (): string => `${generateUuidPart(8)}-${generateUuidPart(4)}-${generateUuidPart(4)}-${generateUuidPart(4)}-${generateUuidPart(12)}`; diff --git a/src/util/index.ts b/src/util/index.ts index 98e69718b9..b5675ded35 100644 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -1,3 +1,11 @@ +/** + * Utility functions and types for the docx library. + * + * This module re-exports all utility functions, type definitions, and validators + * used throughout the library for unit conversion, ID generation, and value validation. + * + * @module + */ export * from "./convenience-functions"; export * from "./values"; export type * from "./output-type"; diff --git a/src/util/output-type.ts b/src/util/output-type.ts index a2d19d3c44..d9bc27e59b 100644 --- a/src/util/output-type.ts +++ b/src/util/output-type.ts @@ -1,18 +1,66 @@ +/** + * Output type definitions for document generation. + * + * This module defines the various output formats supported when generating + * .docx files. These types correspond to JSZip's output formats. + * + * @module + */ + /* v8 ignore start */ // Simply type definitions. Can ignore testing and coverage -// From JSZip + +/** + * Maps output type names to their corresponding TypeScript types. + * + * This type is used to provide type-safe document generation where the output + * format determines the return type. Based on JSZip's output types. + * + * @example + * ```typescript + * // Generate as base64 string + * const doc: OutputByType["base64"] = await packer.toBase64(document); + * + * // Generate as Buffer (Node.js) + * const doc: OutputByType["nodebuffer"] = await packer.toBuffer(document); + * + * // Generate as Blob (browser) + * const doc: OutputByType["blob"] = await packer.toBlob(document); + * ``` + */ export type OutputByType = { + /** Base64-encoded string representation */ readonly base64: string; + /** UTF-8 string representation */ // eslint-disable-next-line id-denylist readonly string: string; + /** Text string representation */ readonly text: string; + /** Binary string representation */ readonly binarystring: string; + /** Array of numbers (0-255) representing bytes */ readonly array: readonly number[]; + /** Uint8Array (typed array) representation */ readonly uint8array: Uint8Array; + /** ArrayBuffer representation */ readonly arraybuffer: ArrayBuffer; + /** Blob representation (browser environments) */ readonly blob: Blob; + /** Node.js Buffer representation */ readonly nodebuffer: Buffer; }; +/** + * Valid output type identifiers. + * + * Use these string literals to specify the desired output format when + * generating documents. + * + * @example + * ```typescript + * const outputType: OutputType = "base64"; + * const doc = await packer.generate(document, { type: outputType }); + * ``` + */ export type OutputType = keyof OutputByType; /* v8 ignore stop */ diff --git a/src/util/types.ts b/src/util/types.ts index 3817bcf818..56a577d213 100644 --- a/src/util/types.ts +++ b/src/util/types.ts @@ -1,7 +1,27 @@ -// -// -// -// -// -// -export type InsetMode = "auto" | "custom"; // VML only type +/** + * Type definitions for OOXML specification values. + * + * This module contains TypeScript type definitions that correspond to + * specific types defined in the OOXML specification, primarily for VML + * (Vector Markup Language) elements. + * + * @module + */ + +/** + * Inset mode for VML text boxes. + * + * Specifies whether inset values are automatically calculated or custom-defined. + * This type is used exclusively in VML (Vector Markup Language) elements. + * + * - `auto` - Inset values are automatically calculated + * - `custom` - Inset values are explicitly specified + * + * Reference: ST_InsetMode in OOXML specification + * + * @example + * ```typescript + * const insetMode: InsetMode = "auto"; + * ``` + */ +export type InsetMode = "auto" | "custom"; diff --git a/src/util/values.ts b/src/util/values.ts index fb88758aa3..7e586e43e2 100644 --- a/src/util/values.ts +++ b/src/util/values.ts @@ -1,39 +1,101 @@ -// Runtime checks and cleanup for value types in the spec that aren't easily expressed through our type system. -// These will help us to prevent silent failures and corrupted documents. -// -// Most of the rest of the types not defined here are either aliases of existing types or enumerations. -// Enumerations should probably just be implemented as enums, with instructions to end-users, without a runtime check. +/** + * Runtime validation and type conversion functions for OOXML specification values. + * + * This module provides runtime checks and cleanup for value types in the OOXML spec + * that aren't easily expressed through the TypeScript type system alone. These + * validators help prevent silent failures and corrupted documents by enforcing + * spec-compliant values at runtime. + * + * @module + */ -// -?[0-9]+(\.[0-9]+)?(mm|cm|in|pt|pc|pi) +/** + * A measurement value with optional sign and unit suffix. + * + * Supports units: mm (millimeters), cm (centimeters), in (inches), + * pt (points), pc (picas), pi (picas). + * + * Pattern: `-?[0-9]+(\.[0-9]+)?(mm|cm|in|pt|pc|pi)` + * + * @example + * ```typescript + * const measure: UniversalMeasure = "10.5mm"; + * const negative: UniversalMeasure = "-5pt"; + * ``` + */ export type UniversalMeasure = `${"-" | ""}${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`; -// -// -// -// -// +/** + * A positive measurement value with unit suffix. + * + * Same as UniversalMeasure but restricted to positive values only. + * + * Reference: ST_PositiveUniversalMeasure in OOXML specification + * + * @example + * ```typescript + * const measure: PositiveUniversalMeasure = "10.5mm"; + * ``` + */ export type PositiveUniversalMeasure = `${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`; -// -// -// -// -// +/** + * A percentage value with optional sign. + * + * Pattern: `-?[0-9]+(\.[0-9]+)?%` + * + * Reference: ST_Percentage in OOXML specification + * + * @example + * ```typescript + * const percent: Percentage = "50%"; + * const negative: Percentage = "-10.5%"; + * ``` + */ export type Percentage = `${"-" | ""}${number}%`; -// -// -// -// -// +/** + * A positive percentage value. + * + * Same as Percentage but restricted to positive values only. + * + * Reference: ST_PositivePercentage in OOXML specification + * + * @example + * ```typescript + * const percent: PositivePercentage = "50%"; + * ``` + */ export type PositivePercentage = `${number}%`; -// Only applies to VmlTextbox so far +/** + * A relative measurement value using em or ex units. + * + * Used in VML text boxes for font-relative measurements. + * + * @example + * ```typescript + * const measure: RelativeMeasure = "2em"; + * const negative: RelativeMeasure = "-0.5ex"; + * ``` + */ export type RelativeMeasure = `${"-" | ""}${number}${"em" | "ex"}`; -// -// -// +/** + * Validates and converts a number to an integer (decimal number). + * + * Reference: ST_DecimalNumber in OOXML specification + * + * @param val - The number to validate and convert + * @returns The floored integer value + * @throws Error if the value is NaN + * + * @example + * ```typescript + * const num = decimalNumber(10.7); // Returns 10 + * const negative = decimalNumber(-5.3); // Returns -5 + * ``` + */ export const decimalNumber = (val: number): number => { if (isNaN(val)) { throw new Error(`Invalid value '${val}' specified. Must be an integer.`); @@ -41,9 +103,21 @@ export const decimalNumber = (val: number): number => { return Math.floor(val); }; -// -// -// +/** + * Validates and converts a number to a positive integer (unsigned decimal number). + * + * Reference: ST_UnsignedDecimalNumber in OOXML specification + * + * @param val - The number to validate and convert + * @returns The floored positive integer value + * @throws Error if the value is NaN or negative + * + * @example + * ```typescript + * const num = unsignedDecimalNumber(10.7); // Returns 10 + * const invalid = unsignedDecimalNumber(-5); // Throws Error + * ``` + */ export const unsignedDecimalNumber = (val: number): number => { const value = decimalNumber(val); if (value < 0) { @@ -52,11 +126,24 @@ export const unsignedDecimalNumber = (val: number): number => { return value; }; -// The xsd:hexBinary type represents binary data as a sequence of binary octets. -// It uses hexadecimal encoding, where each binary octet is a two-character hexadecimal number. -// Lowercase and uppercase letters A through F are permitted. For example, 0FB8 and 0fb8 are two -// equal xsd:hexBinary representations consisting of two octets. -// http://www.datypic.com/sc/xsd/t-xsd_hexBinary.html +/** + * Validates and normalizes a hexadecimal binary value. + * + * The xsd:hexBinary type represents binary data as a sequence of binary octets + * using hexadecimal encoding, where each binary octet is a two-character + * hexadecimal number. Both lowercase and uppercase letters A-F are permitted. + * + * @param val - The hexadecimal string to validate + * @param length - The expected length in bytes (not characters) + * @returns The validated hexadecimal string + * @throws Error if the value is not a valid hex string of the expected length + * + * @example + * ```typescript + * hexBinary("0FB8", 2); // Valid: 2 bytes = 4 characters + * hexBinary("ABC", 2); // Invalid: wrong length + * ``` + */ const hexBinary = (val: string, length: number): string => { const expectedLength = length * 2; if (val.length !== expectedLength || isNaN(Number(`0x${val}`))) { @@ -65,49 +152,90 @@ const hexBinary = (val: string, length: number): string => { return val; }; -// -// -// -// -// +/** + * Validates a long hexadecimal number (4 bytes / 8 characters). + * + * Reference: ST_LongHexNumber in OOXML specification + * + * @param val - The hexadecimal string to validate + * @returns The validated hexadecimal string + * @throws Error if the value is not a valid 8-character hex string + * + * @example + * ```typescript + * const hex = longHexNumber("ABCD1234"); // Valid + * ``` + */ export const longHexNumber = (val: string): string => hexBinary(val, 4); -// -// -// -// -// +/** + * Validates a short hexadecimal number (2 bytes / 4 characters). + * + * Reference: ST_ShortHexNumber in OOXML specification + * + * @param val - The hexadecimal string to validate + * @returns The validated hexadecimal string + * @throws Error if the value is not a valid 4-character hex string + * + * @example + * ```typescript + * const hex = shortHexNumber("AB12"); // Valid + * ``` + */ export const shortHexNumber = (val: string): string => hexBinary(val, 2); -// -// -// -// -// +/** + * Validates a single-byte hexadecimal number (1 byte / 2 characters). + * + * Reference: ST_UcharHexNumber in OOXML specification + * + * @param val - The hexadecimal string to validate + * @returns The validated hexadecimal string + * @throws Error if the value is not a valid 2-character hex string + * + * @example + * ```typescript + * const hex = uCharHexNumber("FF"); // Valid + * ``` + */ export const uCharHexNumber = (val: string): string => hexBinary(val, 1); -// -// -// -// -// - -// -// -// -// -// +/** + * Normalizes a universal measure value by parsing and reformatting. + * + * Ensures the numeric portion is properly formatted while preserving the unit. + * + * Reference: ST_UniversalMeasure in OOXML specification + * + * @param val - The universal measure string to normalize + * @returns The normalized universal measure + * + * @example + * ```typescript + * const measure = universalMeasureValue("10.500mm"); // Returns "10.5mm" + * ``` + */ export const universalMeasureValue = (val: UniversalMeasure): UniversalMeasure => { const unit = val.slice(-2); const amount = val.substring(0, val.length - 2); return `${Number(amount)}${unit}` as UniversalMeasure; }; -// -// -// -// -// +/** + * Validates and normalizes a positive universal measure value. + * + * Reference: ST_PositiveUniversalMeasure in OOXML specification + * + * @param val - The positive universal measure string to validate + * @returns The normalized positive universal measure + * @throws Error if the value is negative + * + * @example + * ```typescript + * const measure = positiveUniversalMeasureValue("10.5mm"); // Valid + * const invalid = positiveUniversalMeasureValue("-5mm"); // Throws Error + * ``` + */ export const positiveUniversalMeasureValue = (val: PositiveUniversalMeasure): PositiveUniversalMeasure => { const value = universalMeasureValue(val); if (parseFloat(value) < 0) { @@ -116,20 +244,26 @@ export const positiveUniversalMeasureValue = (val: PositiveUniversalMeasure): Po return value as PositiveUniversalMeasure; }; -// -// -// -// -// -// -// -// - -// -// -// -// -// +/** + * Validates and normalizes a hexadecimal color value. + * + * Accepts either "auto" or a 6-character RGB hex value (with or without # prefix). + * The # prefix is commonly used but technically invalid in OOXML, so it is stripped + * for strict compliance. + * + * Reference: ST_HexColor in OOXML specification + * + * @param val - The color value to validate ("auto" or hex color) + * @returns The normalized color value + * @throws Error if the hex color is invalid + * + * @example + * ```typescript + * const color1 = hexColorValue("auto"); // Returns "auto" + * const color2 = hexColorValue("FF0000"); // Returns "FF0000" + * const color3 = hexColorValue("#00FF00"); // Returns "00FF00" (# stripped) + * ``` + */ export const hexColorValue = (val: string): string => { if (val === "auto") { return val; @@ -140,52 +274,116 @@ export const hexColorValue = (val: string): string => { return hexBinary(color, 3); }; -// -// -// +/** + * Validates a signed TWIP measurement value. + * + * Accepts either a universal measure string or a numeric TWIP value. + * + * Reference: ST_SignedTwipsMeasure in OOXML specification + * + * @param val - The measurement value (universal measure or number) + * @returns The normalized measurement value + * + * @example + * ```typescript + * const measure1 = signedTwipsMeasureValue("10mm"); + * const measure2 = signedTwipsMeasureValue(1440); // 1 inch in TWIP + * ``` + */ export const signedTwipsMeasureValue = (val: UniversalMeasure | number): UniversalMeasure | number => typeof val === "string" ? universalMeasureValue(val) : decimalNumber(val); -// -// -// +/** + * Validates a half-point (HPS) measurement value. + * + * Accepts either a positive universal measure string or a positive number. + * HPS (half-points) are commonly used for font sizes. + * + * Reference: ST_HpsMeasure in OOXML specification + * + * @param val - The measurement value (positive universal measure or number) + * @returns The normalized measurement value + * + * @example + * ```typescript + * const fontSize1 = hpsMeasureValue("12pt"); + * const fontSize2 = hpsMeasureValue(24); // 12pt in half-points + * ``` + */ export const hpsMeasureValue = (val: PositiveUniversalMeasure | number): string | number => typeof val === "string" ? positiveUniversalMeasureValue(val) : unsignedDecimalNumber(val); -// -// -// +/** + * Validates a signed half-point (HPS) measurement value. + * + * Accepts either a universal measure string or a numeric value. + * + * Reference: ST_SignedHpsMeasure in OOXML specification + * + * @param val - The measurement value (universal measure or number) + * @returns The normalized measurement value + * + * @example + * ```typescript + * const spacing1 = signedHpsMeasureValue("6pt"); + * const spacing2 = signedHpsMeasureValue(-12); // Negative spacing + * ``` + */ export const signedHpsMeasureValue = (val: UniversalMeasure | number): string | number => typeof val === "string" ? universalMeasureValue(val) : decimalNumber(val); -// -// -// +/** + * Validates a positive TWIP measurement value. + * + * Accepts either a positive universal measure string or a positive number. + * + * Reference: ST_TwipsMeasure in OOXML specification + * + * @param val - The measurement value (positive universal measure or number) + * @returns The normalized measurement value + * + * @example + * ```typescript + * const width1 = twipsMeasureValue("25.4mm"); + * const width2 = twipsMeasureValue(1440); // 1 inch in TWIP + * ``` + */ export const twipsMeasureValue = (val: PositiveUniversalMeasure | number): PositiveUniversalMeasure | number => typeof val === "string" ? positiveUniversalMeasureValue(val) : unsignedDecimalNumber(val); -// -// -// -// -// +/** + * Normalizes a percentage value by parsing and reformatting. + * + * Reference: ST_Percentage in OOXML specification + * + * @param val - The percentage string to normalize + * @returns The normalized percentage + * + * @example + * ```typescript + * const percent = percentageValue("50.000%"); // Returns "50%" + * ``` + */ export const percentageValue = (val: Percentage): Percentage => { const percent = val.substring(0, val.length - 1); return `${Number(percent)}%`; }; -// -// -// - -// -// -// - -// -// -// - +/** + * Validates a measurement value that can be expressed as a number, percentage, or universal measure. + * + * Reference: ST_MeasurementOrPercent in OOXML specification + * + * @param val - The measurement value (number, percentage, or universal measure) + * @returns The normalized measurement value + * + * @example + * ```typescript + * const measure1 = measurementOrPercentValue(100); // Unqualified number + * const measure2 = measurementOrPercentValue("50%"); // Percentage + * const measure3 = measurementOrPercentValue("10mm"); // Universal measure + * ``` + */ export const measurementOrPercentValue = (val: number | Percentage | UniversalMeasure): number | UniversalMeasure | Percentage => { if (typeof val === "number") { return decimalNumber(val); @@ -196,34 +394,54 @@ export const measurementOrPercentValue = (val: number | Percentage | UniversalMe return universalMeasureValue(val as UniversalMeasure); }; -// -// -// +/** + * Validates an eighth-point measurement value. + * + * Eighth-points are used for fine-grained measurements in text formatting. + * + * Reference: ST_EighthPointMeasure in OOXML specification + * + * @param val - The measurement value in eighth-points + * @returns The validated positive integer value + * + * @example + * ```typescript + * const measure = eighthPointMeasureValue(16); // 2 points + * ``` + */ export const eighthPointMeasureValue = unsignedDecimalNumber; -// -// -// +/** + * Validates a point measurement value. + * + * Reference: ST_PointMeasure in OOXML specification + * + * @param val - The measurement value in points + * @returns The validated positive integer value + * + * @example + * ```typescript + * const fontSize = pointMeasureValue(12); // 12pt + * ``` + */ export const pointMeasureValue = unsignedDecimalNumber; -// -// -// -// -// http://www.datypic.com/sc/xsd/t-xsd_dateTime.html -// The type xsd:dateTime represents a specific date and time in the format -/* cspell:disable-next-line */ -// CCYY-MM-DDThh:mm:ss.sss, which is a concatenation of the date and time forms, -// separated by a literal letter "T". All of the same rules that apply to the date -// and time types are applicable to xsd:dateTime as well. -// -// An optional time zone expression may be added at the end of the value. -// The letter Z is used to indicate Coordinated Universal Time (UTC). All other time -// zones are represented by their difference from Coordinated Universal Time in the -// format +hh:mm, or -hh:mm. These values may range from -14:00 to 14:00. For example, -// US Eastern Standard Time, which is five hours behind UTC, is represented as -05:00. -// If no time zone value is present, it is considered unknown; it is not assumed to be UTC. -// -// Luckily, js has this format built in already. See: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString +// cspell:words CCYY +/** + * Converts a JavaScript Date object to an ISO 8601 date-time string. + * + * The format is CCYY-MM-DDThh:mm:ss.sssZ where T is a literal and Z indicates UTC. + * This matches the xsd:dateTime format required by OOXML. + * + * Reference: ST_DateTime in OOXML specification + * + * @param val - The Date object to convert + * @returns An ISO 8601 formatted date-time string + * + * @example + * ```typescript + * const now = new Date(); + * const timestamp = dateTimeValue(now); // Returns "2024-01-15T10:30:00.000Z" + * ``` + */ export const dateTimeValue = (val: Date): string => val.toISOString();