From c08ec0ae8a34084af462e581dd3e751e860ffbaa Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 17 Oct 2026 15:41:30 +0100 Subject: [PATCH] feat: two lines in one and horizontal in vertical with eastAsianLayout (#1943) (#3783) --- demo/text/two-lines-in-one.ts | 67 ++++++++++ docs/usage/layout.md | 7 +- docs/usage/text.md | 68 +++++++++++ .../paragraph/run/east-asian-layout.spec.ts | 59 +++++++++ src/file/paragraph/run/east-asian-layout.ts | 115 ++++++++++++++++++ src/file/paragraph/run/index.ts | 1 + src/file/paragraph/run/properties.ts | 11 ++ src/file/paragraph/run/run.spec.ts | 33 +++++ src/util/values.spec.ts | 14 +++ src/util/values.ts | 8 +- 10 files changed, 376 insertions(+), 7 deletions(-) create mode 100644 demo/text/two-lines-in-one.ts create mode 100644 src/file/paragraph/run/east-asian-layout.spec.ts create mode 100644 src/file/paragraph/run/east-asian-layout.ts diff --git a/demo/text/two-lines-in-one.ts b/demo/text/two-lines-in-one.ts new file mode 100644 index 0000000000..75ce595b1a --- /dev/null +++ b/demo/text/two-lines-in-one.ts @@ -0,0 +1,67 @@ +// Two lines in one and horizontal in vertical, Word's East Asian typography for runs of text + +import * as fs from "fs"; +import { Document, Packer, PageTextDirectionType, Paragraph, TextRun, TwoLinesInOneBrackets } from "docx"; + +const doc = new Document({ + styles: { + default: { + document: { + run: { + font: { ascii: "Calibri", eastAsia: "SimSun" }, + size: 32, + }, + }, + }, + }, + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun("财政部"), + new TextRun({ text: "国家税务总局", eastAsianLayout: { twoLinesInOne: true } }), + new TextRun("文件"), + ], + }), + new Paragraph({ + children: [ + new TextRun("会议"), + new TextRun({ + text: "二〇二六年十月", + eastAsianLayout: { twoLinesInOne: true, brackets: TwoLinesInOneBrackets.ROUND }, + }), + new TextRun("纪要"), + ], + }), + new Paragraph({ + children: [ + new TextRun("Runs in one group: "), + new TextRun({ text: "bold ", bold: true, eastAsianLayout: { twoLinesInOne: true, group: 1 } }), + new TextRun({ text: "and italic", italics: true, eastAsianLayout: { twoLinesInOne: true, group: 1 } }), + ], + }), + ], + }, + { + properties: { + page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }, + }, + children: [ + new Paragraph({ + children: [ + new TextRun("令和"), + new TextRun({ text: "8", eastAsianLayout: { horizontalInVertical: true } }), + new TextRun("年"), + new TextRun({ text: "10", eastAsianLayout: { horizontalInVertical: true } }), + new TextRun("月"), + ], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/docs/usage/layout.md b/docs/usage/layout.md index e1c18db325..e9aee9f020 100644 --- a/docs/usage/layout.md +++ b/docs/usage/layout.md @@ -206,7 +206,7 @@ The pages are laid out with the widths and heights of the characters of the font - keeping a paragraph with the next, keeping its lines together, widow and orphan control, and page breaks - numbered and bulleted lists, including those a paragraph's style numbers it in, counted as Word counts them: lists made from the same definition count on from one another, and a list's own first number for a level, which `docx` writes for each `instance` of a list, starts that level there at the list's first paragraph of that level. A level starts again after any level above it, or only after the level it gives, or never (`w:lvlRestart`), and a legal level (`isLegalNumberingStyle`) writes every level's number in decimal. A number is in its paragraph mark's formatting (`run` on a `Paragraph`), but for what its level gives it (`style.run`), and makes its line taller only above the baseline, with multiple line spacing a share of its text's line more, as Word lays it out. Its emphasis marks, and a number raised or lowered, take room as text's do. A line with nothing but a number is as tall as its paragraph's mark, or as the number above the baseline where that is taller. A number aligned to the right (`AlignmentType.END` or `RIGHT`) ends at the start of its paragraph's first line, and a centred one, with the space after it, is centred there, so a wide number can go into the margin, as Word puts it, and the text after it goes on from its end, at the hanging indent or the next tab stop after it. Word lines up a number aligned distribute or with a low kashida to the left, one aligned `numTab` to the right, and one aligned for Thai in the centre, and so does the layout. A number in a border (`style.run.border`) is in a box with the tab or space after it: the text after it starts at the tab's stop, or right after the border's room from the number where that is further, and the line is taller by the room above. A word that doesn't fit after a number's tab stays on the number's line, broken after the last character that fits, as a word after a tab that starts its line does. Bullets that are pictures Word draws nothing for, so the text is at the tab's stop and the line as tall as its text. A level numbered as Word 6 numbered lists (`w:legacy`) puts the text at the level's indent from the number, or after its space from the number's end where that is further. After a number aligned to the right, the tab goes to the next stop past its end, or, without a first line or hanging indent, to the left indent, where the number ends. Word measures the space after a number (`LevelSuffix.SPACE`) in Arial, and so does the layout. Word writes Thai and Hindi words (`thaiCounting`, `hindiCounting`) from 1 to 5. A level whose text shows a level its list doesn't have, or aligned as justified text is (`w:lvlJc` both), Word leaves out, as though it weren't there: its paragraphs have no number, nor the level's indent, another level's number shows nothing for it, and a paragraph at it starts the levels below it again, as a paragraph at any level does, while the list's other levels are numbered as usual. Word puts its automatic spacing between the paragraphs of two lists made from the same definition (`instance`), as between lists of other definitions, and so does the layout - footnotes, which take room at the bottom of the page their reference is on, and endnotes, which follow the text. A footnote that doesn't fit below its reference continues at the bottom of the next page, as Word continues it: it breaks between its paragraphs and table rows, and inside a paragraph keeping to its widow and orphan control, and its reference's line moves to the next page with it when too little of it would stay. A first paragraph kept together, or kept with the next, stays with its reference whole, with the first lines of what it is kept with. A footnote breaks before a later paragraph kept together, and before paragraphs kept with the next with what they are kept with, as the text does, unless they start its part on the page, which would leave none of it, where it breaks as without them, as the text does at the top of a page. It breaks before a table row whose lines widow control keeps together, and in a row whose lines could go on both pages, between its cells' lines, as a row of the text breaks, with the rest of the row at the top of the next page's footnotes, as Word breaks it. A footnote or endnote that ends with a table has a line below it for the empty paragraph Word puts after the table. A table's header rows aren't repeated above the rest of a footnote on the next page, nor left alone at the bottom of a page, as the table goes on the next page then. The footnote of a line kept with a longer paragraph goes below the first lines of it that the line is kept with, and of one kept with a table, below its first row, and the rest goes on the next page. One longer than a page fills the pages after it, and the text goes on above its end. Before the next section, whether it starts on a new page or not, and before a paragraph with a page break before it, the rest of a footnote goes on pages of its own, which belong to the section its reference is in, and the new section or paragraph starts after them. Before a continuous section, those pages show that section's header and footer, as Word shows them, and in columns, the rest is evened out in the columns of its last page. After a footnote that continues from the page before, the text after a page break at the start of a paragraph goes on the page the footnote ends on, as Word puts it. Before a continuous section numbered afresh, Word numbers each of those pages with the section's first number, and so does `docx/layout`. Before a continuous section, the number of pages of the section the footnote is in isn't worked out, as Word counts it its own way, and the next section's is its own pages, as Word counts them. A line whose footnote can't go on a page with it, such as one that starts with a paragraph kept together that is taller than a page, goes at the top of a page, with the text after it, from the top of a later column too, and the footnote starts on the next page, with those referred to after it after it, the last of those going on to the next page as far as it doesn't fit below its end. So does the last of a line's footnotes that doesn't fit below the others, and the footnote of a table row at the top of a page that fits there, but not with it. In columns, a line referring to a footnote below one that continues on the next page goes on the next page with it. A table row refers to footnotes as a line does: it moves to the next page with a footnote that doesn't fit below it, and one that breaks across pages has each line's footnote on the page the line is on, and breaks after a line whose footnote continues. A table row in a footnote breaks across as many pages as it takes, as Word breaks it, and moves to the next page whole where a cell of it would have none of its lines on the page. Where its footnotes fit whole below fewer of its lines, with the lines that refer to them, it breaks there instead, as Word breaks a row with a table in a cell beside a line whose footnote would otherwise continue. In columns, the footnotes of a page are laid out in the columns too, as Word lays them out: one after the other from the first column, evened out, each part broken at the width of the column it is in, and every column ends above them. Footnotes from another section on the page go on in the columns of its first footnote's. A line or table row in columns whose footnotes don't fit below it moves to the next column, or the next page, with all of them, as Word moves it, and the page is left as it was when a reference moves on as its columns are laid out again for its footnote. At the top of the page's columns, or of the column a section starts in after the section before's, a line stays, and its footnote goes on the page as far as it fits below the lines of every column, with the text going on above it, and continues at the foot of the next page's columns. At the top of a later column, the columns before it are laid out again above as much of the footnote as leaves the line on the page, as Word lays them out: a footnote of 120 lines referred to from line 11 of the first of 2 columns takes 44 lines of each, the columns above it 6, and its reference goes on in the second. The separator above the endnotes goes on the page of their first line, and on each page after the first they are on, the continuation separator is above them, as Word puts them. Each is a line of its paragraph style's text tall, at single spacing, whatever its own spacing, line spacing, size, text and paragraphs, as Word lays them out. A footnote's paragraph borders take room as in the text. Below the continuation separator, as many lines of endnotes go on the page as fit on it without it, so the last can go past the bottom margin by as much as the separator takes, as Word puts them. Footnotes and endnotes are numbered as Word numbers them, 1, 2, 3 and i, ii, iii, or in the format and from the number a document or its sections give, afresh in each section when they say so, and footnotes afresh on each page. A section's own start number adds to the number of notes before it, as Word adds it: after 27 footnotes, a section numbered from 5 numbers its first 32. A footnote or endnote with a mark of its own in place of its number isn't counted, footnotes numbered afresh on each page are numbered on from those of the page numbered so in another section, and a section's footnotes can go just below the text of their page, rather than at its bottom, below the space after a section's last paragraph and the rest of one continued from the page before too, or in columns of their own, evened out, as Word puts them. Word puts the endnotes of a section that says they go at the end of it at the end of the document, unless the document's settings say so too, when each section's go after it, after a separator of their own, but for a section that suppresses its own, whose go after the next's, and so does `docx/layout`. After text in columns, the text is evened out above the endnotes, which are laid out in the columns below their separator, in the first column, the continuation separator at the top of the first column only on the next page, and evened out in the columns they end in, as Word lays them out -- run formatting that changes how much room text takes, as Word lays it out. Superscript and subscript (`superScript`, `subScript`) are drawn at 65% of the text's size, to the nearest half-point and down from a quarter, so 7 points at 11 and 9.5 at 15, and small capitals (`smallCaps`) at 80%, so 9 points at 11; both take up the line of their run's own size, so they never make a line taller. Raised and lowered text (`position`) raises the line's top or lowers its bottom by as much as it goes past the rest of the line: a word raised 6 points makes a line of Calibri 11 120 twips taller, and a smaller word raised a little none. Emphasis marks (`emphasisMark`) take a quarter of their line, over it, or under it for dots below, and both on a line with marks over and under it, with a picture in the line counted in it; line spacing that gives a line less room than a quarter of it adds it below the marks' room, and spacing that gives it at least that, such as 1.25 lines, holds the marks, and spacing of less than a line makes the line and the marks' room that share of themselves. A border around text (`border` on a `TextRun`) takes its space and its width on each side of the text, and above and below it, as wide as a paragraph's border of its style, an art border its size in points, and a space past 31 points only what is left over 32: two runs next to each other with the same border are in one box, a box that goes on to the next line starts again there, also in a word broken across lines, and a line keeps room for its box to end after its last word. A shadow doubles a border's width as Word draws it, whatever its style, and one drawn as a frame takes the room it takes without (`w:shadow`, `w:frame`, in documents Word made), and a picture in the line in a run with a border has its border's room around it, beside it and above and below it, in one box with text in the same border either side of it, and multiple line spacing adds its share of the run's line with the border's room above and below. Text fitted to a width (`w:fitText`, in documents Word made) is one box of that width, which goes on to the next line whole when it doesn't fit, or takes a line of its own and goes past its end when it is wider than the line, and runs one after the other fitted with the same id are one box, as tall as the tallest of their lines. Text with a phonetic guide over it (`w:ruby`, in documents Word made) is one box as wide as the wider of the guide and its base, and its line is as tall as the base makes it and as the guide raised over the base's baseline by its raise (`w:hpsRaise`), as text raised that far. Two lines in one (`w:eastAsianLayout` with `w:combine`) of text that isn't Chinese, Japanese or Korean is drawn at half its size on one row, as Word draws it +- run formatting that changes how much room text takes, as Word lays it out. Superscript and subscript (`superScript`, `subScript`) are drawn at 65% of the text's size, to the nearest half-point and down from a quarter, so 7 points at 11 and 9.5 at 15, and small capitals (`smallCaps`) at 80%, so 9 points at 11; both take up the line of their run's own size, so they never make a line taller. Raised and lowered text (`position`) raises the line's top or lowers its bottom by as much as it goes past the rest of the line: a word raised 6 points makes a line of Calibri 11 120 twips taller, and a smaller word raised a little none. Emphasis marks (`emphasisMark`) take a quarter of their line, over it, or under it for dots below, and both on a line with marks over and under it, with a picture in the line counted in it; line spacing that gives a line less room than a quarter of it adds it below the marks' room, and spacing that gives it at least that, such as 1.25 lines, holds the marks, and spacing of less than a line makes the line and the marks' room that share of themselves. A border around text (`border` on a `TextRun`) takes its space and its width on each side of the text, and above and below it, as wide as a paragraph's border of its style, an art border its size in points, and a space past 31 points only what is left over 32: two runs next to each other with the same border are in one box, a box that goes on to the next line starts again there, also in a word broken across lines, and a line keeps room for its box to end after its last word. A shadow doubles a border's width as Word draws it, whatever its style, and one drawn as a frame takes the room it takes without (`w:shadow`, `w:frame`, in documents Word made), and a picture in the line in a run with a border has its border's room around it, beside it and above and below it, in one box with text in the same border either side of it, and multiple line spacing adds its share of the run's line with the border's room above and below. Text fitted to a width (`w:fitText`, in documents Word made) is one box of that width, which goes on to the next line whole when it doesn't fit, or takes a line of its own and goes past its end when it is wider than the line, and runs one after the other fitted with the same id are one box, as tall as the tallest of their lines. Text with a phonetic guide over it (`w:ruby`, in documents Word made) is one box as wide as the wider of the guide and its base, and its line is as tall as the base makes it and as the guide raised over the base's baseline by its raise (`w:hpsRaise`), as text raised that far. Two lines in one (`eastAsianLayout: { twoLinesInOne: true }`) of text that isn't Chinese, Japanese or Korean is drawn at half its size on one row, as Word draws it - pictures in the line, which stand on the baseline, so a line with text in it is as tall as the picture and the text below the baseline, as Word makes it. A line with a picture is at least as tall as a line of the picture's run's font, and its multiple line spacing adds a share of that, as Word's does. A line of only a picture isn't as tall as a larger paragraph mark, at single spacing - pictures, shapes and charts that text wraps around (`floating` with a `wrap`), as Word lays the text out around them. A line beside a drawing has the room beside it, with the drawing's distances from the text (`margins`) and the room its effects take, such as a shape's line or shadow, and a line with no room beside it goes below it. Square, tight and through wrapping put the text beside the drawing's box, on the side or sides its wrapping's `side` says, the left first, and Word puts as many words in the room on a side as fit there, and none when the next word doesn't fit, nor in a room narrower than 18 points, so a line with no wider room goes below the drawing. Top and bottom wrapping puts the lines below the drawing. Drawings that overlap keep the text out of all their room. A drawing in a margin, where there is no text, leaves the lines as they are. A line beside a drawing starts at the drawing's edge or the paragraph's left indent, whichever is further in, and its first line is indented from there. A drawing is placed against the page, its margins, the column, or the paragraph or line it is anchored in, as its `horizontalPosition` and `verticalPosition` say: at an offset, which places the drawing without its effects, lined up with them, with its effects, or at a percentage of them, as `docx/shapes` places shapes, and its percentage sizes are a share of the page or its margins: the inside and outside margins are those it is placed against on its page. Lined up inside or outside against the margins, it is lined up with them, and against the page, down it, it is at the top of the page, inside on odd pages and outside on even ones, half the header's distance from the page's top below it, and at the bottom otherwise, half the footer's distance above it. One placed by its simple position is placed from the page's top left corner by that. Placed against its paragraph, it is at the top of the paragraph, below the space after the paragraph before, which is that paragraph's, and above its own space before, and no higher than the top of the page's text. Where it would go past the bottom of the page's text, the paragraph moves to the next column or page with it, above footnotes too, and a paragraph whose first line goes below a drawing with top and bottom wrapping keeps its own space before above that line. Placed against its line, it is at the line its anchor is on before the text goes round it, though the text going round it can move the anchor on to the next line. One anchored in a line that goes on to the next page goes there with it, against the top of the paragraph's part on that page. The text before a drawing's paragraph on its page goes round it too, as Word lays the page out again with it, and the drawing stays where it was first placed, though its paragraph moves down: with top and bottom wrapping, the lines before it that its distance above it reaches go below it. Where that moves the paragraph on to the next page, it starts there with the drawing, and the page is laid out again without it. Of two drawings that may not overlap (`allowOverlap: false`), the later is moved out of the way across the page, at the height it was placed at: to the right of the other, their boxes side by side, or to the left of it when it is lined up at the right. A table that fits beside a drawing at its indent goes beside it, as does one that fits past a drawing on its left, with its indent from there, and one that doesn't fit goes below it; one sized to its text goes beside it as wide as it is in the column. Paragraphs kept with the next are kept with as many of the next paragraph's lines beside a drawing as they would be without it, and move to the next page with a paragraph that moves there with its drawing. Those with drawings of their own move to the next page with the next, and their drawings with them, and those kept with a table stay where they are when the next starts on their page. Columns are evened out with the drawings in them. A turned picture wraps the text around its box as it is before it is turned. A drawing that text wraps around in a header or footer, placed against the page or its margins, is on each page that shows the header or footer, and the body's text goes round it as round its own, as Word lays it out. So is one in the first line of a header's first paragraph placed against its paragraph or line, which is the top of the header, and one placed against a column of a section of several by a distance from its left, which is the left margin, and the header's lines go round its drawings, as the body's do. Drawings behind or in front of the text don't move the body's lines. A drawing beside the page's footnotes leaves their lines as they are - tables that text wraps around (a table's `float`), as Word lays the text out around them: the text after the table goes beside it, as beside a picture with square wrapping, kept from it by its distances from the text (`leftFromText`, `rightFromText`, `topFromText` and `bottomFromText`), and at least half a point from it across the page, as Word keeps it: half a point with none given, or with a smaller one. A table is placed across against the page, its margins or the column (`horizontalAnchor`), and down against the page, its margins or the top of the paragraph after it (`verticalAnchor`), at a distance (`absoluteHorizontalPosition`, `absoluteVerticalPosition`) or lined up with them (`relativeHorizontalPosition`, `relativeVerticalPosition`). Without `horizontalAnchor` it is placed against the column, and without `verticalAnchor` against the margins, and lined up inline against the text (`RelativeVerticalPosition.INLINE`), it is at the top of the paragraph after it. Its room is as wide as its rows with the halves of its borders left and right, on one side or both, or 0.75 points wider than its rows without any borders, which borders between its rows alone count as, and as tall as its rows, and its indent doesn't move it. It is below the space after the paragraph before, and the paragraph after it has all of its space before below that, as after a table. It is placed against the top of what comes after it: a paragraph, the empty paragraph that ends its section, which takes a line after it then, and whose next section on the page goes round it too, a table, or the empty paragraph Word adds after it at the end of the document. Tables one after the other before a paragraph each go round it, and the paragraphs after it go round it too while they are beside it. Its footnotes are on its page. Of two that may not overlap (`overlap: OverlapType.NEVER`), the later moves to the right until the room it keeps the text out of is beside the other's, or to the left of the other when it has no room on the right, or is lined up at the right. One that goes past the bottom of the page is broken between its rows: those that fit stay where it was placed, the rest go at the top of the next pages, below its header rows, which go there again, and the paragraph after it starts beside its last rows. One in a footnote or an endnote is laid out in the note's text, as a table that doesn't float. One before a table that moves on to the next page stays where it was placed, as does one anchored in a paragraph kept with the next that moves on to the next page with the next @@ -219,7 +219,7 @@ The pages are laid out with the widths and heights of the characters of the font - sections, with their page sizes, margins, columns, headers and footers, how they start, and their page numbering. Page numbers are written in Word's number formats as Word writes them, such as roman numerals, letters, words ("twenty-one") and the numbers of other languages, but for those it leaves blank (see below), and with chapter numbers in front of them (`chapterHeadingLevel`), such as 2-5 for page 5 of chapter 2. Each column's lines are broken at its own width, so a paragraph that goes on into a column of another width is broken again there, as Word breaks it. Widow control counts the lines left for the next column as they are broken in the column before, as Word counts them, and a table sized to its text keeps the widths it was sized to in each column it goes on into, as Word keeps them, going past the edge of a narrower one. Columns before a continuous section break are evened out, as Word evens them out, unless a column break is in them or a section in them started in the next column, and the next section starts below the longest. A section that starts in the next column (`SectionType.NEXT_COLUMN`) starts in the next column of the page when the section before has as many columns and one is left, as Word starts it, and on a new page otherwise. When its own columns are of other widths, it is laid out in the page's, where they are and as wide as they are, as Word lays it out, and in its own on the pages after. Its footnotes are laid out in its own columns. A continuous section numbered afresh (`pageNumbers: { start }`) leaves the page it starts on its number, and numbers the next on from its own first number, as Word does: 8 after a section numbered from 7 starts on page 12. When none of it fits on the page before, the page it starts at the top of is its first, numbered 7. One that starts in the next column of a page numbers on through the document, as Word numbers it. A gutter is beside the page's text, or above it in a document that puts it at the top (`w:gutterAtTop`), as Word takes it from the page's height, on every page with mirrored margins too, and below a negative top margin, which the header doesn't push the text below. A paragraph kept together that is taller than a column goes down only the first column of each page, as Word lays it out, from the top of a new page unless it is at the top of this one, and what follows it goes on below it. In columns of different widths it does when it is taller than each of them. One taller than some of them but not others goes in the first column, from where it is, that it fits in, as Word moves it: from the top of a narrow first column to a wide second, and past a narrow second column to a new page, in 3 columns or more as in 2, and the paragraphs kept with the next before it go with it. Paragraphs kept with the next before one taller than each column go to the new page with it, unless they are at the top of the page already, and it moves on to the next page, as Word moves them, so they are alone on theirs. A section that ends with a table has a line below it for the empty paragraph that ends the section, as Word has it - in [templates](#templates), the divisions of a web page that paragraphs are in (`w:divId`), as documents made from HTML have them, laid out as Word lays them out: a paragraph is indented by the margins left and right of its division and of the divisions that division is in, with the division's borders outside them as a paragraph's borders, and a division's paragraphs are in one box, with its margins above its first and below its last, and at the top of a page below the border and its space, without the margin. Word draws the box once, round the first run of the division's paragraphs: its paragraphs after other paragraphs have its borders left and right but none above or below, its margins above the first and below the last, which stand in for less space before or after of the paragraph's own and give way to more, and the larger of a margin and the space of the paragraph or division next to it between them. And pages printed two to a sheet or folded as a booklet, either way round (`w:printTwoOnOne`, `w:bookFoldPrinting` and `w:bookFoldRevPrinting`), which Word lays out as the section's pages, as it does without - a section's document grid (`grid`), as Chinese and Japanese documents and Word's templates for them have it. On a grid of lines (`DocumentGridType.LINES`), each line takes as many of the grid's lines (`linePitch`) as its own height needs, with its text in the middle, as Word lays it out: at 360 twips, a line of Times New Roman of up to 15.5 points takes one, and from 16 points two. Multiple line spacing takes the grid's lines times the spacing when that is more, so 1.08 lines are 388.8 twips, at least a height takes that height when it is more, and exact spacing is as it is without the grid. The space before and after a paragraph isn't put on the grid's lines, a line of space before or after (in lines) is one of them, and the room below the last line's text can go below the bottom of the page. The lines of table cells, headers and footers aren't on the grid, nor the lines above footnotes and endnotes, but footnotes and endnotes are. A paragraph whose `snapToGrid` is off, in documents Word made, isn't on the grid's lines. A grid of lines and characters (`DocumentGridType.LINES_AND_CHARS`) also adds its `charSpace`, in 4096ths of a point, after each character, and a quarter of a character more between Chinese, Japanese or Korean characters and Latin letters, as Word does. One that snaps to characters (`DocumentGridType.SNAP_TO_CHARS`) puts each Chinese, Japanese or Korean character in as many cells as it needs, as many cells as fit across a column at the size of the Normal style's text and the `charSpace` more, spread evenly across it, and the other text between them on a line in as many cells as it needs together, with text spaced out by its run (`characterSpacing`) as wide as it is spaced. In columns of different widths each column has cells of its own. A left tab, and a line beside a drawing, start at the next cell, Chinese, Japanese or Korean text at a right or centred tab ends at the stop, or is centred on it, in its cells, a picture in the line takes as many cells as it needs after the text before it, a word longer than its line goes on to the next, a word with soft hyphens breaks at the last whose part fits in the cells left, and a justified or distributed line isn't squeezed. Characters of indents are the grid's characters, an indent of part of one is rounded up to the next cell, each line's on its own, as a first line indent of part of a cell beside a left indent of part of one, and an indent of part of a cell before the margin, are, a hanging indent's other lines go that many more cells in, and a tab goes to its stop and the text after it to the next cell, as Word lays them out. Footnotes are on the grid as the body is, and endnotes on the last section's grid. Kerned text is kerned on a grid of characters, and on one that snaps to characters takes as many cells as it needs kerned. On a grid of lines and characters, text in a font that isn't East Asian, such as digits in Calibri, has no quarter of a character beside Chinese, Japanese or Korean characters. Emphasis marks take their room in the line before it is put on the grid, with multiple line spacing and at least a height too. A run with `snapToGrid: false` isn't on a grid of characters, and headers and footers aren't. Sections whose text direction (`page: { textDirection }`) runs across the page are laid out as those without one -- text that runs down the page (`page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }`, and the other directions down it of documents Word made), as Chinese and Japanese documents have it, laid out as Word lays it out: each line runs from the top margin to the bottom one, and the lines go across the page from the right margin, or from the left for the directions that put them that way, each as far from the one before as it is tall, on the section's grid if it has one. Chinese, Japanese and Korean characters in fonts whose characters are all an em, such as MS Mincho and SimSun, are an em down the line, and Latin text is on its side, as wide as it is across a page. Indents are from the top and bottom margins, and the space before and after a paragraph is across the page. Half-width katakana are on their side, half an em each. A tab to a left stop, a border around text or around the paragraph, emphasis marks, superscript and subscript, and a justified line with spaces take the room they take across the page, and a footnote goes below the text, at the left of the page. Two digits set across the line (`w:eastAsianLayout w:vert`) take as much room along it as the line is tall. A gutter is beside the right margin, a negative top or bottom margin is as far from the edge as a positive one, and a grid that snaps to characters puts its cells along the lines. The header and footer stay across the top and bottom of the page, and a header doesn't push the lines down. A section whose text runs down the page starts a new page after one whose text runs across it, as a continuous section does too, and a continuous one goes on on the page after text that runs down it the same way. Endnotes referred to from text that runs down the page go at the end of the document, down the page too, and endnotes from a section followed by one whose text runs another way end with their own section, before it, as Word ends them +- text that runs down the page (`page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }`, and the other directions down it of documents Word made), as Chinese and Japanese documents have it, laid out as Word lays it out: each line runs from the top margin to the bottom one, and the lines go across the page from the right margin, or from the left for the directions that put them that way, each as far from the one before as it is tall, on the section's grid if it has one. Chinese, Japanese and Korean characters in fonts whose characters are all an em, such as MS Mincho and SimSun, are an em down the line, and Latin text is on its side, as wide as it is across a page. Indents are from the top and bottom margins, and the space before and after a paragraph is across the page. Half-width katakana are on their side, half an em each. A tab to a left stop, a border around text or around the paragraph, emphasis marks, superscript and subscript, and a justified line with spaces take the room they take across the page, and a footnote goes below the text, at the left of the page. Two digits set across the line (`eastAsianLayout: { horizontalInVertical: true }`) take as much room along it as the line is tall. A gutter is beside the right margin, a negative top or bottom margin is as far from the edge as a positive one, and a grid that snaps to characters puts its cells along the lines. The header and footer stay across the top and bottom of the page, and a header doesn't push the lines down. A section whose text runs down the page starts a new page after one whose text runs across it, as a continuous section does too, and a continuous one goes on on the page after text that runs down it the same way. Endnotes referred to from text that runs down the page go at the end of the document, down the page too, and endnotes from a section followed by one whose text runs another way end with their own section, before it, as Word ends them ## What it leaves blank @@ -273,7 +273,8 @@ It stops at the first thing it can't lay out yet, and the page numbers of the he - a page reference, number of pages or page number in a format other than those above, or with a picture Word's text isn't known for, as above, or past what its format writes, such as 781 in letters - in a document in compatibility mode, which Word lays out as Word 2010, 2007 or 2003 did (one saved by those versions of Word, or by an application that writes their mode, or given `compatibility: { version: 14 }`, 12 or 11), what those versions lay out unlike Word 2013 and haven't been seen laying out: a line beside a frame in a gap between 62.5 and 75 points, or of text centred or aligned right in one narrower than 75, or beside a picture or a table that text wraps around in one narrower than 25 points for text aligned left, 50 for justified, 75 for centred and 94 for right-aligned, a line whose only room is a gap beside a frame that they leave empty, a table sized to its text in a table cell indented or as a share of its width, a table with space between its cells or a share of the width widened for a long word or with its rows evened out, and any of the `compatibility` options, which Word 2013 leaves out in its own mode, but the older ones may follow; and in Word 2007's and 2003's modes, VML shapes that text flows around other than a text box, embedded objects, and VML drawings in a header, footer or text box. The rest is laid out as in Word 2013's mode, but that: justified and distributed lines, and lines justified for Thai or with a low kashida, aren't squeezed, so they break as lines aligned left do; a tab to a stop past the end of the line goes to that stop on the line, past the margin, and the rest of the paragraph's text stays on that line as far as 22 inches from where the lines start, where it goes on to the next line; a gap of 62.5 points or less beside a frame is left empty, of text aligned left or justified, and the line goes in the room beside it; a table sized to its text has its first and last cells' margins beside the room for it, the page's text or what its indent leaves of it, as Word 2010 and before line a table's text up with its indent rather than its borders, but in a table cell, and one of a share of the width is that share of the room with the margins, whatever its indent; a table whose cells all have widths grows for a long word to the room with the margins beside it, its columns narrowed in proportion to their widest words, and has its rows evened out as Word 2013 does; a table that text wraps around is placed with its first cell's text where it is placed across the page, sized to its text too, and one lined up across the page as Word 2013 places it; ligatures are drawn only with Word's `enableOpenTypeFeatures` on, as Word 2010 writes it; and in Word 2007's and 2003's modes, Chinese and Japanese text breaks only at its spaces, as Latin text does, in an East Asian language too, and a text box's or a shape's outline takes no room in its line, nor beside a text box that text flows around. A mode Word doesn't have, such as 13, stops the layout - a compatibility setting that changes how Word lays out lines in compatibility mode 15 in a way not yet followed: with `suppressTopSpacing`, a line at the top of a page or column on a document grid; with `useFELayout`, Chinese, Japanese and Korean text beside letters of another script than Latin, East Asian punctuation or full-width forms beside Latin letters or digits, or Chinese, Japanese and Korean text beside Latin letters or digits in a font whose average character width isn't known, such as Courier New, Yu Mincho or a bold East Asian font, and any text where another of the East Asian `compatibility` options is on too. `suppressTopSpacing` is followed otherwise: Word leaves out the space above the text of a line at the top of a page or column, a paragraph's first or a later one, and below the space before a section's first paragraph too, at exact spacing all but 9.6 points of the 80% of the line above its baseline, and at at-least spacing all but 9.6 points of that height, whether the line is taller or shorter than it, in a document of any default font and below a header too, and leaves a line of single or multiple spacing as it is, of less than a line too, as it does the lines of a paragraph with a border above it, its first and a later one at the top of a page, and the lines of a table's cells. `useFELayout` is followed too: Word puts half the average width of a character of the font before, at its size, between Chinese, Japanese or Korean text and a Latin letter beside it (`w:autoSpaceDE`, in templates), and between it and a digit (`w:autoSpaceDN`), as the paragraph has them on unless it turns them off: 52.5 twips after MS Mincho 10.5 and 54.7 after Calibri 10.5, and nothing beside a space or punctuation. It leaves the lines of other paragraphs as they are. The other `compatibility` options, which ask for an older Word's or another application's layout, Word lays out lines with as without them in its own mode, so they don't stop it, and `doNotUseHTMLParagraphAutoSpacing` is followed. In [templates](#templates), Word's own settings (`overrideTableStyleFontSizeAndJustification`, `enableOpenTypeFeatures`, `doNotFlipMirrorIndents`, `differentiateMultirowTableHeaders`, `useWord2013TrackBottomHyphenation`, `allowHyphenationAtTrackBottom` and `allowTextAfterFloatingTableBreak`) leave Word's lines as they are too, and those it doesn't know, such as ones a later Word may write, stop it whether they are on or off. Settings for other applications, whose `w:uri` isn't Word's, are left to them, as Word leaves them -- in [templates](#templates), what `docx` doesn't write and Word lays out in ways not yet followed: space between a row's cells as a share of the table's width, a table indent of a type other than twips or a share of the width, a row with table properties of its own other than borders and cell margins, a table style with formatting of its rows or cells other than its rows' height, its rows kept whole and its cells' margins, or a part of one for some cells with properties other than borders, margins, a height for its rows, its rows kept whole and space between cells, text with a phonetic guide, text fitted to a width with other than text in it, wider than its line or in runs of other sizes or fonts, two lines in one with brackets, of Chinese, Japanese or Korean text or at a size of a fraction of a point, and horizontal in vertical text, ink and other content parts, a subdocument, a paragraph in an HTML division with indents or borders of its own, with automatic space before or after it or space in lines, with space before or after it of its own below the division's border above it or above the one below it or between two of its paragraphs, without a border above it at the top of a page or column, in a table cell, note, header, footer or text box, or in a division next to another or to a paragraph with space between them where the division's border is, or in a document that adds the space after a paragraph to the space before the next, in another with borders or other margins above or below, or that is a quotation or a page's body, cells merged across columns as old versions of Word wrote them with text after the first, footnotes in more than 4 columns of their own, or in columns of their own in a section of several columns, of text that runs down the page, or whose columns are spaced otherwise than half an inch apart, endnotes numbered afresh on each page, footnotes numbered afresh on each page after a section on the page numbered otherwise, or in a format not yet written, footnotes anywhere but at the bottom of the page or just below the text, and below the text of columns, or after space below the last paragraph of a page whose text goes on, or of the document, a content control bound to custom XML or the document's properties that Word fills in with other text than is written in it when it opens the document (one whose text is already the XML's is laid out as it is), styles Word updates from the document's template when it opens it, and an imported document (`w:altChunk`) in another format than `.docx`, such as HTML, RTF or plain text, which Word converts its own way, of more than one section, whose formatting is kept as it is (`w:matchSrc`), with a style of its own where its defaults leave out some of the template's, or with a page reference or number of pages, whose number `docx` can't write in it +- two lines in one (`eastAsianLayout: { twoLinesInOne: true }`) with brackets, of Chinese, Japanese or Korean text, with other than text in it or at a size of a fraction of a point, and text set across the line (`horizontalInVertical`) in text that runs across the page, or squeezed into its line (`fitToLine`) +- in [templates](#templates), what `docx` doesn't write and Word lays out in ways not yet followed: space between a row's cells as a share of the table's width, a table indent of a type other than twips or a share of the width, a row with table properties of its own other than borders and cell margins, a table style with formatting of its rows or cells other than its rows' height, its rows kept whole and its cells' margins, or a part of one for some cells with properties other than borders, margins, a height for its rows, its rows kept whole and space between cells, text with a phonetic guide, text fitted to a width with other than text in it, wider than its line or in runs of other sizes or fonts, ink and other content parts, a subdocument, a paragraph in an HTML division with indents or borders of its own, with automatic space before or after it or space in lines, with space before or after it of its own below the division's border above it or above the one below it or between two of its paragraphs, without a border above it at the top of a page or column, in a table cell, note, header, footer or text box, or in a division next to another or to a paragraph with space between them where the division's border is, or in a document that adds the space after a paragraph to the space before the next, in another with borders or other margins above or below, or that is a quotation or a page's body, cells merged across columns as old versions of Word wrote them with text after the first, footnotes in more than 4 columns of their own, or in columns of their own in a section of several columns, of text that runs down the page, or whose columns are spaced otherwise than half an inch apart, endnotes numbered afresh on each page, footnotes numbered afresh on each page after a section on the page numbered otherwise, or in a format not yet written, footnotes anywhere but at the bottom of the page or just below the text, and below the text of columns, or after space below the last paragraph of a page whose text goes on, or of the document, a content control bound to custom XML or the document's properties that Word fills in with other text than is written in it when it opens the document (one whose text is already the XML's is laid out as it is), styles Word updates from the document's template when it opens it, and an imported document (`w:altChunk`) in another format than `.docx`, such as HTML, RTF or plain text, which Word converts its own way, of more than one section, whose formatting is kept as it is (`w:matchSrc`), with a style of its own where its defaults leave out some of the template's, or with a page reference or number of pages, whose number `docx` can't write in it When laying out the pages again with the page numbers it worked out still changes them after three passes, as when a table of contents wraps one way with a number and the other way without it, all of them are left blank, and `layoutDocument` lays out the pages without them. diff --git a/docs/usage/text.md b/docs/usage/text.md index 47dbaa0706..a8d2c64657 100644 --- a/docs/usage/text.md +++ b/docs/usage/text.md @@ -155,6 +155,74 @@ const doc = new Document({ }); ``` +### Two Lines in One + +`eastAsianLayout` gives a run Word's East Asian typography (`w:eastAsianLayout`). `twoLinesInOne` sets the run's text in two lines within one line, each at half the text's size, as Word's Two Lines in One does, and `brackets` draws `"round"`, `"square"`, `"angle"` or `"curly"` brackets around it. Runs next to each other with the same `group` are set together, so the two lines can be formatted differently. + +```ts live +import { Document, Paragraph, TextRun, TwoLinesInOneBrackets } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun({ text: "财政部", size: 32 }), + new TextRun({ text: "国家税务总局", size: 32, eastAsianLayout: { twoLinesInOne: true } }), + new TextRun({ text: "文件", size: 32 }), + ], + }), + new Paragraph({ + children: [ + new TextRun({ text: "Meeting ", size: 32 }), + new TextRun({ + text: "October 2026", + size: 32, + eastAsianLayout: { twoLinesInOne: true, brackets: TwoLinesInOneBrackets.ROUND }, + }), + ], + }), + new Paragraph({ + children: [ + new TextRun({ text: "One group: ", size: 32 }), + new TextRun({ text: "bold ", size: 32, bold: true, eastAsianLayout: { twoLinesInOne: true, group: 1 } }), + new TextRun({ text: "and italic", size: 32, italics: true, eastAsianLayout: { twoLinesInOne: true, group: 1 } }), + ], + }), + ], + }, + ], +}); +``` + +In text that runs down the page, `horizontalInVertical` sets the run's text across the line, as Word's Horizontal in Vertical does. Word ignores it on a run that is also `twoLinesInOne`. `fitToLine` (`w:vertCompress`) asks for that text to be squeezed into the line's width, but Word ignores it ([MS-OI29500](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oi29500/efbc3ed1-1349-4572-93a0-a4e0f71e2a8b)), so keep text set across the line to a character or two: + +```ts live +import { Document, PageTextDirectionType, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + properties: { + page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }, + }, + children: [ + new Paragraph({ + children: [ + new TextRun("令和"), + new TextRun({ text: "8", eastAsianLayout: { horizontalInVertical: true } }), + new TextRun("年"), + new TextRun({ text: "10", eastAsianLayout: { horizontalInVertical: true } }), + new TextRun("月"), + ], + }), + ], + }, + ], +}); +``` + ### Shading and Highlighting ```ts live diff --git a/src/file/paragraph/run/east-asian-layout.spec.ts b/src/file/paragraph/run/east-asian-layout.spec.ts new file mode 100644 index 0000000000..d0339c711f --- /dev/null +++ b/src/file/paragraph/run/east-asian-layout.spec.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; + +import { Formatter } from "@export/formatter"; + +import { TwoLinesInOneBrackets, createEastAsianLayout } from "./east-asian-layout"; + +describe("createEastAsianLayout", () => { + it("should write two lines in one as w:combine", () => { + const tree = new Formatter().format(createEastAsianLayout({ twoLinesInOne: true })); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:combine": true } }, + }); + }); + + it("should write the brackets around two lines in one as w:combineBrackets", () => { + const tree = new Formatter().format(createEastAsianLayout({ twoLinesInOne: true, brackets: TwoLinesInOneBrackets.CURLY })); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:combine": true, "w:combineBrackets": "curly" } }, + }); + }); + + it("should write horizontal in vertical fitted to the line as w:vert and w:vertCompress", () => { + const tree = new Formatter().format(createEastAsianLayout({ horizontalInVertical: true, fitToLine: true })); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:vert": true, "w:vertCompress": true } }, + }); + }); + + it("should write the group as w:id, first as the schema has it", () => { + const tree = new Formatter().format(createEastAsianLayout({ group: 1, twoLinesInOne: true })); + expect(Object.keys(tree["w:eastAsianLayout"]._attr)).to.deep.equal(["w:id", "w:combine"]); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:id": 1, "w:combine": true } }, + }); + }); + + it("should write a group of 0", () => { + const tree = new Formatter().format(createEastAsianLayout({ group: 0, horizontalInVertical: true })); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:id": 0, "w:vert": true } }, + }); + }); + + it("should write false to turn off two lines in one that a style turns on", () => { + const tree = new Formatter().format(createEastAsianLayout({ twoLinesInOne: false })); + expect(tree).to.deep.equal({ + "w:eastAsianLayout": { _attr: { "w:combine": false } }, + }); + }); + + it("should throw for a group that isn't a number, rather than write it as w:id", () => { + expect(() => createEastAsianLayout({ group: NaN })).to.throw(); + }); + + it("should throw for an infinite group, rather than write it as w:id", () => { + expect(() => createEastAsianLayout({ group: Infinity })).to.throw(); + expect(() => createEastAsianLayout({ group: -Infinity })).to.throw(); + }); +}); diff --git a/src/file/paragraph/run/east-asian-layout.ts b/src/file/paragraph/run/east-asian-layout.ts new file mode 100644 index 0000000000..25f877333d --- /dev/null +++ b/src/file/paragraph/run/east-asian-layout.ts @@ -0,0 +1,115 @@ +/** + * East Asian layout module for WordprocessingML run properties. + * + * This module provides Word's two lines in one, which sets a run's text in two half-size lines within one line, and + * horizontal in vertical, which sets a run's text across the line in text that runs down the page. + * + * Reference: ISO/IEC 29500-1, 17.3.2.10 eastAsianLayout + * + * @module + */ +import { BuilderElement, type XmlComponent } from "@file/xml-components"; +import { decimalNumber } from "@util/values"; + +/** + * Brackets Word draws around text set as two lines in one. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * + * + * ``` + * + * @publicApi + */ +export const TwoLinesInOneBrackets = { + /** No brackets */ + NONE: "none", + /** Round brackets: ( ) */ + ROUND: "round", + /** Square brackets: [ ] */ + SQUARE: "square", + /** Angle brackets: < > */ + ANGLE: "angle", + /** Curly brackets: { } */ + CURLY: "curly", +} as const; + +/** + * Options for the East Asian layout of a run's text. + * + * @publicApi + */ +export type IEastAsianLayoutOptions = { + /** Sets the run's text in two lines within one line, each at half the text's size, as Word's Two Lines in One does (`w:combine`) */ + readonly twoLinesInOne?: boolean; + /** The brackets drawn around text set as two lines in one (`w:combineBrackets`). Without them, none are drawn. */ + readonly brackets?: (typeof TwoLinesInOneBrackets)[keyof typeof TwoLinesInOneBrackets]; + /** + * Sets the run's text across the line in text that runs down the page, as Word's Horizontal in Vertical does (`w:vert`). + * Word ignores it when `twoLinesInOne` is on. + */ + readonly horizontalInVertical?: boolean; + /** + * Asks for text set across the line in vertical text to be squeezed so that it fits in the width of the line + * (`w:vertCompress`). Word ignores it (MS-OI29500, 17.3.2.10), so only other applications may squeeze the text. + */ + readonly fitToLine?: boolean; + /** + * Runs next to each other with the same group are laid out together, as one two lines in one or one piece of + * horizontal in vertical text, so it can be made of runs formatted differently (`w:id`) + */ + readonly group?: number; +}; + +type IEastAsianLayoutAttributes = { + readonly id?: number; + readonly combine?: boolean; + readonly combineBrackets?: (typeof TwoLinesInOneBrackets)[keyof typeof TwoLinesInOneBrackets]; + readonly vert?: boolean; + readonly vertCompress?: boolean; +}; + +/** + * Creates the East Asian layout (`w:eastAsianLayout`) of a run's text. + * + * ## XSD Schema + * ```xml + * + * + * + * + * + * + * + * ``` + * + * @example + * ```typescript + * createEastAsianLayout({ twoLinesInOne: true, brackets: TwoLinesInOneBrackets.ROUND }); + * ``` + */ +export const createEastAsianLayout = ({ + twoLinesInOne, + brackets, + horizontalInVertical, + fitToLine, + group, +}: IEastAsianLayoutOptions): XmlComponent => + new BuilderElement({ + name: "w:eastAsianLayout", + attributes: { + id: { key: "w:id", value: group === undefined ? undefined : decimalNumber(group) }, + combine: { key: "w:combine", value: twoLinesInOne }, + combineBrackets: { key: "w:combineBrackets", value: brackets }, + vert: { key: "w:vert", value: horizontalInVertical }, + vertCompress: { key: "w:vertCompress", value: fitToLine }, + }, + }); diff --git a/src/file/paragraph/run/index.ts b/src/file/paragraph/run/index.ts index e15b80b112..6fbbd34571 100644 --- a/src/file/paragraph/run/index.ts +++ b/src/file/paragraph/run/index.ts @@ -14,6 +14,7 @@ export * from "./run-fonts"; export * from "./sequential-identifier"; export * from "./underline"; export * from "./emphasis-mark"; +export * from "./east-asian-layout"; export * from "./simple-field"; export * from "./comment-run"; export * from "./comments-extended"; diff --git a/src/file/paragraph/run/properties.ts b/src/file/paragraph/run/properties.ts index b359b9a047..c189bd792e 100644 --- a/src/file/paragraph/run/properties.ts +++ b/src/file/paragraph/run/properties.ts @@ -25,6 +25,7 @@ import { } from "@file/xml-components"; import type { PositiveUniversalMeasure, UniversalMeasure } from "@util/values"; +import { type IEastAsianLayoutOptions, createEastAsianLayout } from "./east-asian-layout"; import { type EmphasisMarkType, createEmphasisMark } from "./emphasis-mark"; import { CharacterSpacing, Color, Highlight } from "./formatting"; import { type ILanguageOptions, createLanguageComponent } from "./language"; @@ -200,6 +201,12 @@ export type IRunStylePropertiesOptions = { readonly imprint?: boolean; readonly revision?: IRunPropertiesChangeOptions; readonly language?: ILanguageOptions; + /** + * Word's East Asian typography for the run's text: two lines in one, which sets it in two half-size lines within + * one line, optionally in brackets, and horizontal in vertical, which sets it across the line in text that runs + * down the page + */ + readonly eastAsianLayout?: IEastAsianLayoutOptions; readonly border?: IBorderOptions; readonly snapToGrid?: boolean; /** Hides the text. `false` shows text that the run's style hides. */ @@ -402,6 +409,10 @@ export class RunProperties extends IgnoreIfEmptyXmlComponent { this.push(createLanguageComponent(options.language)); } + if (options.eastAsianLayout) { + this.push(createEastAsianLayout(options.eastAsianLayout)); + } + if (options.specVanish !== undefined) { // https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_specVanish_topic_ID0EIE1O.html this.push(new OnOffElement("w:specVanish", options.specVanish)); diff --git a/src/file/paragraph/run/run.spec.ts b/src/file/paragraph/run/run.spec.ts index 0a5cf79fe0..76335b09a0 100644 --- a/src/file/paragraph/run/run.spec.ts +++ b/src/file/paragraph/run/run.spec.ts @@ -6,6 +6,7 @@ import { FootnoteReferenceRun } from "@file/footnotes/footnote/run/reference-run import { Paragraph } from "@file/paragraph"; import { ShadingType } from "@file/shading"; +import { TwoLinesInOneBrackets } from "./east-asian-layout"; import { EmphasisMarkType } from "./emphasis-mark"; import { HighlightColor, TextEffect } from "./properties"; import { PageNumber, Run } from "./run"; @@ -119,6 +120,38 @@ describe("Run", () => { }); }); + describe("#eastAsianLayout()", () => { + it("should set the text as two lines in one in brackets", () => { + const run = new Run({ + eastAsianLayout: { twoLinesInOne: true, brackets: TwoLinesInOneBrackets.ROUND }, + }); + const tree = new Formatter().format(run); + expect(tree).to.deep.equal({ + "w:r": [{ "w:rPr": [{ "w:eastAsianLayout": { _attr: { "w:combine": true, "w:combineBrackets": "round" } } }] }], + }); + }); + + it("should write w:eastAsianLayout after w:lang, as the schema orders them", () => { + const run = new Run({ + eastAsianLayout: { horizontalInVertical: true }, + language: { eastAsia: "ja-JP" }, + specVanish: true, + }); + const tree = new Formatter().format(run); + expect(tree).to.deep.equal({ + "w:r": [ + { + "w:rPr": [ + { "w:lang": { _attr: { "w:eastAsia": "ja-JP" } } }, + { "w:eastAsianLayout": { _attr: { "w:vert": true } } }, + { "w:specVanish": {} }, + ], + }, + ], + }); + }); + }); + describe("#smallCaps()", () => { it("it should add smallCaps to the properties", () => { const run = new Run({ diff --git a/src/util/values.spec.ts b/src/util/values.spec.ts index 6da90b2b60..4a254794be 100644 --- a/src/util/values.spec.ts +++ b/src/util/values.spec.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { dateTimeValue, + decimalNumber, hexColorValue, hpsMeasureValue, longHexNumber, @@ -86,6 +87,18 @@ describe("values", () => { }); }); + describe("decimalNumber", () => { + it("should floor a number to an integer", () => { + expect(decimalNumber(10.7)).to.eq(10); + expect(decimalNumber(-5.3)).to.eq(-6); + }); + it("should throw on NaN and infinities, which aren't integers ST_DecimalNumber can hold", () => { + expect(() => decimalNumber(NaN)).to.throw(); + expect(() => decimalNumber(Infinity)).to.throw(); + expect(() => decimalNumber(-Infinity)).to.throw(); + }); + }); + describe("unsignedDecimalNumber", () => { it("should allow valid values", () => { expect(unsignedDecimalNumber(1243)).to.eq(1243); @@ -94,6 +107,7 @@ describe("values", () => { }); it("should throw on invalid values", () => { expect(() => unsignedDecimalNumber(NaN)).to.throw(); + expect(() => unsignedDecimalNumber(Infinity)).to.throw(); expect(() => unsignedDecimalNumber(-10)).to.throw(); }); }); diff --git a/src/util/values.ts b/src/util/values.ts index ad6b79307b..d12207ef39 100644 --- a/src/util/values.ts +++ b/src/util/values.ts @@ -88,16 +88,16 @@ export type RelativeMeasure = `${"-" | ""}${number}${"em" | "ex"}`; * * @param val - The number to validate and convert * @returns The floored integer value - * @throws Error if the value is NaN + * @throws Error if the value is NaN or infinite, which no integer can be written as * * @example * ```typescript * const num = decimalNumber(10.7); // Returns 10 - * const negative = decimalNumber(-5.3); // Returns -5 + * const negative = decimalNumber(-5.3); // Returns -6 * ``` */ export const decimalNumber = (val: number): number => { - if (isNaN(val)) { + if (!Number.isFinite(val)) { throw new Error(`Invalid value '${val}' specified. Must be an integer.`); } return Math.floor(val); @@ -110,7 +110,7 @@ export const decimalNumber = (val: number): number => { * * @param val - The number to validate and convert * @returns The floored positive integer value - * @throws Error if the value is NaN or negative + * @throws Error if the value is NaN, infinite or negative * * @example * ```typescript