diff --git a/docs/usage/table-of-contents.md b/docs/usage/table-of-contents.md index eb0c0c734f..c29d01e6a1 100644 --- a/docs/usage/table-of-contents.md +++ b/docs/usage/table-of-contents.md @@ -152,6 +152,36 @@ const doc = new Document({ A heading of your own can be a paragraph style with `run: { bold: true }` instead, listed in the table with `stylesWithLevels`. +### Tab leader + +By default, dots fill the space between each entry and its page number. To fill it with something else, or leave it empty, set `tabLeader`, as the "Tab leader" of Word's Table of Contents dialog does: `"none"`, `"hyphen"`, `"underscore"` or `"middleDot"`, or `"dot"`, the default. These are the values of `LeaderType`. + +Word keeps it when it updates the table, whether it updates the page numbers only or the entire table. + +```ts live +import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx"; + +const doc = new Document({ + features: { + updateFields: true, + }, + sections: [ + { + children: [ + new TableOfContents("Contents", { + hyperlink: true, + headingStyleRange: "1-2", + tabLeader: "none", + }), + new Paragraph({ text: "Introduction", heading: HeadingLevel.HEADING_1, pageBreakBefore: true }), + new Paragraph({ text: "Background", heading: HeadingLevel.HEADING_2 }), + new Paragraph({ text: "Method", heading: HeadingLevel.HEADING_1, pageBreakBefore: true }), + ], + }, + ], +}); +``` + ## Table of Contents Options Here is the list of all options that you can use to generate your tables of contents: @@ -246,6 +276,7 @@ These options control the TOC structure rather than field switches: | --------------- | ---------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | contentChildren | `(XmlComponent \| string)[]` | `[]` | Additional content to include inside the TOC between the field begin and end markers. Useful for placeholder entries. | | beginDirty | `boolean` | `true` | When `true`, marks the field as needing update, prompting Word to regenerate the TOC on open. When it isn't given and the document has `pageNumbers`, the field isn't marked, so Word doesn't ask (see [Layout](usage/layout.md#opening-the-document-in-word)). | +| tabLeader | `LeaderType` | `"dot"` | What fills the space between each entry and its page number: `"dot"`, `"hyphen"`, `"underscore"`, `"middleDot"` or `"none"` (see [Tab leader](#tab-leader)). | ### Example with contentChildren diff --git a/src/file/table-of-contents/heading-entries.spec.ts b/src/file/table-of-contents/heading-entries.spec.ts index dd825e16e8..80b2b4d608 100644 --- a/src/file/table-of-contents/heading-entries.spec.ts +++ b/src/file/table-of-contents/heading-entries.spec.ts @@ -519,6 +519,27 @@ describe("Table of contents filled in from the headings", () => { expect(widthsIn(body)).to.deep.equal([9026, 10240]); }); + it("fills the space before the page numbers with dots, or with the tabLeader given, as Word's tab leader", () => { + const leadersIn = (tree: readonly IXmlableObject[]): readonly unknown[] => + elementsNamed(tree, "w:sdt").map( + (table) => attributesOf(elementsNamed(table, "w:tabs")[0]["w:tabs"][0], "w:tab")?.["w:leader"], + ); + const body = bodyOf({ + sections: [ + { + children: [ + new TableOfContents("Dots", { headingStyleRange: "1-3" }), + new TableOfContents("None", { headingStyleRange: "1-3", tabLeader: "none" }), + new TableOfContents("Hyphens", { headingStyleRange: "1-3", tabLeader: "hyphen" }), + heading("One"), + ], + }, + ], + }); + + expect(leadersIn(body)).to.deep.equal(["dot", "none", "hyphen"]); + }); + it("bookmarks a heading once for several tables of contents, with the same bookmark each time the document is written", () => { const file = new File({ sections: [ diff --git a/src/file/table-of-contents/heading-entries.ts b/src/file/table-of-contents/heading-entries.ts index 7d1136bb5e..7346f5e33b 100644 --- a/src/file/table-of-contents/heading-entries.ts +++ b/src/file/table-of-contents/heading-entries.ts @@ -13,7 +13,15 @@ * @module */ import type { BookmarkListNumber } from "@file/document/body/page-numbers"; -import { BookmarkEnd, BookmarkStart, InternalHyperlink, PageReference, Paragraph, type ParagraphChild } from "@file/paragraph"; +import { + BookmarkEnd, + BookmarkStart, + InternalHyperlink, + PageReference, + Paragraph, + type ParagraphChild, + type TabStopDefinition, +} from "@file/paragraph"; import { Run, Tab, TextRun } from "@file/paragraph/run"; import { createBegin, createBeginDirtyWithoutPageNumbers, createEnd, createSeparate } from "@file/paragraph/run/field"; import type { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; @@ -33,6 +41,8 @@ export type HeadingEntriesOptions = { readonly beginDirty?: boolean; /** The width, in twips, of the text in its section, where the page numbers are aligned */ readonly textWidth: number; + /** What fills the space before the page numbers */ + readonly tabLeader: TabStopDefinition["leader"]; }; /** @@ -420,7 +430,7 @@ const entryStyleOf = (level: number, styles: ReadonlyMap): /** The formatted content of a table of contents with its entries */ const contentOf = ( - { properties, beginDirty, textWidth }: HeadingEntriesOptions, + { properties, beginDirty, textWidth, tabLeader }: HeadingEntriesOptions, entries: readonly Entry[], styles: ReadonlyMap, context: IContext, @@ -453,7 +463,7 @@ const contentOf = ( ...(entry.listNumber?.separator === "tab" ? [{ type: "left" as const, position: numberTabStopOf(entry.level, entry.listNumber.width) }] : []), - { type: "right", position: textWidth, leader: "dot" }, + { type: "right", position: textWidth, leader: tabLeader }, ], children: [ ...(index === 0 diff --git a/src/file/table-of-contents/table-of-contents.spec.ts b/src/file/table-of-contents/table-of-contents.spec.ts index 493f419254..5bad850438 100644 --- a/src/file/table-of-contents/table-of-contents.spec.ts +++ b/src/file/table-of-contents/table-of-contents.spec.ts @@ -646,6 +646,25 @@ describe("Table of Contents", () => { expect(fldChar["w:fldChar"]._attr["w:dirty"]).to.equal(false); }); + it("should fill the space before the page numbers of cached entries with the tabLeader given", () => { + const toc = new TableOfContents("Table of Contents", { + cachedEntries: [ + { title: "One", level: 1, page: 1 }, + { title: "Two", level: 2, page: 2 }, + ], + tabLeader: "underscore", + }); + const tree = new Formatter().format(toc); + + const paragraphs = tree["w:sdt"][1]["w:sdtContent"]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rightTabs = paragraphs.map((paragraph: any) => paragraph["w:p"][0]["w:pPr"][1]["w:tabs"][1]["w:tab"]._attr); + expect(rightTabs).to.deep.equal([ + { "w:val": "right", "w:pos": 9025, "w:leader": "underscore" }, + { "w:val": "right", "w:pos": 9025, "w:leader": "underscore" }, + ]); + }); + it("should fill in an end paragraph if only one cached entry is provided", () => { const cachedEntries = [{ title: "Only Entry", level: 1, page: 1 }]; const toc = new TableOfContents("Table of Contents", { cachedEntries }); diff --git a/src/file/table-of-contents/table-of-contents.ts b/src/file/table-of-contents/table-of-contents.ts index 00db62c9df..d79d9eafe6 100644 --- a/src/file/table-of-contents/table-of-contents.ts +++ b/src/file/table-of-contents/table-of-contents.ts @@ -9,7 +9,7 @@ * @module */ import { FileChild } from "@file/file-child"; -import { InternalHyperlink, Paragraph, type TabStopDefinition } from "@file/paragraph"; +import { InternalHyperlink, LeaderType, Paragraph, type TabStopDefinition } from "@file/paragraph"; import { Run, Tab } from "@file/paragraph/run"; import { createEnd, createSeparate } from "@file/paragraph/run/field"; import { Text } from "@file/paragraph/run/run-components/text"; @@ -74,6 +74,7 @@ export class TableOfContents extends FileChild { contentChildren = [], cachedEntries = [], beginDirty, + tabLeader = LeaderType.DOT, ...properties }: ITableOfContentsOptions & { readonly contentChildren?: readonly (XmlComponent | string)[]; @@ -89,6 +90,12 @@ export class TableOfContents extends FileChild { * it is written, and doesn't ask. */ readonly beginDirty?: boolean; + /** + * What fills the space between an entry and its page number, such as dots or nothing, as the "Tab leader" of + * Word's Table of Contents dialog. Word keeps it when it updates the page numbers or the entire table. Default + * is dots. + */ + readonly tabLeader?: (typeof LeaderType)[keyof typeof LeaderType]; } = {}, ) { super("w:sdt"); @@ -124,7 +131,7 @@ export class TableOfContents extends FileChild { return new Paragraph({ style, - tabStops: this.getTabStopsForLevel(entry.level), + tabStops: this.getTabStopsForLevel(entry.level, tabLeader), children, }); }); @@ -160,7 +167,7 @@ export class TableOfContents extends FileChild { content.addChildElement(endParagraph); if (contentChildren.length === 0) { - this.fromHeadings = { properties, beginDirty }; + this.fromHeadings = { properties, beginDirty, tabLeader }; } } @@ -182,7 +189,11 @@ export class TableOfContents extends FileChild { return context.file?.Document?.View.Body.getSectionPropertiesFor(this)?.AvailableTextWidth ?? DEFAULT_AVAILABLE_WIDTH; } - private getTabStopsForLevel(level: number, pageWidth: number = 9025): readonly TabStopDefinition[] { + private getTabStopsForLevel( + level: number, + leader: TabStopDefinition["leader"], + pageWidth: number = 9025, + ): readonly TabStopDefinition[] { const levelSpace = 240; const levelPosition = pageWidth + 1 - (level - 1) * levelSpace; // TODO: should be equal to page width + 1 - level margin return [ @@ -193,7 +204,7 @@ export class TableOfContents extends FileChild { { type: "right", position: pageWidth, - leader: "dot", + leader, }, ]; }