diff --git a/demo/styles/theme-from-a-document.ts b/demo/styles/theme-from-a-document.ts new file mode 100644 index 0000000000..bd396fb77e --- /dev/null +++ b/demo/styles/theme-from-a-document.ts @@ -0,0 +1,63 @@ +// The theme of a document made in Word, read with readTheme, so text and tables in the theme's fonts and +// colors look as they do in that document. field-trip.docx has Office 2007's theme: Cambria for headings, Calibri for +// body text, and its blue, red and green accents. +// See docs/usage/themes.md. + +import * as fs from "fs"; +import { Document, HeadingLevel, Packer, Paragraph, ShadingType, Table, TableCell, TableRow, TextRun, WidthType, readTheme } from "docx"; + +const theme = readTheme(fs.readFileSync("./demo/assets/field-trip.docx")); + +const header = (text: string): TableCell => + new TableCell({ + shading: { type: ShadingType.CLEAR, fill: { theme: "accent1" } }, + children: [new Paragraph({ children: [new TextRun({ text, bold: true, color: { theme: "light1" } })] })], + }); + +const row = (cells: readonly string[], index: number): TableRow => + new TableRow({ + children: cells.map( + (text) => + new TableCell({ + // Banded rows, in the theme's first accent color, lighter by 80% + shading: index % 2 === 0 ? { type: ShadingType.CLEAR, fill: { theme: "accent1", lighter: 80 } } : undefined, + children: [new Paragraph(text)], + }), + ), + }); + +const doc = new Document({ + theme, + styles: { + default: { + document: { run: { font: { theme: "body" }, size: 22 } }, + heading1: { run: { font: { theme: "headings" }, size: 32, bold: true, color: { theme: "accent1", darker: 25 } } }, + }, + }, + sections: [ + { + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("The theme of a document made in Word")] }), + new Paragraph( + `This document has the theme of field-trip.docx, "${theme.name}", whose fonts and colors are those of Office 2007. The heading is in its font for headings, and the table in its first accent color.`, + ), + new Table({ + width: { size: 100, type: WidthType.PERCENTAGE }, + rows: [ + new TableRow({ tableHeader: true, children: [header("Stop"), header("Time")] }), + ...[ + ["Museum", "9:30"], + ["Park", "11:00"], + ["Lunch", "12:30"], + ["Back at school", "15:00"], + ].map(row), + ], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/docs/usage/styling-with-xml.md b/docs/usage/styling-with-xml.md index 7b820e180f..37b7b99882 100644 --- a/docs/usage/styling-with-xml.md +++ b/docs/usage/styling-with-xml.md @@ -78,7 +78,30 @@ const doc = new Document({ Styles made in Word often name the theme's fonts and colors rather than a font or a color: "(Headings)" is written as `w:asciiTheme="majorHAnsi"`, and "Accent 1" as `w:themeColor="accent1"`. Word looks them up in the document's theme, which is the one `docx` writes, not the theme of the document your `styles.xml` came from. It's Office's theme, with Calibri Light for headings and Calibri for body text, unless the [`theme`](usage/themes.md) option changes it. -To keep the fonts and colors of the document the styles came from, give its theme's fonts and colors in `theme`. They're in that document's `word/theme/theme1.xml`: the `typeface` of `a:latin` in `a:majorFont` is the font for headings, the one in `a:minorFont` is the font for body text, and `a:clrScheme` has the colors. +To keep the fonts and colors of the document the styles came from, give it that document's theme, read with [`readTheme`](usage/themes.md#the-theme-of-a-word-document-or-template). It reads the document itself, or its `word/theme/theme1.xml`: + +```ts live +import * as fs from "fs"; +import { Document, HeadingLevel, Paragraph, readTheme } from "docx"; + +const doc = new Document({ + externalStyles: fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8"), + // The theme of the document the styles came from. Here, that of another document made in Word, with Cambria for headings + theme: readTheme(fs.readFileSync("./demo/assets/field-trip.docx")), + sections: [ + { + children: [ + // The styles' Heading 1 is in the theme's sixth accent color, darker 25% + new Paragraph({ text: "A heading in the theme's accent 6", heading: HeadingLevel.HEADING_1 }), + // Their Normal style is in the theme's font for body text + new Paragraph("Body text in the theme's font for body text"), + ], + }, + ], +}); +``` + +Or give its theme's fonts and colors in `theme` yourself. They're in that document's `word/theme/theme1.xml`: the `typeface` of `a:latin` in `a:majorFont` is the font for headings, the one in `a:minorFont` is the font for body text, and `a:clrScheme` has the colors. ```ts live import { Document, HeadingLevel, Paragraph } from "docx"; diff --git a/docs/usage/themes.md b/docs/usage/themes.md index c29e5e80f5..ccabd3fed9 100644 --- a/docs/usage/themes.md +++ b/docs/usage/themes.md @@ -46,11 +46,11 @@ Colors and fonts that aren't given are Office's. ### Theme Options -| Property | Type | Notes | Description | -| -------- | --------------------- | -------- | --------------------------------------------------------------------------------------- | -| `name` | `string` | Optional | The theme's name, as Word shows it. Default is `"Office Theme"` | -| `colors` | `IThemeColorsOptions` | Optional | The theme's colors, each a 6-digit hex color such as `"4472C4"` | -| `fonts` | `IThemeFontsOptions` | Optional | `headings` and `body`: a font name, or `{ latin, eastAsia, complexScript }` for scripts | +| Property | Type | Notes | Description | +| -------- | --------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | `string` | Optional | The theme's name, as Word shows it. Default is `"Office Theme"` | +| `colors` | `IThemeColorsOptions` | Optional | The theme's colors, each a 6-digit hex color such as `"4472C4"` | +| `fonts` | `IThemeFontsOptions` | Optional | `headings` and `body`: a font name, or `{ latin, eastAsia, complexScript, scripts }` for other scripts. See [Fonts for other scripts](#fonts-for-other-scripts) | ### Theme Colors @@ -73,6 +73,79 @@ Colors and fonts that aren't given are Office's. +### Fonts for other scripts + +Each of the theme's fonts can have a font for East Asian text (`eastAsia`), a font for complex scripts such as Arabic and Hebrew (`complexScript`), and a font for each script of its own (`scripts`), by the script's [ISO 15924](https://en.wikipedia.org/wiki/ISO_15924) code, such as `Jpan` for Japanese, `Hans` for simplified Chinese or `Arab` for Arabic. Word uses them for text in those scripts that is in the theme's fonts. + +The fonts given in `scripts` take the place of Office's for those scripts, and Office's are kept for the others, as Office's theme has a font for each of about fifty scripts. + +```ts live +import { Document, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + theme: { + fonts: { + headings: { latin: "Georgia", scripts: { Jpan: "Yu Mincho" } }, + body: { latin: "Verdana", scripts: { Jpan: "Meiryo", Arab: "Tahoma" } }, + }, + }, + sections: [ + { + children: [ + new Paragraph({ children: [new TextRun({ text: "Body text, 本文", font: { theme: "body" } })] }), + new Paragraph({ children: [new TextRun({ text: "A heading, 見出し", font: { theme: "headings" } })] }), + ], + }, + ], +}); +``` + +## The theme of a Word document or template + +Styles made in Word, such as those of a template given in [`externalStyles`](usage/styling-with-xml.md), usually name the theme's fonts and colors rather than a font or a color: "(Headings)", or a table's shading in "Accent 5, Lighter 60%". They look as they did in Word only with the theme of the document they came from. `readTheme` reads that theme, to give `theme`: + +```ts live +import * as fs from "fs"; +import { Document, HeadingLevel, Paragraph, TextRun, readTheme } from "docx"; + +// A document made in Word, whose theme is Office 2007's: Cambria for headings, Calibri for body text, and blue accents +const theme = readTheme(fs.readFileSync("./demo/assets/field-trip.docx")); + +const doc = new Document({ + theme, + styles: { + default: { + heading1: { run: { font: { theme: "headings" }, size: 32, color: { theme: "accent1" } } }, + }, + }, + sections: [ + { + children: [ + new Paragraph({ + heading: HeadingLevel.HEADING_1, + children: [new TextRun("In the theme's font for headings, and accent 1")], + }), + new Paragraph({ + children: [ + new TextRun({ text: "Accent 2, in the font for body text", color: { theme: "accent2" }, font: { theme: "body" } }), + ], + }), + ], + }, + ], +}); +``` + +It reads: + +- a Word document or template (`.docx`, `.docm`, `.dotx` or `.dotm`), a PowerPoint presentation (`.pptx`), an Excel workbook (`.xlsx`) or an Office theme (`.thmx`), as bytes, such as a `Buffer`, a `Uint8Array` or an `ArrayBuffer`; +- the XML of a theme, such as a document's `word/theme/theme1.xml`, as text or bytes; +- the XML of colors or fonts that Word saves on their own, from **Design > Colors > Customize Colors** or **Design > Fonts > Customize Fonts**, as the theme's `colors` or `fonts`. + +It gives the options of `theme`: the theme's `name`, its `colors`, and its `fonts` for headings and body text, with their fonts for other scripts. Change them before giving them to `theme` if you like, such as `{ ...theme, colors: { ...theme.colors, accent1: "1F6F8B" } }`. The fills, lines and effects of the theme's shape styles are Office's in the new document, as they are for every theme `docx` writes. + +It throws for a file that isn't one of those, or that has no theme. + ## Text in the theme's fonts A run's or a style's `font` can be one of the theme's fonts: `{ theme: "headings" }` or `{ theme: "body" }`. It's the theme's font for every script, as Word's own styles use it. @@ -102,7 +175,7 @@ const doc = new Document({ }); ``` -The library's own styles don't use the theme's fonts, so text looks as it always has until a style or a run asks for them. Word's styles, such as those in `externalStyles` taken from a Word document, use them: Word's `Normal` style is in the theme's font for body text, and its headings in the font for headings. The theme is the one `docx` writes, not the theme of the document the styles came from, so give that theme's fonts and colors in `theme` to keep them. +The library's own styles don't use the theme's fonts, so text looks as it always has until a style or a run asks for them. Word's styles, such as those in `externalStyles` taken from a Word document, use them: Word's `Normal` style is in the theme's font for body text, and its headings in the font for headings. The theme is the one `docx` writes, not the theme of the document the styles came from, so give that document's theme with [`readTheme`](#the-theme-of-a-word-document-or-template) to keep its fonts and colors. ## Text, tables and borders in the theme's colors @@ -184,6 +257,12 @@ const doc = new Document({ ## Examples +### The theme of a Word document + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/styles/theme-from-a-document.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/styles/theme-from-a-document.ts_ + ### A theme of its own [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/styles/theme.ts ":include") diff --git a/src/file/theme/font-scheme.ts b/src/file/theme/font-scheme.ts index 3f423a405b..cc0796eab7 100644 --- a/src/file/theme/font-scheme.ts +++ b/src/file/theme/font-scheme.ts @@ -8,6 +8,7 @@ * * @module */ +// cspell:ignore Jpan import { BuilderElement, type XmlComponent } from "@file/xml-components"; /** @@ -22,6 +23,12 @@ export type IThemeFontOptions = { readonly eastAsia?: string; /** The font for complex scripts, such as Arabic and Hebrew. By default Word picks a font for each script */ readonly complexScript?: string; + /** + * The fonts for text in particular scripts, by the script's ISO 15924 code, such as `{ Jpan: "Meiryo", Arab: "Arial" }` + * for Japanese and Arabic text. They take the place of Office's fonts for those scripts, and Office's fonts are kept + * for the others + */ + readonly scripts?: Readonly>; }; /** @@ -121,9 +128,25 @@ const themeLatinFont = (use: keyof IThemeFontsOptions, fonts: IThemeFontsOptions return latin ?? OFFICE_FONTS[use].latin; }; +/** + * The font for each script of one of a theme's fonts: Office's, in Office's order, with those given in their place, and + * then the scripts Office has no font for, in the order given. + */ +const themeScriptFonts = ( + use: keyof IThemeFontsOptions, + scripts: Readonly> = {}, +): readonly (readonly [string, string])[] => { + const office = OFFICE_SCRIPT_FONTS.map(([script, headings, body = headings]): readonly [string, string] => [ + script, + scripts[script] ?? (use === "headings" ? headings : body), + ]); + const officeScripts = new Set(office.map(([script]) => script)); + return [...office, ...Object.entries(scripts).filter(([script]) => !officeScripts.has(script))]; +}; + const createFontCollection = (use: keyof IThemeFontsOptions, fonts: IThemeFontsOptions): XmlComponent => { const font = fonts[use]; - const { eastAsia = "", complexScript = "" } = typeof font === "object" ? font : {}; + const { eastAsia = "", complexScript = "", scripts } = typeof font === "object" ? font : {}; const latin = themeLatinFont(use, fonts); const office = OFFICE_FONTS[use]; return new BuilderElement({ @@ -133,13 +156,13 @@ const createFontCollection = (use: keyof IThemeFontsOptions, fonts: IThemeFontsO createTextFont("a:latin", latin, latin === office.latin ? office.panose : undefined), createTextFont("a:ea", eastAsia), createTextFont("a:cs", complexScript), - ...OFFICE_SCRIPT_FONTS.map( - ([script, headings, body = headings]) => + ...themeScriptFonts(use, scripts).map( + ([script, typeface]) => new BuilderElement<{ readonly script: string; readonly typeface: string }>({ name: "a:font", attributes: { script: { key: "script", value: script }, - typeface: { key: "typeface", value: use === "headings" ? headings : body }, + typeface: { key: "typeface", value: typeface }, }, }), ), diff --git a/src/file/theme/index.ts b/src/file/theme/index.ts index 02064d831c..8c09d7d01c 100644 --- a/src/file/theme/index.ts +++ b/src/file/theme/index.ts @@ -5,3 +5,4 @@ */ export * from "./theme"; export type { ThemeColor, ThemeColorName } from "./theme-color"; +export { readTheme } from "./read-theme"; diff --git a/src/file/theme/read-theme.spec.ts b/src/file/theme/read-theme.spec.ts new file mode 100644 index 0000000000..59ddbe5d4e --- /dev/null +++ b/src/file/theme/read-theme.spec.ts @@ -0,0 +1,284 @@ +/* eslint-disable @typescript-eslint/naming-convention -- The keys of objects here are paths of parts in a package */ +// cspell:ignore hlink Hlink purl oclc DRAWINGML Jpan +import { describe, expect, it } from "vitest"; + +import { Packer } from "@export/packer/packer"; +import { File } from "@file/file"; +import { encodeUtf8 } from "@util/convenience-functions"; +import { damaging, zip } from "tests/zip"; + +import { readTheme, readThemeColorValues, themePathOf } from "./read-theme"; + +const DRAWINGML = "http://schemas.openxmlformats.org/drawingml/2006/main"; +const RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships"; +const MAIN_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; +const THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"; + +const relationships = (...items: readonly (readonly [type: string, target: string])[]): string => + `${items + .map(([type, target], index) => ``) + .join("")}`; + +const themeXml = (themeElements: string, name = "Harbour"): string => + `${themeElements}`; + +const colorScheme = (colors: string): string => `${colors}`; + +const fontScheme = (headings: string, body: string): string => + `${headings}${body}`; + +const HARBOUR = themeXml( + colorScheme( + `` + + `` + + ``, + ) + + fontScheme( + `` + + ``, + ``, + ), +); + +const HARBOUR_OPTIONS = { + name: "Harbour", + colors: { dark2: "1B3A4B", accent1: "1F6F8B", hyperlink: "0563C1", followedHyperlink: "954F72" }, + fonts: { + headings: { latin: "Cambria", scripts: { Jpan: "游明朝", Arab: "Times New Roman" } }, + body: { latin: "Calibri", eastAsia: "Yu Gothic", complexScript: "Tahoma" }, + }, +}; + +describe("readTheme", () => { + it("should read a theme's name, colors and fonts from its XML", () => { + expect(readTheme(HARBOUR)).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should read the XML of a theme given as bytes, such as a file read from disk", () => { + const bytes = new TextEncoder().encode(`\uFEFF${HARBOUR}`); + expect(readTheme(bytes)).to.deep.equal(HARBOUR_OPTIONS); + expect(readTheme(bytes.buffer)).to.deep.equal(HARBOUR_OPTIONS); + // A view of part of a larger buffer, as Node's Buffer can be + const padded = new Uint8Array(bytes.length + 8); + padded.set(bytes, 4); + expect(readTheme(padded.subarray(4, 4 + bytes.length))).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should read the XML of a theme in UTF-16, which starts with its byte order mark", () => { + const xml = `\uFEFF${HARBOUR.replace('encoding="UTF-8"', 'encoding="UTF-16"')}`; + const codeUnits = [...Array(xml.length).keys()].map((index) => xml.charCodeAt(index)); + const littleEndian = new Uint8Array(codeUnits.flatMap((unit) => [unit % 0x100, Math.floor(unit / 0x100)])); + const bigEndian = new Uint8Array(codeUnits.flatMap((unit) => [Math.floor(unit / 0x100), unit % 0x100])); + expect(readTheme(littleEndian)).to.deep.equal(HARBOUR_OPTIONS); + expect(readTheme(bigEndian)).to.deep.equal(HARBOUR_OPTIONS); + expect( + readTheme( + zip({ + "_rels/.rels": relationships([MAIN_PART, "word/document.xml"]), + "word/_rels/document.xml.rels": relationships([THEME, "theme/theme1.xml"]), + "word/theme/theme1.xml": littleEndian, + }), + ), + ).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should inflate only a package's relationships and its theme, so its other parts don't stop it", () => { + const document = zip({ + "_rels/.rels": relationships([MAIN_PART, "word/document.xml"]), + "word/_rels/document.xml.rels": relationships([THEME, "theme/theme1.xml"]), + "word/document.xml": "", + "word/theme/theme1.xml": HARBOUR, + }); + expect(readTheme(damaging(document, "word/document.xml"))).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should read the theme of a document, with the colors and fonts `docx` gave it", async () => { + const theme = readTheme( + await Packer.toBuffer( + new File({ + theme: { + name: "Harbour", + colors: { accent1: "1F6F8B", dark1: "1B1B1B" }, + fonts: { headings: "Cambria", body: { latin: "Calibri", scripts: { Jpan: "Meiryo" } } }, + }, + sections: [], + }), + ), + ); + expect(theme.name).to.equal("Harbour"); + expect(theme.colors).to.deep.include({ dark1: "1B1B1B", accent1: "1F6F8B", accent2: "ED7D31" }); + // The system's window color, as `docx` writes it when no color is given + expect(theme.colors).not.to.have.property("light1"); + expect(theme.fonts?.headings).to.deep.include({ latin: "Cambria" }); + expect(theme.fonts?.body).to.deep.include({ latin: "Calibri" }); + expect(theme.fonts?.body).to.have.nested.property("scripts.Jpan", "Meiryo"); + expect(theme.fonts?.body).to.have.nested.property("scripts.Hang", "맑은 고딕"); + }); + + it("should find a theme whose relationship's target is in another case, as part names are the same whatever their case", () => { + expect( + readTheme( + zip({ + "_rels/.rels": relationships([MAIN_PART, "word/document.xml"]), + "word/_rels/document.xml.rels": relationships([THEME, "Theme/THEME1.xml"]), + "word/theme/theme1.xml": HARBOUR, + }), + ), + ).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should read the theme of a presentation, a workbook or a theme file from its main part's relationships", () => { + const presentation = zip({ + "_rels/.rels": relationships([MAIN_PART, "ppt/presentation.xml"]), + "ppt/presentation.xml": "", + // Relationships of other types first, and one with no type + "ppt/_rels/presentation.xml.rels": relationships([`${THEME}x`, "theme/theme2.xml"], [THEME, "theme/theme1.xml"]).replace( + "`, + "theme/theme/_rels/themeManager.xml.rels": relationships([ + "http://purl.oclc.org/ooxml/officeDocument/relationships/theme", + "./../theme/theme1.xml", + ]), + "theme/theme/theme1.xml": HARBOUR, + }); + expect(readTheme(officeTheme)).to.deep.equal(HARBOUR_OPTIONS); + }); + + it("should read the colors or fonts that Word saves on their own", () => { + expect( + readTheme(``), + ).to.deep.equal({ + colors: { accent1: "1F6F8B" }, + }); + expect( + readTheme( + ``, + ), + ).to.deep.equal({ fonts: { headings: { latin: "Georgia" }, body: { latin: "Verdana" } } }); + }); + + it("should read system colors as their last value, other than the window text and window colors of the first dark and light colors", () => { + const { colors } = readTheme( + themeXml( + colorScheme( + `` + + ``, + ), + ), + ); + expect(colors).to.deep.equal({ dark1: "FFFFFF", light1: "000000", dark2: "1B1B1B" }); + }); + + it("should leave out colors of kinds it doesn't read, colors that aren't 6-digit hex values, and elements that aren't colors", () => { + const { colors } = readTheme( + themeXml( + colorScheme( + `` + + ``, + ), + ), + ); + expect(colors).to.deep.equal({ accent3: "A5A5A5" }); + }); + + it("should leave out fonts with no typeface, and fonts for scripts with no script or typeface", () => { + const { fonts } = readTheme( + themeXml( + fontScheme( + ``, + ``, + ), + ), + ); + expect(fonts).to.deep.equal({ headings: { scripts: { Hang: "" } }, body: {} }); + expect(readTheme(themeXml(``)).fonts).to.deep.equal({ headings: {}, body: {} }); + }); + + it("should leave out what a theme doesn't have", () => { + expect(readTheme(``)).to.deep.equal({}); + expect(readTheme(``)).to.deep.equal({}); + }); + + it("should read a theme whatever the prefix of its namespace", () => { + expect( + readTheme( + ``, + ), + ).to.deep.equal({ name: "Harbour", colors: { accent1: "1F6F8B" } }); + expect( + readTheme( + ``, + ), + ).to.deep.equal({ colors: { dark2: "44546A" } }); + }); + + it("should throw for XML that isn't a theme", () => { + expect(() => readTheme(``)).to.throw( + "Invalid theme: expected the XML of a theme, such as a document's word/theme/theme1.xml, but its root element is w:document", + ); + expect(() => readTheme(``)).to.throw("but its root element is missing"); + expect(() => readTheme(new TextEncoder().encode("not XML"))).to.throw("Invalid XML"); + }); + + it("should throw for a zip file that isn't an Office file", () => { + const message = "Invalid file: a zip file that isn't a Word, PowerPoint or Excel file or an Office theme (.thmx)"; + expect(() => readTheme(zip({ "theme1.xml": HARBOUR }))).to.throw(message); + expect(() => readTheme(zip({ "_rels/.rels": relationships([THEME, "theme1.xml"]), "theme1.xml": HARBOUR }))).to.throw(message); + }); + + it("should throw for a file with no theme", () => { + expect(() => + readTheme(zip({ "_rels/.rels": relationships([MAIN_PART, "word/document.xml"]), "word/document.xml": "" })), + ).to.throw("The file has no theme: its main part, word/document.xml, refers to none"); + // A relationship to a theme that isn't in the file + expect(() => + readTheme( + zip({ + "_rels/.rels": relationships([MAIN_PART, "word/document.xml"]), + "word/_rels/document.xml.rels": relationships([THEME, "theme/theme1.xml"]), + }), + ), + ).to.throw("The file has no theme"); + }); +}); + +describe("themePathOf", () => { + it("should give the path of the theme a part refers to", () => { + const files = new Map([["ppt/_rels/presentation.xml.rels", encodeUtf8(relationships([THEME, "../themes/ocean.xml"]))]]); + expect(themePathOf(files, "ppt/presentation.xml")).to.equal("themes/ocean.xml"); + expect(themePathOf(files, "word/document.xml")).to.equal(undefined); + }); +}); + +describe("readThemeColorValues", () => { + it("should read every color of a theme, with the first dark and light colors' last values when they are system colors", () => { + expect( + readThemeColorValues( + themeXml( + colorScheme( + `` + + ``, + ), + ), + ), + ).to.deep.equal({ dark1: "1A1A1A", light1: "FAFAFA", accent1: "1F6F8B" }); + }); + + it("should read no colors from XML that isn't a theme, or a theme with no colors", () => { + expect(readThemeColorValues(colorScheme(``))).to.deep.equal({}); + expect(readThemeColorValues(themeXml(""))).to.deep.equal({}); + }); +}); diff --git a/src/file/theme/read-theme.ts b/src/file/theme/read-theme.ts new file mode 100644 index 0000000000..88b52d750a --- /dev/null +++ b/src/file/theme/read-theme.ts @@ -0,0 +1,244 @@ +/** + * Reads themes: the theme of a Word document or template, of another Office file, or of a theme file, as the options of + * a document's `theme`, so a document `docx` writes can have it, and the colors of a document's theme for the patcher. + * + * @module + */ +// cspell:ignore hlink Hlink purl oclc thmx dotm +import { isSamePart, relationshipsPathOf, resolveTarget } from "@util/package-paths"; +import { type XmlElement, parseXml } from "@util/xml"; +import { unzipFiles } from "@util/zip"; + +import type { IThemeColorsOptions } from "./color-scheme"; +import type { IThemeFontOptions, IThemeFontsOptions } from "./font-scheme"; +import type { IThemeOptions } from "./theme"; +import type { ThemeColorName } from "./theme-color"; + +/* cspell:disable */ +const COLOR_NAMES: ReadonlyMap = new Map([ + ["dk1", "dark1"], + ["lt1", "light1"], + ["dk2", "dark2"], + ["lt2", "light2"], + ["accent1", "accent1"], + ["accent2", "accent2"], + ["accent3", "accent3"], + ["accent4", "accent4"], + ["accent5", "accent5"], + ["accent6", "accent6"], + ["hlink", "hyperlink"], + ["folHlink", "followedHyperlink"], +]); +/* cspell:enable */ + +// The system colors a theme's first dark and light colors are by default, which `docx` writes when they aren't given +const DEFAULT_SYSTEM_COLORS: ReadonlyMap = new Map([ + ["dark1", "windowText"], + ["light1", "window"], +]); + +// The types of the relationships to a package's main part and to a theme, as Transitional and Strict OOXML name them +const MAIN_PART_TYPES: ReadonlySet = new Set([ + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", + "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument", +]); +const THEME_TYPES: ReadonlySet = new Set([ + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", + "http://purl.oclc.org/ooxml/officeDocument/relationships/theme", +]); + +// An element's name without its namespace prefix, which a file may choose +const localName = (element: XmlElement | undefined): string => element?.name?.slice(element.name.indexOf(":") + 1) ?? ""; + +const childElements = (element: XmlElement | undefined): readonly XmlElement[] => + element?.elements?.filter((item) => item.type === "element") ?? []; + +const child = (element: XmlElement | undefined, name: string): XmlElement | undefined => + childElements(element).find((item) => localName(item) === name); + +const attribute = (element: XmlElement | undefined, name: string): string | undefined => { + const value = element?.attributes?.[name]; + return value === undefined ? undefined : String(value); +}; + +// A zip file starts with the signature of its first file's header, "PK\x03\x04" +const isZip = (bytes: Uint8Array): boolean => bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04; + +// A part's text, in UTF-16 when it starts with UTF-16's byte order mark, as XML may be, or else in UTF-8 +const decode = (bytes: Uint8Array): string => + new TextDecoder( + bytes[0] === 0xff && bytes[1] === 0xfe ? "utf-16le" : bytes[0] === 0xfe && bytes[1] === 0xff ? "utf-16be" : "utf-8", + ).decode(bytes); + +// The object without its properties that are undefined +const defined = (object: T): T => + Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined)) as T; + +/** + * The part that a part's relationship of one of `types` refers to, such as the package's main part, which the package + * itself (`""`) refers to. + */ +const relatedPart = (files: ReadonlyMap, from: string, types: ReadonlySet): string | undefined => { + const relationships = files.get(relationshipsPathOf(from)); + const relationship = + relationships && + childElements(child(parseXml(decode(relationships)), "Relationships")).find((item) => types.has(attribute(item, "Type") ?? "")); + const target = attribute(relationship, "Target"); + return target === undefined ? undefined : resolveTarget(from, target); +}; + +/** + * The path of the theme a part of a package refers to, such as word/theme/theme1.xml for a Word document's + * word/document.xml. + */ +export const themePathOf = (files: ReadonlyMap, part: string): string | undefined => + relatedPart(files, part, THEME_TYPES); + +/** + * The XML of a package's theme: the theme its main part refers to, such as word/theme/theme1.xml in a Word document. + * + * @throws If the package has no main part, or its main part has no theme + */ +const packageThemeXml = (bytes: Uint8Array): string => { + // Only the package's relationships are inflated, and then its theme, however large its other parts are + const relationships = unzipFiles(bytes, (path) => path.endsWith(".rels")); + const mainPart = relatedPart(relationships, "", MAIN_PART_TYPES); + if (mainPart === undefined) { + throw new Error("Invalid file: a zip file that isn't a Word, PowerPoint or Excel file or an Office theme (.thmx)"); + } + const themePath = themePathOf(relationships, mainPart); + // The theme's path in the zip file may differ in case from the relationship's target, and is the same part's + const theme = themePath === undefined ? undefined : [...unzipFiles(bytes, (path) => isSamePart(path, themePath)).values()][0]; + if (theme === undefined) { + throw new Error(`The file has no theme: its main part, ${mainPart}, refers to none`); + } + return decode(theme); +}; + +/** + * A theme color's 6-digit hex color: an RGB color's value, or a system color's last value. Unless `withSystemColors`, + * the first dark and light colors are left out when they are the system's window text and window colors, as `docx` + * writes them then. + */ +const colorValue = (name: ThemeColorName, color: XmlElement, withSystemColors: boolean): string | undefined => { + // A theme's color is one color, of one of the kinds DrawingML has + const [value] = childElements(color); + const hex = + localName(value) === "srgbClr" + ? attribute(value, "val") + : localName(value) === "sysClr" && (withSystemColors || attribute(value, "val") !== DEFAULT_SYSTEM_COLORS.get(name)) + ? attribute(value, "lastClr") + : undefined; + return hex !== undefined && /^[0-9A-Fa-f]{6}$/.test(hex) ? hex.toUpperCase() : undefined; +}; + +const readColors = (scheme: XmlElement, withSystemColors = false): IThemeColorsOptions => + Object.fromEntries( + childElements(scheme).flatMap((color) => { + const name = COLOR_NAMES.get(localName(color)); + const value = name && colorValue(name, color, withSystemColors); + return name && value ? [[name, value]] : []; + }), + ); + +/** + * The colors of a theme's XML, each a 6-digit hex color, with the first dark and light colors as their last values when + * they are system colors. The patcher writes theme colors in patches with the hex colors they come to in them. + */ +export const readThemeColorValues = (xml: string): IThemeColorsOptions => { + const [root] = childElements(parseXml(xml)); + const scheme = localName(root) === "theme" ? child(child(root, "themeElements"), "clrScheme") : undefined; + return scheme ? readColors(scheme, true) : {}; +}; + +// A font's typeface, or `undefined` for none, which a theme writes as "" +const typefaceOf = (font: XmlElement | undefined): string | undefined => attribute(font, "typeface") || undefined; + +const readFont = (collection: XmlElement | undefined): IThemeFontOptions => { + const scripts = childElements(collection) + .filter((font) => localName(font) === "font") + .flatMap((font) => { + const script = attribute(font, "script"); + const typeface = attribute(font, "typeface"); + return script && typeface !== undefined ? [[script, typeface] as const] : []; + }); + return defined({ + latin: typefaceOf(child(collection, "latin")), + eastAsia: typefaceOf(child(collection, "ea")), + complexScript: typefaceOf(child(collection, "cs")), + scripts: scripts.length > 0 ? Object.fromEntries(scripts) : undefined, + }); +}; + +const readFonts = (scheme: XmlElement): IThemeFontsOptions => ({ + headings: readFont(child(scheme, "majorFont")), + body: readFont(child(scheme, "minorFont")), +}); + +/** + * The XML of the theme the data is or has: the XML itself, as text or bytes, or the theme of a package. + */ +const xmlOf = (data: string | Uint8Array | ArrayBuffer): string => { + if (typeof data === "string") { + return data; + } + const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data); + return isZip(bytes) ? packageThemeXml(bytes) : decode(bytes); +}; + +/** + * Reads a theme, such as the theme of a Word document or template, as the options of a document's `theme`. The new + * document then has the theme's colors and fonts, so the styles, tables and text that use them look as they do in the + * file the theme came from: + * + * - its name; + * - its colors, each an RGB color or a system color's last value; + * - its fonts for headings and body text, with their fonts for East Asian text, complex scripts and each other script. + * + * The fills, lines and effects of shapes styled by the theme are Office's in the new document, as `docx` writes them. + * + * It reads the colors or fonts Word saves on their own too, from Design > Colors > Customize Colors or Design > Fonts > + * Customize Fonts, as the theme's `colors` or `fonts`. + * + * @param data - A Word document or template (.docx, .docm, .dotx or .dotm), a PowerPoint presentation (.pptx), an Excel + * workbook (.xlsx), an Office theme (.thmx), or the XML of a theme, such as a document's word/theme/theme1.xml, or of a + * theme's colors or fonts, as text or bytes + * @returns The theme's options, to give `Document`'s `theme`, or to change before giving it + * @throws If the data isn't one of those, or the file has no theme + * + * @example + * ```typescript + * import * as fs from "fs"; + * import { Document, readTheme } from "docx"; + * + * // The template's styles, and its theme, whose colors and fonts its styles use + * const doc = new Document({ + * theme: readTheme(fs.readFileSync("template.dotx")), + * externalStyles: fs.readFileSync("styles.xml", "utf-8"), + * sections: [], + * }); + * ``` + */ +export const readTheme = (data: string | Uint8Array | ArrayBuffer): IThemeOptions => { + const [root] = childElements(parseXml(xmlOf(data))); + // The colors or fonts of a theme, on their own + if (localName(root) === "clrScheme") { + return { colors: readColors(root) }; + } + if (localName(root) === "fontScheme") { + return { fonts: readFonts(root) }; + } + if (localName(root) !== "theme") { + throw new Error( + `Invalid theme: expected the XML of a theme, such as a document's word/theme/theme1.xml, but its root element is ${root?.name ?? "missing"}`, + ); + } + const elements = child(root, "themeElements"); + const colorScheme = child(elements, "clrScheme"); + const fontScheme = child(elements, "fontScheme"); + return defined({ + name: attribute(root, "name") || undefined, + colors: colorScheme && readColors(colorScheme), + fonts: fontScheme && readFonts(fontScheme), + }); +}; diff --git a/src/file/theme/theme.spec.ts b/src/file/theme/theme.spec.ts index 01158d9ff8..0a903f36ba 100644 --- a/src/file/theme/theme.spec.ts +++ b/src/file/theme/theme.spec.ts @@ -116,6 +116,21 @@ describe("Theme", () => { ]); }); + it("should write the fonts given for scripts in place of Office's, and add the scripts Office has no font for", () => { + const { fonts } = elements( + new Theme({ fonts: { headings: { latin: "Georgia", scripts: { Jpan: "Meiryo", Arab: "Tahoma", Latn: "Georgia" } } } }), + ); + const headings = fontCollection(fonts, "a:majorFont"); + expect(headings[3]).to.deep.equal({ "a:font": { _attr: { script: "Jpan", typeface: "Meiryo" } } }); + // Office's font for Korean text, as no other is given + expect(headings[4]).to.deep.equal({ "a:font": { _attr: { script: "Hang", typeface: "맑은 고딕" } } }); + expect(headings[7]).to.deep.equal({ "a:font": { _attr: { script: "Arab", typeface: "Tahoma" } } }); + expect(headings).to.have.length(51); + expect(headings[50]).to.deep.equal({ "a:font": { _attr: { script: "Latn", typeface: "Georgia" } } }); + // The fonts for body text are still Office's + expect(fontCollection(fonts, "a:minorFont")[3]).to.deep.equal({ "a:font": { _attr: { script: "Jpan", typeface: "游明朝" } } }); + }); + it("should give the hex color of each of its colors, with Office's in place of those not given", () => { expect(new Theme().Colors).to.deep.equal({ dark1: "000000", diff --git a/src/patcher/core-properties.ts b/src/patcher/core-properties.ts index 237e72aa5d..de9e7b1714 100644 --- a/src/patcher/core-properties.ts +++ b/src/patcher/core-properties.ts @@ -4,9 +4,9 @@ * @module */ import type { IPropertiesOptions } from "@file/core-properties"; +import { resolveTarget } from "@util/package-paths"; import type { XmlElement as Element } from "@util/xml"; -import { resolveTarget } from "./drawing-patch"; import { appendRelationship, createRelationshipFile, getNextRelationshipIndex } from "./relationship-manager"; import { getFirstLevelElements, toJson } from "./util"; diff --git a/src/patcher/drawing-patch.spec.ts b/src/patcher/drawing-patch.spec.ts index 52e034961f..5770dd6607 100644 --- a/src/patcher/drawing-patch.spec.ts +++ b/src/patcher/drawing-patch.spec.ts @@ -7,17 +7,7 @@ import { BuilderElement } from "@file/xml-components"; import type { XmlElement as Element } from "@util/xml"; import { textOf, unzip, zip } from "tests/zip"; -import { - DrawingPatch, - type TemplateDrawing, - type TemplatePackage, - altTextOf, - findDrawings, - relationshipsPathOf, - relativeTarget, - resolveTarget, - sourceOfRelationships, -} from "./drawing-patch"; +import { DrawingPatch, type TemplateDrawing, type TemplatePackage, altTextOf, findDrawings } from "./drawing-patch"; import { type IPatch, PatchType, patchDocument } from "./from-docx"; import { patchDetector } from "./patch-detector"; import { toJson } from "./util"; @@ -249,108 +239,6 @@ describe("drawing-patch", () => { }); }); - describe("relationshipsPathOf", () => { - it("should give the relationships part of a part in word/", () => { - expect(relationshipsPathOf("word/document.xml")).to.equal("word/_rels/document.xml.rels"); - expect(relationshipsPathOf("word/header1.xml")).to.equal("word/_rels/header1.xml.rels"); - }); - - it("should give the relationships part of a part in a folder of its own", () => { - expect(relationshipsPathOf("word/charts/chart1.xml")).to.equal("word/charts/_rels/chart1.xml.rels"); - expect(relationshipsPathOf("word/glossary/document.xml")).to.equal("word/glossary/_rels/document.xml.rels"); - }); - - it("should give the relationships part of a part at the package's root", () => { - expect(relationshipsPathOf("chart.xml")).to.equal("_rels/chart.xml.rels"); - }); - }); - - describe("sourceOfRelationships", () => { - it("should give the part a relationships part belongs to", () => { - expect(sourceOfRelationships("word/_rels/document.xml.rels")).to.equal("word/document.xml"); - expect(sourceOfRelationships("word/charts/_rels/chart1.xml.rels")).to.equal("word/charts/chart1.xml"); - expect(sourceOfRelationships("_rels/chart.xml.rels")).to.equal("chart.xml"); - }); - - it("should give the package's root for the package's own relationships", () => { - expect(sourceOfRelationships("_rels/.rels")).to.equal(""); - }); - - it("should be the opposite of relationshipsPathOf", () => { - for (const path of ["word/document.xml", "word/charts/chart10.xml", "a/b/c/d.xml", "x.xml"]) { - expect(sourceOfRelationships(relationshipsPathOf(path))).to.equal(path); - } - }); - }); - - describe("resolveTarget", () => { - it("should resolve a target relative to the folder of the part it is from", () => { - expect(resolveTarget("word/document.xml", "charts/chart1.xml")).to.equal("word/charts/chart1.xml"); - expect(resolveTarget("word/charts/chart1.xml", "../embeddings/Microsoft_Excel_Worksheet1.xlsx")).to.equal( - "word/embeddings/Microsoft_Excel_Worksheet1.xlsx", - ); - expect(resolveTarget("word/charts/chart1.xml", "style1.xml")).to.equal("word/charts/style1.xml"); - }); - - it("should resolve a target from the package's root when it starts with a slash", () => { - expect(resolveTarget("word/charts/chart1.xml", "/word/embeddings/book.xlsx")).to.equal("word/embeddings/book.xlsx"); - expect(resolveTarget("", "/word/document.xml")).to.equal("word/document.xml"); - }); - - it("should resolve the package's own relationships from its root", () => { - expect(resolveTarget("", "word/document.xml")).to.equal("word/document.xml"); - }); - - it("should read backslashes as slashes", () => { - expect(resolveTarget("word/document.xml", "charts\\chart1.xml")).to.equal("word/charts/chart1.xml"); - expect(resolveTarget("word/charts/chart1.xml", "..\\embeddings\\book.xlsx")).to.equal("word/embeddings/book.xlsx"); - }); - - it("should leave out empty and current folders, and never go above the root", () => { - expect(resolveTarget("word/document.xml", "./charts//./chart1.xml")).to.equal("word/charts/chart1.xml"); - expect(resolveTarget("word/document.xml", "../../../../x.xml")).to.equal("x.xml"); - expect(resolveTarget("word/a/b/c.xml", "../../d.xml")).to.equal("word/d.xml"); - }); - }); - - describe("relativeTarget", () => { - it("should give a target in the same folder", () => { - expect(relativeTarget("word/document.xml", "word/styles.xml")).to.equal("styles.xml"); - }); - - it("should give a target in a folder below", () => { - expect(relativeTarget("word/document.xml", "word/charts/chart1.xml")).to.equal("charts/chart1.xml"); - }); - - it("should give a target in a folder beside", () => { - expect(relativeTarget("word/charts/chart1.xml", "word/embeddings/Microsoft_Excel_Worksheet2.xlsx")).to.equal( - "../embeddings/Microsoft_Excel_Worksheet2.xlsx", - ); - }); - - it("should give a target in a folder above, and from the root", () => { - expect(relativeTarget("word/a/b/c.xml", "word/d.xml")).to.equal("../../d.xml"); - expect(relativeTarget("word/a/b/c.xml", "x.xml")).to.equal("../../../x.xml"); - expect(relativeTarget("chart.xml", "word/embeddings/book.xlsx")).to.equal("word/embeddings/book.xlsx"); - }); - - it("should give a target that resolves to the part", () => { - const paths = [ - "word/document.xml", - "word/charts/chart1.xml", - "word/embeddings/book.xlsx", - "a.xml", - "word/a/b/c/d.xml", - "x/y.xml", - ]; - for (const from of paths) { - for (const to of paths) { - expect(resolveTarget(from, relativeTarget(from, to)), `${from} to ${to}`).to.equal(to); - } - } - }); - }); - describe("DrawingPatch", () => { it("should be a patch of the drawing type", () => { expect(new RecordingPatch().type).to.equal(PatchType.DRAWING); diff --git a/src/patcher/drawing-patch.ts b/src/patcher/drawing-patch.ts index 3e7a4248c7..db07e86416 100644 --- a/src/patcher/drawing-patch.ts +++ b/src/patcher/drawing-patch.ts @@ -12,6 +12,7 @@ import { Formatter } from "@export/formatter"; import type { File } from "@file/file"; import type { PackagePart } from "@file/package-part"; import type { IContext, XmlComponent } from "@file/xml-components"; +import { relationshipsPathOf, relativeTarget, resolveTarget, sourceOfRelationships } from "@util/package-paths"; import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { removeContentTypeOverride } from "./content-types-manager"; @@ -134,56 +135,6 @@ export const findDrawings = (element: Element): readonly FoundDrawing[] => export const altTextOf = (properties: Element): readonly string[] => [properties.attributes?.descr, properties.attributes?.title].flatMap((text) => (text === undefined ? [] : [String(text)])); -/** - * The path of a part's relationships part, such as word/_rels/document.xml.rels for word/document.xml. - */ -export const relationshipsPathOf = (path: string): string => { - const slash = path.lastIndexOf("/"); - return `${path.slice(0, slash + 1)}_rels/${path.slice(slash + 1)}.rels`; -}; - -/** - * The part a relationships part belongs to, or "" for the package's own (_rels/.rels), whose targets are from its root. - */ -export const sourceOfRelationships = (path: string): string => path.replace(/(^|\/)_rels\/([^/]*)\.rels$/, "$1$2"); - -// A part's folder, with its slash, such as "word/" for word/document.xml, or "" for a part at the package's root -const folderOf = (path: string): string => path.slice(0, path.lastIndexOf("/") + 1); - -/** - * The path of the part a relationship's target refers to: relative to the folder of the part the relationship belongs - * to, or from the package's root if it starts with "/". Backslashes, which some applications write, are read as slashes. - * - * @param from - The path of the part the relationship belongs to - */ -export const resolveTarget = (from: string, target: string): string => { - const normalized = target.replace(/\\/g, "/"); - return (normalized.startsWith("/") ? normalized : `${folderOf(from)}${normalized}`) - .split("/") - .reduce((segments, segment) => { - if (segment === "" || segment === ".") { - return segments; - } - return segment === ".." ? segments.slice(0, -1) : [...segments, segment]; - }, []) - .join("/"); -}; - -/** - * A relationship's target for a part, relative to the folder of the part the relationship belongs to, such as - * "../embeddings/Microsoft_Excel_Worksheet1.xlsx" from word/charts/chart1.xml. - * - * @param from - The path of the part the relationship belongs to - * @param to - The path of the part it refers to - */ -export const relativeTarget = (from: string, to: string): string => { - const folders = folderOf(from).split("/").filter(Boolean); - const segments = to.split("/"); - const common = folders.findIndex((folder, index) => index >= segments.length - 1 || segments[index] !== folder); - const shared = common === -1 ? folders.length : common; - return [...folders.slice(shared).map(() => ".."), ...segments.slice(shared)].join("/"); -}; - const CONTENT_TYPES = "[Content_Types].xml"; /** diff --git a/src/patcher/from-docx.ts b/src/patcher/from-docx.ts index a5c240e133..7e3c8f5818 100644 --- a/src/patcher/from-docx.ts +++ b/src/patcher/from-docx.ts @@ -24,6 +24,7 @@ import { type RelationshipType, TargetModeType } from "@file/relationships/relat import type { IContext } from "@file/xml-components"; import { uniqueId } from "@util/convenience-functions"; import type { OutputByType, OutputType } from "@util/output-type"; +import { relationshipsPathOf } from "@util/package-paths"; import { type XmlElement as Element, stringifyElement } from "@util/xml"; import { zipFiles, zipOutput } from "@util/zip"; @@ -31,7 +32,7 @@ import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids"; import { appendContentType, appendContentTypeOverride } from "./content-types-manager"; import { type PatchDocumentProperties, patchCoreProperties } from "./core-properties"; import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids"; -import { type DrawingPatch, patchDrawings, relationshipsPathOf } from "./drawing-patch"; +import { type DrawingPatch, patchDrawings } from "./drawing-patch"; import { type ZipArchive, loadZip } from "./load-zip"; import { patchNotes } from "./notes"; import { patchNumbering } from "./numbering"; diff --git a/src/patcher/notes.ts b/src/patcher/notes.ts index acd43cf8a0..cd2a051e93 100644 --- a/src/patcher/notes.ts +++ b/src/patcher/notes.ts @@ -21,11 +21,11 @@ import { } from "@file/styles/style/default-styles"; import type { IContext, XmlComponent } from "@file/xml-components"; import { uniqueId } from "@util/convenience-functions"; +import { relationshipsPathOf, relativeTarget, resolveTarget } from "@util/package-paths"; import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import type { RenumberBookmarks } from "./bookmark-ids"; import type { RenumberDrawings } from "./drawing-ids"; -import { relationshipsPathOf, relativeTarget, resolveTarget } from "./drawing-patch"; import { getFirstLevelElements, toJson } from "./util"; const formatter = new Formatter(); diff --git a/src/patcher/numbering.ts b/src/patcher/numbering.ts index 33076292bb..77669be6a4 100644 --- a/src/patcher/numbering.ts +++ b/src/patcher/numbering.ts @@ -8,9 +8,9 @@ import { Formatter } from "@export/formatter"; import type { ConcreteNumbering, Numbering } from "@file/numbering"; import type { IContext, XmlComponent } from "@file/xml-components"; import { uniqueId } from "@util/convenience-functions"; +import { relationshipsPathOf, relativeTarget, resolveTarget } from "@util/package-paths"; import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; -import { relationshipsPathOf, relativeTarget, resolveTarget } from "./drawing-patch"; import { getFirstLevelElements, toJson } from "./util"; const formatter = new Formatter(); diff --git a/src/patcher/page-numbers.ts b/src/patcher/page-numbers.ts index 79e2a0c974..f75a6f08e4 100644 --- a/src/patcher/page-numbers.ts +++ b/src/patcher/page-numbers.ts @@ -7,10 +7,10 @@ import { type ElementTree, fillBodyFields, fillPartFields } from "@file/document/body/page-number-fields"; import type { EstimatedPageNumbers } from "@file/document/body/page-numbers"; +import { relationshipsPathOf, resolveTarget, sourceOfRelationships } from "@util/package-paths"; import type { XmlElement as Element } from "@util/xml"; import { unzipFiles } from "@util/zip"; -import { relationshipsPathOf, resolveTarget, sourceOfRelationships } from "./drawing-patch"; import { decodeUtf8, toJson } from "./util"; /** diff --git a/src/patcher/theme-colors.spec.ts b/src/patcher/theme-colors.spec.ts index 41dd79c168..b6ff73ba52 100644 --- a/src/patcher/theme-colors.spec.ts +++ b/src/patcher/theme-colors.spec.ts @@ -142,6 +142,14 @@ describe("readThemeColors", () => { expect(readThemeColors(zip)).to.deep.equal({ ...OFFICE_COLORS, accent1: "2E7D32" }); }); + it("should find a theme whose target is in another case", () => { + const zip = createZip([ + ["word/_rels/document.xml.rels", RELATIONSHIPS("Theme/THEME1.xml")], + ["word/theme/theme1.xml", THEME(``)], + ]); + expect(readThemeColors(zip)).to.deep.equal({ ...OFFICE_COLORS, accent1: "2E7D32" }); + }); + it("should use Office's colors for a theme without a color scheme", () => { const zip = createZip([ ["word/_rels/document.xml.rels", RELATIONSHIPS("theme/theme1.xml")], diff --git a/src/patcher/theme-colors.ts b/src/patcher/theme-colors.ts index d2bdcb65c6..07e6a2e140 100644 --- a/src/patcher/theme-colors.ts +++ b/src/patcher/theme-colors.ts @@ -4,86 +4,22 @@ * * @module */ -// cspell:ignore hlink Hlink - import { type ThemeColorValues, themeColorValues } from "@file/theme/color-scheme"; -import type { ThemeColorName } from "@file/theme/theme-color"; -import type { XmlElement as Element } from "@util/xml"; +import { readThemeColorValues, themePathOf } from "@file/theme/read-theme"; +import { isSamePart } from "@util/package-paths"; -import { resolveTarget } from "./drawing-patch"; -import { decodeUtf8, toJson } from "./util"; - -const THEME_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"; - -/* cspell:disable */ -const COLOR_NAMES: ReadonlyMap = new Map([ - ["dk1", "dark1"], - ["lt1", "light1"], - ["dk2", "dark2"], - ["lt2", "light2"], - ["accent1", "accent1"], - ["accent2", "accent2"], - ["accent3", "accent3"], - ["accent4", "accent4"], - ["accent5", "accent5"], - ["accent6", "accent6"], - ["hlink", "hyperlink"], - ["folHlink", "followedHyperlink"], -]); -/* cspell:enable */ - -// An element's name without its namespace prefix, which a document may choose -const localName = (element: Element): string | undefined => element.name?.slice(element.name.indexOf(":") + 1); - -const child = (element: Element | undefined, name: string): Element | undefined => - element?.elements?.find((item) => localName(item) === name); - -/** - * The hex value of a theme's color: an RGB color's value, or the last value of a system color, as Word writes them. - * Other kinds of color aren't read. - */ -const hexValue = (color: Element): string | undefined => { - const value = color.elements - ?.map((item) => - localName(item) === "srgbClr" ? item.attributes?.val : localName(item) === "sysClr" ? item.attributes?.lastClr : undefined, - ) - .find((item) => item !== undefined); - return typeof value === "string" && /^[0-9A-Fa-f]{6}$/.test(value) ? value.toUpperCase() : undefined; -}; +import { decodeUtf8 } from "./util"; // The patcher leaves parts in UTF-16 as they are, so they aren't read here either const isUtf16 = (bytes: Uint8Array): boolean => (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff); -const readPart = (files: ReadonlyMap, path: string): Element | undefined => { - const part = files.get(path); - return part === undefined || isUtf16(part) ? undefined : toJson(decodeUtf8(part)); -}; - -/** - * The document's theme part, found from the document's relationships. - */ -const readTheme = (files: ReadonlyMap): Element | undefined => { - const relationships = readPart(files, "word/_rels/document.xml.rels"); - const theme = child(relationships, "Relationships")?.elements?.find((item) => item.attributes?.Type === THEME_RELATIONSHIP_TYPE); - const target = theme?.attributes?.Target; - return typeof target === "string" ? readPart(files, resolveTarget("word/document.xml", target)) : undefined; -}; - /** * Reads the colors of the document's theme. Colors it doesn't give, or gives in a way that isn't read, are Office's. * * @returns The theme's colors, or `undefined` if the document has no theme that can be read */ export const readThemeColors = (files: ReadonlyMap): ThemeColorValues | undefined => { - const theme = readTheme(files); - if (theme === undefined) { - return undefined; - } - const scheme = child(child(child(theme, "theme"), "themeElements"), "clrScheme"); - const colors = (scheme?.elements ?? []).flatMap((color) => { - const name = COLOR_NAMES.get(localName(color) ?? ""); - const value = hexValue(color); - return name && value ? [[name, value] as const] : []; - }); - return themeColorValues(Object.fromEntries(colors)); + const path = themePathOf(files, "word/document.xml"); + const theme = path === undefined ? undefined : [...files].find(([name]) => isSamePart(name, path))?.[1]; + return theme === undefined || isUtf16(theme) ? undefined : themeColorValues(readThemeColorValues(decodeUtf8(theme))); }; diff --git a/src/util/package-paths.spec.ts b/src/util/package-paths.spec.ts new file mode 100644 index 0000000000..b750f2209d --- /dev/null +++ b/src/util/package-paths.spec.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; + +import { isSamePart, relationshipsPathOf, relativeTarget, resolveTarget, sourceOfRelationships } from "./package-paths"; + +describe("relationshipsPathOf", () => { + it("should give the relationships part of a part in word/", () => { + expect(relationshipsPathOf("word/document.xml")).to.equal("word/_rels/document.xml.rels"); + expect(relationshipsPathOf("word/header1.xml")).to.equal("word/_rels/header1.xml.rels"); + }); + + it("should give the relationships part of a part in a folder of its own", () => { + expect(relationshipsPathOf("word/charts/chart1.xml")).to.equal("word/charts/_rels/chart1.xml.rels"); + expect(relationshipsPathOf("word/glossary/document.xml")).to.equal("word/glossary/_rels/document.xml.rels"); + }); + + it("should give the relationships part of a part at the package's root", () => { + expect(relationshipsPathOf("chart.xml")).to.equal("_rels/chart.xml.rels"); + }); +}); + +describe("sourceOfRelationships", () => { + it("should give the part a relationships part belongs to", () => { + expect(sourceOfRelationships("word/_rels/document.xml.rels")).to.equal("word/document.xml"); + expect(sourceOfRelationships("word/charts/_rels/chart1.xml.rels")).to.equal("word/charts/chart1.xml"); + expect(sourceOfRelationships("_rels/chart.xml.rels")).to.equal("chart.xml"); + }); + + it("should give the package's root for the package's own relationships", () => { + expect(sourceOfRelationships("_rels/.rels")).to.equal(""); + }); + + it("should be the opposite of relationshipsPathOf", () => { + for (const path of ["word/document.xml", "word/charts/chart10.xml", "a/b/c/d.xml", "x.xml"]) { + expect(sourceOfRelationships(relationshipsPathOf(path))).to.equal(path); + } + }); +}); + +describe("resolveTarget", () => { + it("should resolve a target relative to the folder of the part it is from", () => { + expect(resolveTarget("word/document.xml", "charts/chart1.xml")).to.equal("word/charts/chart1.xml"); + expect(resolveTarget("word/charts/chart1.xml", "../embeddings/Microsoft_Excel_Worksheet1.xlsx")).to.equal( + "word/embeddings/Microsoft_Excel_Worksheet1.xlsx", + ); + expect(resolveTarget("word/charts/chart1.xml", "style1.xml")).to.equal("word/charts/style1.xml"); + }); + + it("should resolve a target from the package's root when it starts with a slash", () => { + expect(resolveTarget("word/charts/chart1.xml", "/word/embeddings/book.xlsx")).to.equal("word/embeddings/book.xlsx"); + expect(resolveTarget("", "/word/document.xml")).to.equal("word/document.xml"); + }); + + it("should resolve the package's own relationships from its root", () => { + expect(resolveTarget("", "word/document.xml")).to.equal("word/document.xml"); + }); + + it("should read backslashes as slashes", () => { + expect(resolveTarget("word/document.xml", "charts\\chart1.xml")).to.equal("word/charts/chart1.xml"); + expect(resolveTarget("word/charts/chart1.xml", "..\\embeddings\\book.xlsx")).to.equal("word/embeddings/book.xlsx"); + }); + + it("should leave out empty and current folders, and never go above the root", () => { + expect(resolveTarget("word/document.xml", "./charts//./chart1.xml")).to.equal("word/charts/chart1.xml"); + expect(resolveTarget("word/document.xml", "../../../../x.xml")).to.equal("x.xml"); + expect(resolveTarget("word/a/b/c.xml", "../../d.xml")).to.equal("word/d.xml"); + }); +}); + +describe("relativeTarget", () => { + it("should give a target in the same folder", () => { + expect(relativeTarget("word/document.xml", "word/styles.xml")).to.equal("styles.xml"); + }); + + it("should give a target in a folder below", () => { + expect(relativeTarget("word/document.xml", "word/charts/chart1.xml")).to.equal("charts/chart1.xml"); + }); + + it("should give a target in a folder beside", () => { + expect(relativeTarget("word/charts/chart1.xml", "word/embeddings/Microsoft_Excel_Worksheet2.xlsx")).to.equal( + "../embeddings/Microsoft_Excel_Worksheet2.xlsx", + ); + }); + + it("should give a target in a folder above, and from the root", () => { + expect(relativeTarget("word/a/b/c.xml", "word/d.xml")).to.equal("../../d.xml"); + expect(relativeTarget("word/a/b/c.xml", "x.xml")).to.equal("../../../x.xml"); + expect(relativeTarget("chart.xml", "word/embeddings/book.xlsx")).to.equal("word/embeddings/book.xlsx"); + }); + + it("should give a target that resolves to the part", () => { + const paths = ["word/document.xml", "word/charts/chart1.xml", "word/embeddings/book.xlsx", "a.xml", "word/a/b/c/d.xml", "x/y.xml"]; + for (const from of paths) { + for (const to of paths) { + expect(resolveTarget(from, relativeTarget(from, to)), `${from} to ${to}`).to.equal(to); + } + } + }); +}); + +describe("isSamePart", () => { + it("should be the same part for paths that differ only in case", () => { + expect(isSamePart("word/theme/theme1.xml", "word/theme/theme1.xml")).to.equal(true); + expect(isSamePart("word/Theme/THEME1.xml", "word/theme/theme1.xml")).to.equal(true); + }); + + it("should be another part for another path", () => { + expect(isSamePart("word/theme/theme1.xml", "word/theme/theme2.xml")).to.equal(false); + expect(isSamePart("word/theme1.xml", "word/theme/theme1.xml")).to.equal(false); + }); +}); diff --git a/src/util/package-paths.ts b/src/util/package-paths.ts new file mode 100644 index 0000000000..adaf235a84 --- /dev/null +++ b/src/util/package-paths.ts @@ -0,0 +1,63 @@ +/** + * The paths of a package's parts, such as word/document.xml in a .docx file, and the targets of the relationships + * between them. + * + * @module + */ + +/** + * The path of a part's relationships part, such as word/_rels/document.xml.rels for word/document.xml. + */ +export const relationshipsPathOf = (path: string): string => { + const slash = path.lastIndexOf("/"); + return `${path.slice(0, slash + 1)}_rels/${path.slice(slash + 1)}.rels`; +}; + +/** + * The part a relationships part belongs to, or "" for the package's own (_rels/.rels), whose targets are from its root. + */ +export const sourceOfRelationships = (path: string): string => path.replace(/(^|\/)_rels\/([^/]*)\.rels$/, "$1$2"); + +// A part's folder, with its slash, such as "word/" for word/document.xml, or "" for a part at the package's root +const folderOf = (path: string): string => path.slice(0, path.lastIndexOf("/") + 1); + +/** + * The path of the part a relationship's target refers to: relative to the folder of the part the relationship belongs + * to, or from the package's root if it starts with "/". Backslashes, which some applications write, are read as slashes. + * + * @param from - The path of the part the relationship belongs to + */ +export const resolveTarget = (from: string, target: string): string => { + const normalized = target.replace(/\\/g, "/"); + return (normalized.startsWith("/") ? normalized : `${folderOf(from)}${normalized}`) + .split("/") + .reduce((segments, segment) => { + if (segment === "" || segment === ".") { + return segments; + } + return segment === ".." ? segments.slice(0, -1) : [...segments, segment]; + }, []) + .join("/"); +}; + +/** + * A relationship's target for a part, relative to the folder of the part the relationship belongs to, such as + * "../embeddings/Microsoft_Excel_Worksheet1.xlsx" from word/charts/chart1.xml. + * + * @param from - The path of the part the relationship belongs to + * @param to - The path of the part it refers to + */ +export const relativeTarget = (from: string, to: string): string => { + const folders = folderOf(from).split("/").filter(Boolean); + const segments = to.split("/"); + const common = folders.findIndex((folder, index) => index >= segments.length - 1 || segments[index] !== folder); + const shared = common === -1 ? folders.length : common; + return [...folders.slice(shared).map(() => ".."), ...segments.slice(shared)].join("/"); +}; + +/** + * Whether two paths are the same part's. Part names are compared without regard to case, as the Open Packaging + * Conventions compare them, so a relationship's target such as "Theme/THEME1.xml" from word/document.xml names + * word/theme/theme1.xml. + */ +export const isSamePart = (path: string, other: string): boolean => path.toLowerCase() === other.toLowerCase();