diff --git a/.github/workflows/demos.yml b/.github/workflows/demos.yml index e3504ed862..353ef16594 100644 --- a/.github/workflows/demos.yml +++ b/.github/workflows/demos.yml @@ -255,3 +255,9 @@ jobs: # - uses: "./.github/actions/validate-docx" - run: npm run run-ts -- ./demo/114-image-links.ts - uses: "./.github/actions/validate-docx" + - run: npm run run-ts -- ./demo/115-shape-document-styles.ts + # - uses: "./.github/actions/validate-docx" + - run: npm run run-ts -- ./demo/116-shape-swimlanes.ts + # - uses: "./.github/actions/validate-docx" + - run: npm run run-ts -- ./demo/117-shape-page-layout.ts + # - uses: "./.github/actions/validate-docx" diff --git a/demo/115-shape-document-styles.ts b/demo/115-shape-document-styles.ts new file mode 100644 index 0000000000..827748351e --- /dev/null +++ b/demo/115-shape-document-styles.ts @@ -0,0 +1,124 @@ +// cspell:ignore DEEBF +// Shapes sized to fit their text in the document's styles: Word's newer defaults of 11pt Calibri with space after +// each paragraph, a heading style, a character style and paragraph indents. +// See docs/usage/shapes.md. + +import * as fs from "fs"; +import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx"; +import { ShapeCanvasRun, ShapeGroupRun, ShapeRun } from "docx/shapes"; + +const arrow = { color: "404040", width: 1.25, endArrow: "triangle" } as const; + +const doc = new Document({ + styles: { + default: { + // Word's defaults for new documents since 2013, which shapes measure their text in + document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160, line: 259 } } }, + heading2: { run: { font: "Calibri", size: 32, bold: true, color: "2F5496" }, paragraph: { spacing: { before: 240 } } }, + }, + characterStyles: [{ id: "Code", name: "Code", run: { font: "Courier New", size: 20 } }], + paragraphStyles: [{ id: "Note", name: "Note", basedOn: "Normal", run: { italics: true }, paragraph: { indent: { left: 360 } } }], + }, + sections: [ + { + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Shapes in the document's styles")] }), + new Paragraph( + "This document's text is 11pt Calibri with space after each paragraph. Shapes sized to fit their text measure it in the same styles.", + ), + + new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("Text in the document's font")] }), + new Paragraph({ + children: [ + // One line of `text` has no space after it, so it stays in the middle of the shape + new ShapeRun({ + type: "roundedRectangle", + text: "Fits its text", + transformation: { width: "fitText", height: "fitText" }, + fill: "DEEBF7", + line: { color: "5B9BD5" }, + }), + new TextRun(" "), + // Paragraphs of the shape's own keep the space after them + new ShapeRun({ + type: "rectangle", + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("A heading")] }), + new Paragraph({ + children: [new TextRun("and a paragraph with "), new TextRun({ text: "code", style: "Code" })], + }), + new Paragraph({ style: "Note", children: [new TextRun("An indented note")] }), + ], + transformation: { width: 220, height: "fitText" }, + fill: "FFF2CC", + line: { color: "BF9000" }, + }), + ], + }), + + new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("A diagram")] }), + new Paragraph({ + children: [ + new ShapeCanvasRun({ + layout: { type: "flow", direction: "right" }, + children: [ + { + id: "order", + type: "flowChartTerminator", + text: "Order received", + transformation: { width: "fitText", height: "fitText" }, + fill: "A5A5A5", + line: "none", + }, + { + id: "stock", + type: "flowChartDecision", + text: "In stock?", + transformation: { width: "fitText", height: "fitText" }, + fill: "70AD47", + line: "none", + }, + { + id: "ship", + type: "flowChartProcess", + text: "Ship it", + transformation: { width: "fitText", height: "fitText" }, + fill: "4472C4", + line: "none", + }, + { type: "connector", from: "order", to: "stock", line: arrow }, + { + type: "connector", + from: "stock", + to: "ship", + line: arrow, + label: { text: "Yes", position: "start", fill: "FFFFFF" }, + }, + ], + }), + ], + }), + + new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("A group")] }), + new Paragraph({ + children: [ + new ShapeGroupRun({ + layout: { type: "grid", columns: 3 }, + children: ["Small", "Medium sized", "A little longer"].map((text) => ({ + type: "ellipse" as const, + text, + transformation: { width: "fitText" as const, height: "fitText" as const }, + fill: "FBE5D6", + line: { color: "ED7D31" }, + })), + }), + ], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/demo/116-shape-swimlanes.ts b/demo/116-shape-swimlanes.ts new file mode 100644 index 0000000000..82131f65dd --- /dev/null +++ b/demo/116-shape-swimlanes.ts @@ -0,0 +1,127 @@ +// cspell:ignore DEEBF FBE5D6 EDEDED +// A process in swimlanes: each step goes in the lane of the team that does it, and the flow runs along the lanes. +// See docs/usage/shapes.md. + +import * as fs from "fs"; +import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx"; +import { type IShapeCanvasChildOptions, ShapeCanvasRun } from "docx/shapes"; + +const arrow = { color: "404040", width: 1.25, endArrow: "triangle" } as const; + +// A step as wide as its text +const step = (id: string, text: string, lane: string, fill: string): IShapeCanvasChildOptions => ({ + id, + lane, + type: "flowChartProcess", + text, + transformation: { width: "fitText", height: 40 }, + fill, + line: "none", +}); + +const process: readonly IShapeCanvasChildOptions[] = [ + { + id: "start", + lane: "Customer", + type: "flowChartTerminator", + text: "Report a problem", + transformation: { width: "fitText", height: 36 }, + fill: "A5A5A5", + line: "none", + }, + step("log", "Log the ticket", "Support", "5B9BD5"), + { + id: "known", + lane: "Support", + type: "flowChartDecision", + text: "Known issue?", + transformation: { width: "fitText", height: 70 }, + fill: "70AD47", + line: "none", + }, + step("fix", "Fix the bug", "Engineering", "ED7D31"), + step("reply", "Send the answer", "Support", "5B9BD5"), + { + id: "done", + lane: "Customer", + type: "flowChartTerminator", + text: "Problem solved", + transformation: { width: "fitText", height: 36 }, + fill: "A5A5A5", + line: "none", + }, + { type: "connector", from: "start", to: "log", route: "elbow", line: arrow }, + { type: "connector", from: "log", to: "known", line: arrow }, + { type: "connector", from: "known", to: "reply", line: arrow, label: { text: "Yes", position: "start", fill: "FFFFFF" } }, + { + type: "connector", + from: { id: "known", side: "right" }, + to: "fix", + route: "elbow", + line: arrow, + label: { text: "No", position: "start", fill: "FFFFFF" }, + }, + { type: "connector", from: "fix", to: "reply", route: "elbow", line: arrow }, + { type: "connector", from: "reply", to: "done", route: "elbow", line: arrow }, +]; + +// A shorter process, for lanes across the page +const order: readonly IShapeCanvasChildOptions[] = [ + step("order", "Order", "Customer", "A5A5A5"), + step("pack", "Pack", "Warehouse", "5B9BD5"), + step("ship", "Ship", "Courier", "ED7D31"), + step("receive", "Receive", "Customer", "A5A5A5"), + { type: "connector", from: "order", to: "pack", route: "elbow", line: arrow }, + { type: "connector", from: "pack", to: "ship", route: "elbow", line: arrow }, + { type: "connector", from: "ship", to: "receive", route: "elbow", line: arrow }, +]; + +const doc = new Document({ + styles: { default: { document: { run: { font: "Calibri", size: 22 } } } }, + sections: [ + { + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Swimlanes")] }), + new Paragraph( + "A support process, with a lane for each team. The flow runs down the lanes, and connectors cross between them.", + ), + new Paragraph({ + children: [ + new ShapeCanvasRun({ + layout: { + type: "flow", + spacing: 30, + levelSpacing: 40, + lanes: [ + { name: "Customer", fill: "F2F2F2" }, + { name: "Support", fill: "DEEBF7" }, + { name: "Engineering", fill: "FBE5D6" }, + ], + }, + children: process, + }), + ], + }), + new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun("Lanes across the page")] }), + new Paragraph({ + children: [ + new ShapeCanvasRun({ + layout: { + type: "flow", + direction: "right", + spacing: 20, + levelSpacing: 40, + lanes: ["Customer", "Warehouse", "Courier"], + }, + children: order, + }), + ], + }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/demo/117-shape-page-layout.ts b/demo/117-shape-page-layout.ts new file mode 100644 index 0000000000..599e5e62fc --- /dev/null +++ b/demo/117-shape-page-layout.ts @@ -0,0 +1,109 @@ +// cspell:ignore DEEBF +// Shapes placed by the page: rules as wide as the text, a sidebar sized and placed as percentages of the page, and an +// article whose text flows from one text box into the next. +// See docs/usage/shapes.md. + +import * as fs from "fs"; +import { + AlignmentType, + Document, + HeadingLevel, + HorizontalPositionRelativeFrom, + Packer, + Paragraph, + TextRun, + TextWrappingType, + VerticalPositionRelativeFrom, +} from "docx"; +import { type ShapePercentage, ShapeRun } from "docx/shapes"; + +// A rule as wide as the space between the margins, whatever the page's size, just below the paragraph's first line +const rule = (color: string): ShapeRun => + new ShapeRun({ + type: "line", + transformation: { width: "100%", height: 0 }, + line: { color, width: 2 }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset: 0 }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 380000 }, + allowOverlap: true, + }, + }); + +const article = [ + "Shapes can hold text that flows from one to the next, as the columns of a newsletter do. The text starts in the first shape of the flow, and what doesn't fit carries on in the next one, wherever it is in the document. Word lays the text out when it opens the document, so the flow follows the fonts and styles the document uses, and if one of the boxes changes size in Word, the text moves between them.", + "This article starts in the box on the left and carries on in the box on the right.", +].map( + (text) => + new Paragraph({ + spacing: { after: 120 }, + children: [new TextRun({ text, size: 20 })], + }), +); + +// A column of the article: a box a third of the text's width, below the heading +const column = (offset: ShapePercentage): ShapeRun => + new ShapeRun({ + type: "rectangle", + transformation: { width: "31%", height: 180 }, + line: { color: "BFBFBF", width: 0.75 }, + textFlow: "article", + children: offset === "0%" ? article : undefined, + textOptions: { margins: { top: 6, right: 6, bottom: 6, left: 6 } }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 }, + wrap: { type: TextWrappingType.SQUARE }, + }, + }); + +const doc = new Document({ + styles: { default: { document: { run: { font: "Calibri", size: 22 } } } }, + sections: [ + { + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Page layout"), rule("2E74B5")] }), + new Paragraph( + "The rule under the heading is as wide as the space between the margins, and stays so if the page or its margins change.", + ), + new Paragraph({ + spacing: { before: 240 }, + children: [ + // A sidebar a quarter of the text's width, 75% of the way across it + new ShapeRun({ + type: "roundedRectangle", + transformation: { width: "25%", height: 110 }, + fill: "DEEBF7", + line: "none", + children: [ + new Paragraph({ + alignment: AlignmentType.CENTER, + children: [ + new TextRun({ + text: "A sidebar, placed and sized as percentages of the text's width", + italics: true, + }), + ], + }), + ], + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset: "75%" }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 }, + wrap: { type: TextWrappingType.SQUARE }, + }, + }), + new TextRun( + "A floating shape's size and offsets can be percentages of the page, its margins, or the space between the margins. Word keeps them as percentages, so the shape moves and grows with the page. Other applications draw it as it would be on an A4 page with 1-inch margins.", + ), + ], + }), + new Paragraph({ heading: HeadingLevel.HEADING_2, spacing: { before: 480 }, children: [new TextRun("Text that flows")] }), + new Paragraph({ children: [column("0%"), column("34%")] }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/docs/usage/shapes.md b/docs/usage/shapes.md index 9fcea6dcd0..36f79281f7 100644 --- a/docs/usage/shapes.md +++ b/docs/usage/shapes.md @@ -301,7 +301,7 @@ An `Arrowhead` is one of `"triangle"`, `"stealth"`, `"diamond"`, `"oval"` or `"a ## Text in Shapes -`text` puts a line of text in the middle of a shape, in the document's default font. Each `\n` starts a new, centred paragraph: +`text` puts a line of text in the middle of a shape, in the document's default font. Each `\n` starts a new, centred paragraph. If the document's paragraphs have space before or after them, these paragraphs don't, so the text stays in the middle: ```ts new ShapeRun({ type: "flowChartProcess", text: "Review", transformation: { width: 120, height: 40 }, fill: "DEEBF7" }); @@ -345,7 +345,38 @@ new ShapeRun({ - Both include the text margins, and allow for shapes whose text box is smaller than the shape, such as ellipses and diamonds. - Text that runs up or down the shape (`textOptions.direction`) is measured across the shape's height. -The size is worked out when the document is made, from how wide each character is in the run's font and size. Widths are built in for Calibri, Cambria, Arial, Times New Roman and Courier New. Other fonts are measured as the one most like them: Aptos and other sans-serif fonts as Arial, and serif fonts as Times New Roman. Text without a font or size of its own is measured in Word's defaults, 10pt Times New Roman, because the document's styles aren't known when the shape is made. Give the runs a `font` and `size` if your document uses other defaults. +The size is worked out when the document is written, from how wide each character is in its font and size. Widths are built in for Calibri, Cambria, Arial, Times New Roman and Courier New. Other fonts are measured as the one most like them: Aptos and other sans-serif fonts as Arial, and serif fonts as Times New Roman. + +The text is measured in the document's styles, as Word formats it: + +- The font, size and bold of the document's defaults (`styles.default.document`), the paragraph's style (such as a heading or `Normal`), the run's character style, and the run's own formatting, each overriding the one before. All caps, small caps, hidden text, character spacing and scale are included. +- The paragraph's space before and after, line spacing and indents, from the same styles and the paragraph's own formatting. Contextual spacing leaves out the space between paragraphs of the same style. +- Text in a document with no default font or size is measured in Word's own defaults, 10pt Times New Roman. + +```ts +const doc = new Document({ + // Word's defaults for new documents: 11pt Calibri, with space after each paragraph + styles: { default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160, line: 259 } } } } }, + sections: [ + { + children: [ + new Paragraph({ + // As wide as "Write the draft" in 11pt Calibri + children: [ + new ShapeRun({ + type: "flowChartProcess", + text: "Write the draft", + transformation: { width: "fitText", height: 40 }, + }), + ], + }), + ], + }, + ], +}); +``` + +Fonts that come from the document's theme, such as those in styles copied from a Word document with `externalStyles`, aren't known, as the library doesn't write a theme. Give those styles a font by name if shapes should fit their text. The estimate is close for the built-in fonts and rougher for others. For an exact fit once Word has laid the text out, use `textOptions.resizeShapeToFitText` as well. @@ -523,6 +554,50 @@ new ShapeRun({ ?> Use `TextWrappingType.SQUARE` or `TextWrappingType.TOP_AND_BOTTOM` to wrap text around a shape's box. `TextWrappingType.TIGHT` and `TextWrappingType.THROUGH` wrap it around the shape's outline instead. +### Sizes and positions as percentages + +A floating shape's `width` and `height` can be percentages, such as `"100%"`, and so can its offsets. Word keeps them as percentages, so the shape grows and moves with the page if its size or margins change. A rule as wide as the text: + +```ts +new ShapeRun({ + type: "line", + transformation: { width: "100%", height: 0 }, + line: { color: "2E74B5", width: 2 }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset: 0 }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 380000 }, + }, +}); +``` + +- A percentage size is of the space between the margins, where the text goes. `floating.sizeRelativeTo` makes it of something else: `{ width: "page" }`, or `"leftMargin"`, `"rightMargin"`, `"insideMargin"` or `"outsideMargin"` for a width, and `"page"`, `"topMargin"`, `"bottomMargin"`, `"insideMargin"` or `"outsideMargin"` for a height. +- A percentage offset, such as `offset: "75%"`, is of the width or height of what the position is `relative` to: the page, the space between the margins (`MARGIN`), or one of the margins. It can't be of a column, character, paragraph or line. +- A shape in a group or canvas, or one in the line of text, can't have a percentage size. + +The shape is written with the percentages, as Word 2010 and later read them (`wp14:sizeRelH`, `wp14:sizeRelV`, `wp14:pctPosHOffset` and `wp14:pctPosVOffset`), and with the size and offset it would have on an A4 page with 1-inch margins for applications that don't. LibreOffice reads the percentage sizes, and places the shape by the offset. + +### Text that flows from one shape to the next + +Give shapes the same `textFlow` to make their text flow from one to the next, as the columns of a newsletter do. The first shape of the flow in the document holds the text, and what doesn't fit flows on into the next shape with the same `textFlow`, in the order they are in the document: + +```ts +const column = (offset: `${number}%`, children?: readonly Paragraph[]): ShapeRun => + new ShapeRun({ + type: "rectangle", + transformation: { width: "31%", height: 180 }, + textFlow: "article", + children, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 }, + }, + }); + +new Paragraph({ children: [column("0%", articleParagraphs), column("34%")] }); +``` + +The shapes after the first continue its text, so their own `text` and `children` aren't written. Word and LibreOffice lay out the text when they open the document, so it follows the document's fonts. A flow is only for a `ShapeRun`: shapes in groups and canvases can't be in one. + ## Alternative Text Give a shape `altText` so screen readers can describe it: @@ -536,6 +611,10 @@ new ShapeRun({ }); ``` +A group or canvas without a `description` of its own is described from the text of its shapes and its connectors, following each flow from its start, such as "Start, then Write the draft, then Approved? Yes: Publish, then End. No: Fix it, then back to Write the draft." Branches use the connectors' labels, and a shape that leads to several shapes without labels, as in an org chart, lists them: "Chief Executive leads to Technology, Finance and Operations." Shapes are read by their `altText.name`, or their text, and those with neither are left out. A decorative group or canvas isn't described. Give the diagram a `description` of its own to say something else. + +The rectangle behind a canvas's group, for applications that can't draw canvases, and the bands of swimlanes, are marked as decorative, so screen readers skip them. + ## Groups A `ShapeGroupRun` keeps several shapes together, so they move, resize and wrap as one drawing. Each shape takes the same options as a `ShapeRun`, except `floating`, and its `transformation.offset` positions it in pixels. @@ -623,9 +702,9 @@ To attach to a particular point, give a `point` instead of a `side`, as percenta | `"elbow"` | Horizontal and vertical lines with right-angled bends, like Word's elbow connector | | `"curved"` | A smooth curve that leaves and arrives square to the shapes, like Word's curved connector | -Elbow and curved connectors leave and arrive at right angles to the sides they attach to, and go around a shape when they have to, for example to join two shapes' top sides. `margin` sets how far out they go, in pixels (default `24`, a quarter of an inch). +Elbow and curved connectors leave and arrive at right angles to the sides they attach to, and go around a shape when they have to, for example to join two shapes' top sides. `margin` sets how far out they go, in pixels (default `24`, a quarter of an inch). Elbow connectors whose lines would lie on top of each other between their bends are moved 6 pixels apart, unless they meet at one end, as the lines from a box in an org chart do. -When the usual route would cross another shape in the group or canvas, an elbow or curved connector takes a route with up to four bends that goes around it, a margin away, if there is one. +When the usual route would cross another shape in the group or canvas, an elbow or curved connector takes a route with up to four bends that goes around it, a margin away, if there is one. Where shapes are closer together than two margins, the route goes halfway between them. An elbow connector that needs more than four bends to get around the shapes, which Word's connectors can't have, is drawn as a freeform line instead. Word doesn't keep a freeform line attached to the shapes when they are moved. Without a `route`, a connector is straight, unless a straight line would go through another shape in the group or canvas. Then it takes an elbow route around it. Give `route: "straight"` to keep it straight anyway. @@ -639,10 +718,10 @@ A label is a string, or an object with: - `text`: a string or paragraphs. - `position`: `"start"`, `"middle"` (the default) or `"end"`. At the start or end, the label sits just clear of the shape there, such as `"Yes"` and `"No"` beside a decision. -- `width` and `height`: in pixels. By default the box fits the text, measured as for [`"fitText"`](#sizing-a-shape-to-its-text). +- `width` and `height`: in pixels. By default the box fits the text, measured as for [`"fitText"`](#sizing-a-shape-to-its-text). A label given as a string has no space before or after it. - `fill` and `line`. -A label that would sit on a shape, or on an earlier label, moves along its route until it is clear. If there is no room on the route, it goes beside it. A label is a separate text box, so Word doesn't move it when the connector moves. +A label that would sit on a shape, on an earlier label or on another connector's line moves along its route until it is clear. If there is no room on the route, it goes beside it, on the side with fewer shapes and labels near it. In a flow or tree, the space between two levels grows to fit the labels of the connectors between them. A label is a separate text box, so Word doesn't move it when the connector moves. ### Connectors that meet @@ -693,47 +772,88 @@ new ShapeCanvasRun({ }); ``` -| `layout.type` | Places the shapes | -| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `"flow"` | In levels along the connectors, like a flowchart. Each shape goes on the level after the shapes that connect to it, and each level is ordered so connectors cross as little as they can | -| `"tree"` | As a tree, like an org chart. Each connector joins a parent (`from`) to a child (`to`), and each parent is centred over its children | -| `"grid"` | In rows and columns, in the order they are given, each centred in its cell | +| `layout.type` | Places the shapes | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `"flow"` | In levels along the connectors, like a flowchart. Each shape goes on the level after the shapes that connect to it, each level is ordered so connectors cross as little as they can, and each shape is lined up with the shapes it connects to, so connectors are as straight as they can be | +| `"tree"` | As a tree, like an org chart. Each connector joins a parent (`from`) to a child (`to`), and each parent is centred over its children | +| `"grid"` | In rows and columns, in the order they are given, each centred in its cell | -| Option | Layouts | Description | -| -------------- | ---------- | -------------------------------------------------------------------------------------- | -| `direction` | flow, tree | `"down"` (the default), `"right"`, `"up"` or `"left"`: the way the levels run | -| `spacing` | all | Space between shapes on the same level, or between rows and columns, in pixels | -| `levelSpacing` | flow, tree | Space between one level and the next, in pixels | -| `columns` | grid | The number of columns. By default, enough to make the grid about as wide as it is tall | +| Option | Layouts | Description | +| -------------- | ---------- | ------------------------------------------------------------------------------------------- | +| `direction` | flow, tree | `"down"` (the default), `"right"`, `"up"` or `"left"`: the way the levels run | +| `spacing` | all | Space between shapes on the same level, or between rows and columns, in pixels | +| `levelSpacing` | flow, tree | Space between one level and the next, in pixels | +| `columns` | grid | The number of columns. By default, enough to make the grid about as wide as it is tall | +| `lanes` | flow | Bands the flow runs along, such as the teams that do each step. See [Swimlanes](#swimlanes) | Spacing defaults to 40 pixels between shapes and 50 between levels in a flow, 20 and 40 in a tree, and 40 in a grid. In a flow or tree, a connector without a `side` leaves one level from the side facing the next level and arrives from the side facing the level before, such as bottom to top when the levels run down. A connector back to the level before goes between the same sides the other way, and one that leads further back, such as a loop to redo a step, leaves and arrives at the side (right, or bottom when the levels run across) and goes around the shapes. In a flow, connectors that lead back don't change the levels. -A shape with an `offset` keeps it, and the layout places the other shapes as if it weren't there, starting at the top-left corner. A group inside a canvas or group is placed as one shape, and can have a `layout` of its own for its children. Rotated shapes are placed by the box around them. +In a flow, a connector given a side across the levels places the shape it leads to on that side: a "No" connector that leaves the right of a decision (`from: { id: "review", side: "right" }`) puts its shape to the right of the decision's other shapes, and the decision stays lined up with them. Arriving at the left of a shape does the same. -The positions are worked out when the document is made and written as ordinary offsets, so the diagram can be edited in Word like any other. +A shape with an `offset` keeps it. If it connects to shapes the layout places, it takes part in the layout, and the layout is placed around it: give the first shape of a flow an offset to start the flow there. With several such shapes, the layout is placed as near all of them as it can be. A shape with an `offset` that doesn't connect to the layout's shapes is left out of it, and the layout starts at the top-left corner. A group inside a canvas or group is placed as one shape, and can have a `layout` of its own for its children. Rotated shapes are placed by the box around them. + +The positions are worked out when the document is written, and written as ordinary offsets, so the diagram can be edited in Word like any other. + +### Swimlanes + +Give a flow `lanes` to draw a process in bands, one for each person or team that does its steps. Each shape with a `lane` goes in the band of that name, and shapes without one go in the first. The bands are side by side across the flow, each with a header, with its name, at the start of the flow. Connectors cross between the bands. + +```ts +new ShapeCanvasRun({ + layout: { + type: "flow", + lanes: [{ name: "Customer", fill: "F2F2F2" }, { name: "Support", fill: "DEEBF7" }, "Engineering"], + }, + children: [ + { + id: "report", + lane: "Customer", + type: "flowChartTerminator", + text: "Report a problem", + transformation: { width: "fitText", height: 36 }, + }, + { id: "log", lane: "Support", type: "flowChartProcess", text: "Log the ticket", transformation: { width: "fitText", height: 40 } }, + { id: "fix", lane: "Engineering", type: "flowChartProcess", text: "Fix the bug", transformation: { width: "fitText", height: 40 } }, + { type: "connector", from: "report", to: "log", route: "elbow", line: { endArrow: "triangle" } }, + { type: "connector", from: "log", to: "fix", route: "elbow", line: { endArrow: "triangle" } }, + ], +}); +``` + +A lane is a name, or an object with these options: + +| Option | Type | Description | +| ------------ | ----------- | --------------------------------------------------------------------- | +| `name` | `string` | Written in the lane's header. Shapes go in the lane with `lane: name` | +| `fill` | `ShapeFill` | The lane's background. Default is none | +| `headerFill` | `ShapeFill` | The header's background. Default is light grey | +| `line` | `ShapeLine` | The line around the lane and its header. Default is a thin grey line | + +Each lane is as wide as its shapes and its name need. The shapes in each lane are lined up with each other, and elbow connectors (`route: "elbow"`) keep a process's lines square as they cross between lanes. Swimlanes that run across the page (`direction: "right"`) have their headers on the left. ## Options ### ShapeRun -| Property | Type | Notes | Description | -| ---------------- | ------------------------------- | -------- | -------------------------------------------------------------------------------- | -| `type` | `PresetShapeType` \| `"custom"` | Required | The preset shape, such as `"rectangle"`, `"ellipse"` or `"line"`, or `"custom"` | -| `transformation` | `ShapeTransformation` | Required | Size in pixels, rotation and flip. See [Size and Rotation](#size-and-rotation) | -| `fill` | `ShapeFill` | Optional | See [Fill](#fill). Default is no fill | -| `line` | `ShapeLine` | Optional | See [Line](#line). Default is a black line 1pt wide | -| `adjustments` | `ShapeAdjustments` | Optional | The shape's handles, which depend on `type`. See [Adjustments](#adjustments) | -| `path` | `string` | Optional | SVG path data, for `type: "custom"`. See [Custom Shapes](#custom-shapes) | -| `effects` | `ShapeEffects` | Optional | Shadows, glow, soft edges and reflection. See [Effects](#effects) | -| `text` | `string` | Optional | Centred text inside the shape. See [Text in Shapes](#text-in-shapes) | -| `children` | `Paragraph[]` | Optional | Paragraphs inside the shape | -| `textOptions` | `ShapeTextOptions` | Optional | How the text is laid out. See [Text layout](#text-layout) | -| `floating` | `IFloating` | Optional | Positions the shape on the page. See [Inline and Floating](#inline-and-floating) | -| `altText` | `DocPropertiesOptions` | Optional | `name`, `description` and `title` for screen readers | -| `link` | `string` | Optional | A web address the shape opens when it is clicked | -| `decorative` | `boolean` | Optional | Marks the shape as decorative, so screen readers skip it | +| Property | Type | Notes | Description | +| ---------------- | ------------------------------- | -------- | ------------------------------------------------------------------------------------------------- | +| `type` | `PresetShapeType` \| `"custom"` | Required | The preset shape, such as `"rectangle"`, `"ellipse"` or `"line"`, or `"custom"` | +| `transformation` | `ShapeTransformation` | Required | Size in pixels, rotation and flip. See [Size and Rotation](#size-and-rotation) | +| `fill` | `ShapeFill` | Optional | See [Fill](#fill). Default is no fill | +| `line` | `ShapeLine` | Optional | See [Line](#line). Default is a black line 1pt wide | +| `adjustments` | `ShapeAdjustments` | Optional | The shape's handles, which depend on `type`. See [Adjustments](#adjustments) | +| `path` | `string` | Optional | SVG path data, for `type: "custom"`. See [Custom Shapes](#custom-shapes) | +| `effects` | `ShapeEffects` | Optional | Shadows, glow, soft edges and reflection. See [Effects](#effects) | +| `text` | `string` | Optional | Centred text inside the shape. See [Text in Shapes](#text-in-shapes) | +| `children` | `Paragraph[]` | Optional | Paragraphs inside the shape | +| `textOptions` | `ShapeTextOptions` | Optional | How the text is laid out. See [Text layout](#text-layout) | +| `floating` | `ShapeFloating` | Optional | Positions the shape on the page. See [Inline and Floating](#inline-and-floating) | +| `textFlow` | `string` | Optional | The text flow the shape is in. See [Text that flows](#text-that-flows-from-one-shape-to-the-next) | +| `altText` | `DocPropertiesOptions` | Optional | `name`, `description` and `title` for screen readers | +| `link` | `string` | Optional | A web address the shape opens when it is clicked | +| `decorative` | `boolean` | Optional | Marks the shape as decorative, so screen readers skip it | ### ShapeGroupRun @@ -747,15 +867,16 @@ The positions are worked out when the document is made and written as ordinary o ### ShapeCanvasRun -| Property | Type | Notes | Description | -| ---------------- | ----------------------------------- | -------- | ---------------------------------------------------------------------------------------- | -| `children` | `IShapeCanvasChildOptions[]` | Required | Shapes and connectors, as for a `ShapeGroupRun` | -| `transformation` | `{ width: number; height: number }` | Optional | Size in pixels. Defaults to reaching the right and bottom of the shapes | -| `fill` | `ShapeFill` | Optional | The canvas's background. Default is none | -| `line` | `ShapeLine` | Optional | The canvas's outline. Default is none | -| `layout` | `ShapeLayout` | Optional | Places the children without an `offset`. See [Laying Out Diagrams](#laying-out-diagrams) | -| `floating` | `IFloating` | Optional | Positions the canvas on the page | -| `altText` | `DocPropertiesOptions` | Optional | `name`, `description` and `title` for screen readers | +| Property | Type | Notes | Description | +| ---------------- | ----------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `children` | `IShapeCanvasChildOptions[]` | Required | Shapes and connectors, as for a `ShapeGroupRun` | +| `transformation` | `{ width: number; height: number }` | Optional | Size in pixels. Defaults to reaching the right and bottom of the shapes | +| `fill` | `ShapeFill` | Optional | The canvas's background. Default is none | +| `line` | `ShapeLine` | Optional | The canvas's outline. Default is none | +| `layout` | `ShapeLayout` | Optional | Places the children without an `offset`. See [Laying Out Diagrams](#laying-out-diagrams) | +| `floating` | `IFloating` | Optional | Positions the canvas on the page | +| `altText` | `DocPropertiesOptions` | Optional | `name`, `description` and `title` for screen readers | +| `fallback` | `boolean` | Optional | Whether to write the diagram as a group too, for applications that can't draw canvases. Default is `true`. See [Compatibility](#compatibility) | ### Connector @@ -778,7 +899,7 @@ The positions are worked out when the document is made and written as ordinary o Shapes are written as DrawingML shapes (`wps:wsp`), groups (`wpg:wgp` and `wpg:grpSp`), pictures (`pic:pic`) and drawing canvases (`wpc:wpc`), the formats Word has used since Word 2010. Word 2007 and older can't display them. Other word processors differ in how much of DrawingML they draw, so check the result in the applications your readers use. -A canvas is written with the same shapes as a group after it, in `mc:AlternateContent`. Applications that can't draw canvases, such as Apple Pages, draw the group instead. Word and LibreOffice draw the canvas. +A canvas is written with the same shapes as a group after it, in `mc:AlternateContent`. Applications that can't draw canvases, such as Apple Pages, draw the group instead. Word and LibreOffice draw the canvas. Set `fallback: false` on a `ShapeCanvasRun` to leave the group out, which halves the space the canvas takes up in the document, if its readers only use Word or LibreOffice. LibreOffice (checked with version 26.8) draws most shapes as Word does, but: @@ -789,7 +910,7 @@ LibreOffice (checked with version 26.8) draws most shapes as Word does, but: Apple Pages (checked with version 15.1) draws shapes and groups, and the group in place of a canvas, but: -- It draws text that has no size of its own larger than Word does. Shapes sized with `"fitText"` and connector labels are sized for Word's 10pt, so give the text a `size` if it has to fit in Pages as well. +- It draws text that has no size, in its own formatting or the document's styles, larger than Word does. Shapes sized with `"fitText"` and connector labels are sized for Word's 10pt, so give the document a default size (`styles.default.document.run.size`) if the text has to fit in Pages as well. ## Examples @@ -848,3 +969,27 @@ Shapes sized to fit their text, a flowchart, an org chart and a grid laid out au [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/113-shape-layout.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/113-shape-layout.ts_ + +### Shapes in the document's styles + +Shapes, a canvas and a group sized to fit their text in 11pt Calibri with space after each paragraph, with a heading, a character style and an indented paragraph in a shape. + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/115-shape-document-styles.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/115-shape-document-styles.ts_ + +### Swimlanes + +A support process in swimlanes down the page, with a decision and a branch to another team, and a shorter process in lanes across the page. + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/116-shape-swimlanes.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/116-shape-swimlanes.ts_ + +### Page layout + +A rule as wide as the text, a sidebar sized and placed as percentages of the text's width, and an article whose text flows from one box into the next. + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/117-shape-page-layout.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/117-shape-page-layout.ts_ diff --git a/scripts/compare-shape-renders.ts b/scripts/compare-shape-renders.ts index 2631ef5c26..8b8152d99d 100644 --- a/scripts/compare-shape-renders.ts +++ b/scripts/compare-shape-renders.ts @@ -1,12 +1,15 @@ /** * Compares the pages drawn by scripts/render-shape-demos.sh with the reference images in scripts/shape-demos/references. * - * Usage: npm run run-ts -- scripts/compare-shape-renders.ts [renders directory] [--update] + * Usage: npm run run-ts -- scripts/compare-shape-renders.ts [renders directory] [--references directory] [--update] * * The renders directory defaults to build/shape-demos. A page fails when more than a few of its pixels differ from the * reference, or when a page was added or is missing. An image of each difference, with the changed pixels in red, is * written to the renders directory's `diff` folder. * + * With --references, the pages are compared with those in another directory instead, such as pages Apple Pages drew + * from the master branch (see scripts/render-shape-demos-in-pages.sh). + * * With --update, the references are replaced with the renders. Only update them from renders drawn in the Docker image * (SHAPE_RENDER_IMAGE), as LibreOffice versions and fonts draw pages differently. */ @@ -16,7 +19,7 @@ import { join } from "node:path"; import pixelmatch from "pixelmatch"; import { PNG } from "pngjs"; -const REFERENCES = "scripts/shape-demos/references"; +const DEFAULT_REFERENCES = "scripts/shape-demos/references"; // How different two pixels' colours can be before they count as different, from 0 to 1. This ignores slight changes in anti-aliasing const COLOUR_THRESHOLD = 0.1; // How many pixels of a page can differ before it fails @@ -24,7 +27,11 @@ const MAX_DIFFERENT_PIXELS = 25; const args = process.argv.slice(2); const update = args.includes("--update"); -const renders = args.find((arg) => !arg.startsWith("--")) ?? "build/shape-demos"; +// Where the directory after --references is, if it is given +const referencesIndex = args.indexOf("--references") + 1; +const REFERENCES = referencesIndex > 0 ? args[referencesIndex] : DEFAULT_REFERENCES; +const renders = + args.find((arg, index) => !arg.startsWith("--") && (referencesIndex === 0 || index !== referencesIndex)) ?? "build/shape-demos"; const pagesIn = (directory: string): readonly string[] => existsSync(directory) diff --git a/scripts/render-shape-demos-in-pages.sh b/scripts/render-shape-demos-in-pages.sh new file mode 100755 index 0000000000..350623744e --- /dev/null +++ b/scripts/render-shape-demos-in-pages.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Draws the shape demos with Apple Pages, to check how Pages shows them. Pages only runs on macOS, and GitHub's macOS +# runners don't have it, so this is a check to run by hand. +# +# Usage: scripts/render-shape-demos-in-pages.sh [directory] [demo ...] +# +# The directory (default build/shape-demos) is where scripts/render-shape-demos.sh wrote the demos' .docx files, so +# run that first. Each document is opened in Pages and exported as a PDF, and each page is drawn as a PNG, in the +# directory's `pages` folder. Without demo names, every .docx in the directory is drawn. +# +# The pages are drawn with pdftoppm from Poppler, or in the Docker image the other renders use when SHAPE_RENDER_IMAGE +# names it. Pages asks for permission to be controlled the first time, and the terminal needs to be allowed to. +# +# Pages draws differently from version to version, so compare its pages with others drawn by the same Pages, such as +# a render of the master branch: +# +# scripts/render-shape-demos.sh build/master && scripts/render-shape-demos-in-pages.sh build/master +# (switch branch) scripts/render-shape-demos.sh && scripts/render-shape-demos-in-pages.sh +# npm run run-ts -- scripts/compare-shape-renders.ts build/shape-demos/pages --references build/master/pages + +set -euo pipefail + +DIR="${1:-build/shape-demos}" +shift || true +DEMOS=("$@") +if [ ${#DEMOS[@]} -eq 0 ]; then + for docx in "$DIR"/*.docx; do + [ -e "$docx" ] || { echo "No .docx files in $DIR. Run scripts/render-shape-demos.sh first"; exit 1; } + DEMOS+=("$(basename "$docx" .docx)") + done +fi + +OUT="$DIR/pages" +mkdir -p "$OUT" +rm -f "$OUT"/*.png "$OUT"/*.pdf +DIR="$(cd "$DIR" && pwd)" +OUT="$(cd "$OUT" && pwd)" + +for demo in "${DEMOS[@]}"; do + echo "$demo" + # Pages reads the document, converting it, before it can export it. If Pages shows a dialog, such as a request to + # read the folder, the script waits for it to be answered + osascript - "$DIR/$demo.docx" "$OUT/$demo.pdf" << 'EOF' +on run arguments + set source to POSIX file (item 1 of arguments) + set target to POSIX file (item 2 of arguments) + tell application id "com.apple.Pages" + with timeout of 300 seconds + set theDocument to open source + delay 3 + export theDocument to target as PDF + close theDocument saving no + end timeout + end tell +end run +EOF +done +osascript -e 'tell application id "com.apple.Pages" to quit' + +DRAW='for pdf in "$@"; do pdftoppm -png -r 96 "$pdf" "${pdf%.pdf}"; done' +FILES=() +for demo in "${DEMOS[@]}"; do + FILES+=("$demo.pdf") +done +if [ -n "${SHAPE_RENDER_IMAGE:-}" ]; then + docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "$OUT:/work" -w /work "$SHAPE_RENDER_IMAGE" sh -c "$DRAW" sh "${FILES[@]}" +else + (cd "$OUT" && sh -c "$DRAW" sh "${FILES[@]}") +fi +echo "Pages drew ${#DEMOS[@]} documents in $OUT" diff --git a/scripts/render-shape-demos.sh b/scripts/render-shape-demos.sh index 49601c1d75..66e6c93be8 100755 --- a/scripts/render-shape-demos.sh +++ b/scripts/render-shape-demos.sh @@ -23,7 +23,7 @@ OUT="${1:-build/shape-demos}" shift || true DEMOS=("$@") if [ ${#DEMOS[@]} -eq 0 ]; then - DEMOS=(107-inline-shapes 108-shapes 109-shape-groups 110-shape-connectors 111-shape-styles 112-shape-diagrams 113-shape-layout) + DEMOS=(107-inline-shapes 108-shapes 109-shape-groups 110-shape-connectors 111-shape-styles 112-shape-diagrams 113-shape-layout 115-shape-document-styles 116-shape-swimlanes 117-shape-page-layout) fi SOFFICE="${SOFFICE:-soffice}" WP="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" @@ -42,12 +42,35 @@ for demo in "${DEMOS[@]}"; do # (mc:AlternateContent) is checked twice: as read by applications that use the choice, and by those that don't extracted="$(mktemp -d)" unzip -q -o "$OUT/$demo.docx" -d "$extracted" + + # The Word 2010 drawing extensions (wp14), which the ISO schemas don't have, are checked against their own schema, + # and where they are: a floating drawing's relative sizes come after its graphic, and a percentage offset is the + # choice for a position, with its offset in EMUs as the fallback + perl -0ne 'print qq(); + print "$1\n" while /(|.*?<\/wp14:\3>)/gs; + print "\n"' "$extracted/word/document.xml" > "$extracted/wp14.xml" + if ! xmllint --noout --schema scripts/shape-demos/wp14.xsd "$extracted/wp14.xml" 2> "$extracted/errors.txt"; then + cat "$extracted/errors.txt" + echo "::error::$demo has Word 2010 drawing extensions that don't match their schema" + failed=1 + fi + misplaced="$(perl -0ne '$all = () = /-?\d+<\/wp14:pctPos\1Offset><\/mc:Choice>-?\d+<\/wp:posOffset><\/mc:Fallback><\/mc:AlternateContent><\/wp:position\1>/g; + while (/<\/a:graphic>((?:)+)<\/wp:anchor>/gs) { my $sizes = $1; $placed += () = $sizes =~ / + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/shapes/connector/connector-channels.spec.ts b/src/shapes/connector/connector-channels.spec.ts new file mode 100644 index 0000000000..da250ecf77 --- /dev/null +++ b/src/shapes/connector/connector-channels.spec.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from "vitest"; + +import { separateChannels } from "./connector-channels"; +import type { Point } from "./connector-route"; + +const PIXEL = 9525; + +const route = (...points: readonly (readonly [number, number])[]): readonly Point[] => + points.map(([x, y]) => ({ x: x * PIXEL, y: y * PIXEL })); + +const pixels = (points: readonly Point[]): readonly (readonly [number, number])[] => + points.map(({ x, y }) => [x / PIXEL, y / PIXEL] as const); + +describe("separateChannels", () => { + // Two connectors that loop round the right of a column of shapes, along the same line at x = 124 + const upper = route([100, 25], [124, 25], [124, 225], [100, 225]); + const lower = route([100, 125], [124, 125], [124, 325], [100, 325]); + + it("should move apart lines that lie on top of each other, centred on where they were", () => { + const [first, second] = separateChannels( + [ + { points: upper, movable: true }, + { points: lower, movable: true }, + ], + 6 * PIXEL, + ); + expect(pixels(first)).to.deep.equal([ + [100, 25], + [121, 25], + [121, 225], + [100, 225], + ]); + expect(pixels(second)).to.deep.equal([ + [100, 125], + [127, 125], + [127, 325], + [100, 325], + ]); + }); + + it("should put a line whose connector comes from further along on that side", () => { + // The first connector comes from the right of the line, and the second from the left, so they swap places + const fromRight = route([200, 0], [150, 0], [150, 100], [200, 100]); + const fromLeft = route([100, 50], [150, 50], [150, 150], [100, 150]); + const [right, left] = separateChannels( + [ + { points: fromRight, movable: true }, + { points: fromLeft, movable: true }, + ], + 10 * PIXEL, + ); + expect(right[1].x / PIXEL).to.equal(155); + expect(left[1].x / PIXEL).to.equal(145); + }); + + it("should keep together connectors that meet at one end, and move them as one", () => { + // An org chart's lines from one box share their first bend, and a third connector crosses the same line + const toLeft = route([100, 0], [100, 30], [40, 30], [40, 60]); + const toFarLeft = route([100, 0], [100, 30], [0, 30], [0, 60]); + const across = route([80, 0], [80, 30], [20, 30], [20, 0]); + const [a, b, c] = separateChannels( + [ + { points: toLeft, movable: true }, + { points: toFarLeft, movable: true }, + { points: across, movable: true }, + ], + 6 * PIXEL, + ); + expect(a[1].y).to.equal(b[1].y); + expect(Math.abs(a[1].y - c[1].y)).to.equal(6 * PIXEL); + }); + + it("should leave lines on the same line that don't overlap, even a fraction of a pixel apart", () => { + const higher = route([50, 20], [80.2, 20], [80.2, 48], [111, 48]); + const further = route([50, 90], [80, 90], [80, 62], [111, 62]); + const separated = separateChannels( + [ + { points: higher, movable: true }, + { points: further, movable: true }, + ], + 6 * PIXEL, + ); + expect(separated).to.deep.equal([higher, further]); + + // A line between two others that overlap each other doesn't keep them apart + const long = route([0, 0], [100, 0], [100, 50], [200, 50]); + const between = route([0, 60], [100.4, 60], [100.4, 70], [200, 70]); + const inside = route([300, 10], [100.2, 10], [100.2, 30], [300, 30]); + const [first, middle, last] = separateChannels( + [ + { points: long, movable: true }, + { points: between, movable: true }, + { points: inside, movable: true }, + ], + 6 * PIXEL, + ); + expect(middle).to.equal(between); + expect(first).to.not.equal(long); + expect(last).to.not.equal(inside); + }); + + it("should leave routes that can't move, and lines that only meet end to end", () => { + const [first, second] = separateChannels( + [ + { points: upper, movable: false }, + { points: lower, movable: true }, + ], + 6 * PIXEL, + ); + expect(first).to.equal(upper); + expect(second).to.equal(lower); + + const above = route([100, 0], [124, 0], [124, 100], [100, 100]); + const below = route([100, 100], [124, 100], [124, 200], [100, 200]); + const [touching] = separateChannels( + [ + { points: above, movable: true }, + { points: below, movable: true }, + ], + 6 * PIXEL, + ); + expect(touching).to.equal(above); + }); +}); diff --git a/src/shapes/connector/connector-channels.ts b/src/shapes/connector/connector-channels.ts new file mode 100644 index 0000000000..f730410179 --- /dev/null +++ b/src/shapes/connector/connector-channels.ts @@ -0,0 +1,128 @@ +/** + * Moves apart elbow connectors whose lines would lie on top of each other, where they run along the same line between + * their bends. Not part of the public API. + * + * @module + */ +import type { Point } from "./connector-route"; + +/** + * A connector's route: its ends and corners, and whether its bends can move. + */ +export type ChannelRoute = { + readonly points: readonly Point[]; + /** Whether the lines between its bends can be moved, as an elbow connector's can */ + readonly movable: boolean; +}; + +/** + * A line of a route between two of its bends, which runs along `axis` at `at`, from `low` to `high`. + */ +type Segment = { + readonly route: number; + /** The index of the segment's first point in the route */ + readonly index: number; + /** `"x"` for a line that runs across the page, `"y"` for one that runs down it */ + readonly axis: "x" | "y"; + readonly at: number; + readonly low: number; + readonly high: number; + /** Where the lines before and after it go: before it (negative) or after it (positive) across `at` */ + readonly leaning: number; +}; + +// Lines this close together, in EMUs, are on the same line: a pixel +const SAME_LINE = 9525; + +const segmentsOf = (route: ChannelRoute, routeIndex: number): readonly Segment[] => + route.movable + ? route.points.slice(1, -2).map((from, offset): Segment => { + const index = offset + 1; + const to = route.points[index + 1]; + const axis = Math.abs(from.y - to.y) < 1 ? "x" : "y"; + const across = axis === "x" ? "y" : "x"; + const before = route.points[index - 1]; + const after = route.points[index + 2]; + return { + route: routeIndex, + index, + axis, + at: from[across], + low: Math.min(from[axis], to[axis]), + high: Math.max(from[axis], to[axis]), + leaning: before[across] - from[across] + (after[across] - to[across]), + }; + }) + : []; + +/** + * Splits segments into groups that lie on top of each other: on the same line, and overlapping along it. + */ +const findChannels = (segments: readonly Segment[]): readonly (readonly Segment[])[] => { + // Segments along the same line, to within a pixel + const lines = [...segments] + .sort((a, b) => (a.axis === b.axis ? a.at - b.at : a.axis < b.axis ? -1 : 1)) + .reduce((all, segment) => { + const last = all[all.length - 1]; + return last?.[0].axis === segment.axis && Math.abs(last[last.length - 1].at - segment.at) < SAME_LINE + ? [...all.slice(0, -1), [...last, segment]] + : [...all, [segment]]; + }, []); + // On each line, the segments that overlap one another + return lines + .flatMap((line) => + [...line] + .sort((a, b) => a.low - b.low) + .reduce((channels, segment) => { + const last = channels[channels.length - 1]; + return last !== undefined && segment.low < Math.max(...last.map(({ high }) => high)) - SAME_LINE + ? [...channels.slice(0, -1), [...last, segment]] + : [...channels, [segment]]; + }, []), + ) + .filter((channel) => new Set(channel.map(({ route }) => route)).size > 1); +}; + +const sameEnd = (a: ChannelRoute, b: ChannelRoute): boolean => { + const ends = (route: ChannelRoute): readonly Point[] => [route.points[0], route.points[route.points.length - 1]]; + return ends(a).some((end) => ends(b).some((other) => Math.abs(end.x - other.x) < SAME_LINE && Math.abs(end.y - other.y) < SAME_LINE)); +}; + +/** + * Moves apart the lines of elbow connectors that lie on top of each other between their bends, `spacing` apart and + * centred on where they were. Connectors that meet at one end, such as those fanning out from a box in an org chart, + * stay together. The lines are ordered by where the lines before and after them go, so they cross as little as they can. + * + * @returns The routes, with the lines that were moved + */ +export const separateChannels = (routes: readonly ChannelRoute[], spacing: number): readonly (readonly Point[])[] => { + const channels = findChannels(routes.flatMap(segmentsOf)); + const shifts = channels.flatMap((channel) => { + // Segments of connectors that meet at one end share a lane + const lanes = channel.reduce((all, segment) => { + const lane = all.findIndex((members) => members.some((member) => sameEnd(routes[member.route], routes[segment.route]))); + return lane === -1 ? [...all, [segment]] : all.map((members, index) => (index === lane ? [...members, segment] : members)); + }, []); + const leaning = (lane: readonly Segment[]): number => lane.reduce((total, { leaning: value }) => total + value, 0); + const ordered = [...lanes].sort((a, b) => leaning(a) - leaning(b) || a[0].route - b[0].route); + return ordered.flatMap((lane, position) => + lane.map((segment) => ({ segment, by: (position - (ordered.length - 1) / 2) * spacing })), + ); + }); + + return routes.map((route, routeIndex) => + shifts + .filter(({ segment }) => segment.route === routeIndex) + .reduce( + (points, { segment, by }) => + points.map((point, index) => + index === segment.index || index === segment.index + 1 + ? segment.axis === "x" + ? { ...point, y: point.y + by } + : { ...point, x: point.x + by } + : point, + ), + route.points, + ), + ); +}; diff --git a/src/shapes/connector/connector-route.spec.ts b/src/shapes/connector/connector-route.spec.ts index d918f30f9e..18803c2cf0 100644 --- a/src/shapes/connector/connector-route.spec.ts +++ b/src/shapes/connector/connector-route.spec.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "vitest"; -import { type Bounds, type ConnectorEndpoint, type ConnectorGeometry, type Point, routeConnector } from "./connector-route"; +import { + type Bounds, + type ConnectorEndpoint, + type ConnectorGeometry, + type Point, + fitElbowConnector, + routeConnector, +} from "./connector-route"; const MARGIN = 228600; @@ -318,6 +325,87 @@ describe("routeConnector", () => { expect(geometry).to.deep.include({ type: "elbowConnector", adjustments: { bendX: 50 } }); }); + it("should go through a gap narrower than two margins, and still attach to the shapes", () => { + // A wall of shapes with a gap in it, below the line between the ends. The shapes at the ends of the wall are + // too far away to be tried for places to bend + const wall = Array.from({ length: 15 }, (_, index) => [ + box(900, 450 - 400 * (index + 1), 1100, 450 - 400 * index), + box(900, 550 + 400 * index, 1100, 550 + 400 * (index + 1)), + ]).flat(); + const start = at(0, 0, 0); + const end = at(2000, 0, 180); + const geometry = routeConnector("elbow", start, end, { obstacles: wall }); + expect(geometry.type).to.equal("elbowConnectorFourBends"); + expectConnects(geometry, start, end, 9525); + // Through the middle of the gap + expect(geometry.points[2].y).to.equal(500000); + }); + + it("should go through a gap with two or three bends as the presets do", () => { + // A vertical wall with a gap, and an end past it that faces up + const vertical = Array.from({ length: 15 }, (_, index) => [ + box(900, 450 - 400 * (index + 1), 1100, 450 - 400 * index), + box(900, 550 + 400 * index, 1100, 550 + 400 * (index + 1)), + ]).flat(); + const start = at(0, 0, 0); + const below = at(2000, 1400, 270); + const turning = routeConnector("elbow", start, below, { obstacles: vertical }); + expect(turning.type).to.equal("elbowConnectorThreeBends"); + expectConnects(turning, start, below, 9525); + expect(turning.points[2].y).to.equal(500000); + + // A horizontal wall with a gap, and an end below it that faces left + const horizontal = Array.from({ length: 15 }, (_, index) => [ + box(750 - 400 * (index + 1), 400, 750 - 400 * index, 600), + box(850 + 400 * index, 400, 850 + 400 * (index + 1), 600), + ]).flat(); + const across = at(2000, 1000, 180); + const straight = routeConnector("elbow", start, across, { obstacles: horizontal }); + expect(straight.type).to.equal("elbowConnector"); + expectConnects(straight, start, across, 9525); + expect(straight.points[1].x).to.equal(800000); + }); + + it("should draw a route that needs more than four bends as a line that isn't attached", () => { + const pixels = (x: number, y: number): Point => ({ x: x * 9525, y: y * 9525 }); + const shape = (left: number, top: number, right: number, bottom: number): Bounds => ({ + left: left * 9525, + top: top * 9525, + right: right * 9525, + bottom: bottom * 9525, + }); + const geometry = routeConnector( + "elbow", + { point: pixels(0, 0), angle: 270 }, + { point: pixels(200, 40), angle: 0 }, + { margin: 20 * 9525, obstacles: [shape(220, 100, 260, 160), shape(-20, -80, 20, -60), shape(160, -80, 240, 0)] }, + ); + expect(geometry).to.deep.include({ + type: "freeform", + offset: pixels(0, -20), + width: 220 * 9525, + height: 60 * 9525, + rotation: 0, + flip: { horizontal: false, vertical: false }, + }); + expect(geometry.points).to.deep.equal([ + pixels(0, 0), + pixels(0, -20), + pixels(40, -20), + pixels(40, 20), + pixels(220, 20), + pixels(220, 40), + pixels(200, 40), + ]); + }); + + it("should keep the curved route through an obstacle, rather than draw a line", () => { + const geometry = routeConnector("curved", at(0, 0, 90), at(1000, 0, 0), { + obstacles: [box(-100, 300, 100, 400), box(900, -200, 1300, 400)], + }); + expect(geometry.type).to.not.equal("freeform"); + }); + it("should only look at the obstacles nearest the connector for places to bend", () => { const far = Array.from({ length: 20 }, (_, index) => box(5000 + index * 300, 5000, 5100 + index * 300, 5100)); const start = at(0, 0, 0); @@ -327,4 +415,30 @@ describe("routeConnector", () => { expectConnects(geometry, start, end, 9525); }); }); + + describe("fitElbowConnector", () => { + it("should draw a route whose bends have moved with the preset that bends there", () => { + const start = at(0, 0, 0); + const end = at(1000, 500, 180); + const moved = [start.point, { x: 300000, y: 0 }, { x: 300000, y: 500000 }, end.point]; + const geometry = fitElbowConnector(start, end, moved, MARGIN); + expect(geometry).to.deep.include({ type: "elbowConnector", adjustments: { bendX: 30 } }); + expectConnects(geometry, start, end); + }); + + it("should draw a route with more than four bends as a freeform line", () => { + const points = [ + { x: 0, y: 0 }, + { x: 0, y: -100 }, + { x: 200, y: -100 }, + { x: 200, y: 100 }, + { x: 400, y: 100 }, + { x: 400, y: 50 }, + { x: 300, y: 50 }, + ]; + const geometry = fitElbowConnector({ point: points[0], angle: 270 }, { point: points[6], angle: 0 }, points, 50); + expect(geometry.type).to.equal("freeform"); + expect(geometry.points).to.equal(points); + }); + }); }); diff --git a/src/shapes/connector/connector-route.ts b/src/shapes/connector/connector-route.ts index a5f1b02fa9..d8c49f510d 100644 --- a/src/shapes/connector/connector-route.ts +++ b/src/shapes/connector/connector-route.ts @@ -7,10 +7,11 @@ * outside the box, which is how a connector loops around a shape. * * When an elbow or curved connector's usual route would cross other shapes, the router looks for a route - * with up to four bends that goes around them. + * with up to four bends that goes around them. An elbow connector that needs more bends is drawn as a freeform line. * * @module */ +import { findOrthogonalRoute } from "./orthogonal-route"; import type { PresetShapeType } from "../preset-shape/preset-shape-type"; /** @@ -62,7 +63,11 @@ export type ConnectorRoute = "straight" | "elbow" | "curved"; * The shape that draws a connector. */ export type ConnectorGeometry = { - readonly type: PresetShapeType; + /** + * The connector preset, or a freeform line for an elbow route with more bends than the presets have. A freeform + * line isn't attached to the shapes it joins + */ + readonly type: PresetShapeType | "freeform"; /** Where the connector bends, as percentages of its box */ readonly adjustments: Readonly>; /** Top-left corner of the box, before rotation */ @@ -254,7 +259,7 @@ const findElbowPath = (frame: BoxFrame): BoxPath => (frame.parallel ? findParall * The obstacles a path goes through, or goes nearer to than `clearance`. A path that only touches an obstacle's edge, * as a connector does where it meets a shape, doesn't go through it. */ -const countCrossings = (points: readonly Point[], obstacles: readonly Bounds[], clearance = 0): number => +export const countRouteCrossings = (points: readonly Point[], obstacles: readonly Bounds[], clearance = 0): number => obstacles.filter((obstacle) => points.slice(1).some((to, index) => { const from = points[index]; @@ -407,26 +412,43 @@ const findAvoidingPath = (frame: BoxFrame, obstacles: readonly Bounds[], toPage: ), ]; - // Fewest obstacles crossed, then fewest passed within a margin, then the shortest, counting each bend as a margin's length - const score = (path: BoxPath): readonly number[] => { - const points = path.points.map(toPage); - return [ - countCrossings(points, obstacles), - countCrossings(points, obstacles, margin), - pathLength(path.points) + (path.points.length - 2) * margin, - ]; - }; - const isBetter = (a: readonly number[], b: readonly number[]): boolean => { - const index = a.findIndex((value, position) => value !== b[position]); - return index !== -1 && a[index] < b[index]; - }; - const scored = candidates.map((path) => ({ path, score: score(path) })); - return scored.reduce<(typeof scored)[number] | undefined>( - (best, candidate) => (!best || isBetter(candidate.score, best.score) ? candidate : best), - undefined, - )?.path; + // Only obstacles within a margin of the box around every path can be crossed or passed + const onPage = candidates.map((path) => ({ path, points: path.points.map(toPage) })); + const reach = expandBounds(boundsOfPoints(onPage.flatMap(({ points }) => points)), margin); + const near = obstacles.filter((obstacle) => boundsOverlap(obstacle, reach)); + + // Fewest obstacles crossed, then fewest passed within a margin, then the shortest, counting each bend as a margin's + // length. Each measure is only taken for the paths that are best by the ones before it + type Candidate = (typeof onPage)[number]; + const measures: readonly ((candidate: Candidate) => number)[] = [ + ({ points }) => countRouteCrossings(points, near), + ({ points }) => countRouteCrossings(points, near, margin), + ({ path }) => pathLength(path.points) + (path.points.length - 2) * margin, + ]; + const best = measures.reduce((remaining, measure) => { + const measured = remaining.map((candidate) => ({ candidate, value: measure(candidate) })); + const least = Math.min(...measured.map(({ value }) => value)); + return measured.filter(({ value }) => value === least).map(({ candidate }) => candidate); + }, onPage); + return best[0]?.path; }; +const boundsOfPoints = (points: readonly Point[]): Bounds => ({ + left: Math.min(...points.map(({ x }) => x)), + top: Math.min(...points.map(({ y }) => y)), + right: Math.max(...points.map(({ x }) => x)), + bottom: Math.max(...points.map(({ y }) => y)), +}); + +const expandBounds = ({ left, top, right, bottom }: Bounds, by: number): Bounds => ({ + left: left - by, + top: top - by, + right: right + by, + bottom: bottom + by, +}); + +const boundsOverlap = (a: Bounds, b: Bounds): boolean => a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom; + const pageMapping = (start: ConnectorEndpoint, ex: Point, ey: Point): ((point: Point) => Point) => ({ x, y }: Point): Point => ({ @@ -435,19 +457,81 @@ const pageMapping = }); /** - * The usual elbow path between two ends, or one that goes around the obstacles the usual path goes through. + * The usual elbow path between two ends, or one that goes around the obstacles the usual path goes through. An elbow + * connector that can't get around them with four bends takes a route with more, if there is one. + * + * @returns The path in its box, or the corners of a route with more bends, on the page */ -const findRoutedPath = (start: ConnectorEndpoint, end: ConnectorEndpoint, margin: number, obstacles: readonly Bounds[]): BoxPath => { +const findRoutedPath = ( + route: Exclude, + start: ConnectorEndpoint, + end: ConnectorEndpoint, + margin: number, + obstacles: readonly Bounds[], +): BoxPath | readonly Point[] => { const frame = findElbowFrame(start, end, margin); const path = findElbowPath(frame); const toPage = pageMapping(start, frame.ex, frame.ey); - const crossings = countCrossings(path.points.map(toPage), obstacles); + const crossings = countRouteCrossings(path.points.map(toPage), obstacles); if (crossings === 0) { return path; } const avoiding = findAvoidingPath(frame, obstacles, toPage); - return avoiding && countCrossings(avoiding.points.map(toPage), obstacles) < crossings ? avoiding : path; + const best = avoiding && countRouteCrossings(avoiding.points.map(toPage), obstacles) < crossings ? avoiding : path; + if (route === "curved" || countRouteCrossings(best.points.map(toPage), obstacles) === 0) { + return best; + } + const detour = findOrthogonalRoute(start, end, margin, obstacles); + if (!detour || countRouteCrossings(detour, obstacles) > 0) { + return best; + } + return toBoxPath(frame, detour.map(toBox(start, frame))) ?? detour; +}; + +// Moves a point on the page into a connector's box +const toBox = + (start: ConnectorEndpoint, { ex, ey }: BoxFrame): ((point: Point) => Point) => + (point: Point): Point => { + const offset = { x: point.x - start.point.x, y: point.y - start.point.y }; + return { x: dot(offset, ex), y: dot(offset, ey) }; + }; + +// The adjustments of the elbow connector presets with two, three and four bends, in the order the bends come +const BEND_ADJUSTMENTS: Readonly> = { + 2: ["bendX"], + 3: ["firstBendX", "secondBendY"], + 4: ["firstBendX", "secondBendY", "thirdBendX"], +}; + +/** + * The elbow connector preset that draws a route with two to four bends. A route that leaves along the box's x axis and + * arrives along the axis the frame gives bends as one of the presets does, with its bends where the preset's adjustments + * put them. A route with one bend has its bend where the usual route does, so it is never a detour. + * + * @param points - The route's ends and corners, in box coordinates + */ +const toBoxPath = ({ ex, ey, width, height }: BoxFrame, points: readonly Point[]): BoxPath | undefined => { + const corners = points.slice(1, -1); + const names = BEND_ADJUSTMENTS[corners.length] as readonly string[] | undefined; + if (!names) { + return undefined; + } + // Bends are measured along the box, so the box can't be flat + const w = Math.max(width, MIN_BEND_LENGTH); + const h = Math.max(height, MIN_BEND_LENGTH); + // The preset ends at the far corner of the box, and its last corner lines up with it + const last = corners[corners.length - 1]; + return { + ex, + ey, + width: w, + height: h, + points: [...points.slice(0, -2), corners.length % 2 === 0 ? { x: last.x, y: h } : { x: w, y: last.y }, { x: w, y: h }], + adjustments: Object.fromEntries( + names.map((name, index) => [name, index % 2 === 0 ? percentOf(corners[index].x, w) : percentOf(corners[index].y, h)]), + ), + }; }; const findStraightPath = (start: ConnectorEndpoint, end: ConnectorEndpoint): BoxPath => { @@ -484,7 +568,28 @@ export const routeConnector = ( if (!(margin >= 0)) { throw new Error(`Invalid connector margin ${margin}. Expected a distance of 0 or more`); } - const path = route === "straight" ? findStraightPath(start, end) : findRoutedPath(start, end, margin, obstacles); + const routed = route === "straight" ? findStraightPath(start, end) : findRoutedPath(route, start, end, margin, obstacles); + return toGeometry(route, start, routed); +}; + +/** + * The connector for a path in its box, or a freeform line through the corners of a route on the page. + */ +const toGeometry = (route: ConnectorRoute, start: ConnectorEndpoint, routed: BoxPath | readonly Point[]): ConnectorGeometry => { + if (!("ex" in routed)) { + const box = boundsOfPoints(routed); + return { + type: "freeform", + adjustments: {}, + offset: { x: box.left, y: box.top }, + width: box.right - box.left, + height: box.bottom - box.top, + rotation: 0, + flip: { horizontal: false, vertical: false }, + points: routed, + }; + } + const path = routed; const { ex, ey, width, height } = path; const toPage = pageMapping(start, ex, ey); @@ -504,3 +609,19 @@ export const routeConnector = ( points: path.points.map(toPage), }; }; + +/** + * The elbow connector that follows a route through the given corners, such as a route whose bends have been moved: + * the preset whose bends are at those corners, or a freeform line if it has more than four bends. + * + * @param points - The ends and corners of the route, on the page, leaving and arriving as `start` and `end` do + */ +export const fitElbowConnector = ( + start: ConnectorEndpoint, + end: ConnectorEndpoint, + points: readonly Point[], + margin: number, +): ConnectorGeometry => { + const frame = findElbowFrame(start, end, margin); + return toGeometry("elbow", start, toBoxPath(frame, points.map(toBox(start, frame))) ?? points); +}; diff --git a/src/shapes/connector/index.ts b/src/shapes/connector/index.ts index 16b54fa769..7d659f7828 100644 --- a/src/shapes/connector/index.ts +++ b/src/shapes/connector/index.ts @@ -1,3 +1,4 @@ export * from "./connection-sites"; export * from "./connector-route"; export * from "./shape-guides"; +export * from "./connector-channels"; diff --git a/src/shapes/connector/orthogonal-route.spec.ts b/src/shapes/connector/orthogonal-route.spec.ts new file mode 100644 index 0000000000..d762871904 --- /dev/null +++ b/src/shapes/connector/orthogonal-route.spec.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; + +import type { Bounds, Point } from "./connector-route"; +import { findOrthogonalRoute } from "./orthogonal-route"; + +const MARGIN = 20; + +const box = (left: number, top: number, right: number, bottom: number): Bounds => ({ left, top, right, bottom }); + +const crosses = (route: readonly Point[], obstacle: Bounds): boolean => + route.slice(1).some((to, index) => { + const from = route[index]; + const inside = (a: number, b: number, low: number, high: number): boolean => + Math.max(Math.min(a, b), low + 1) < Math.min(Math.max(a, b), high - 1) || (a === b && a > low + 1 && a < high - 1); + return inside(from.x, to.x, obstacle.left, obstacle.right) && inside(from.y, to.y, obstacle.top, obstacle.bottom); + }); + +describe("findOrthogonalRoute", () => { + it("should go around obstacles with right-angled bends, leaving and arriving at right angles to the shapes", () => { + const obstacles = [box(80, -30, 120, 50)]; + const route = findOrthogonalRoute({ point: { x: 0, y: 0 }, angle: 0 }, { point: { x: 200, y: 0 }, angle: 180 }, MARGIN, obstacles)!; + expect(route[0]).to.deep.equal({ x: 0, y: 0 }); + expect(route[route.length - 1]).to.deep.equal({ x: 200, y: 0 }); + expect(route[1].y).to.equal(0); + expect(route[1].x).to.be.at.least(MARGIN); + expect(route.slice(1).every((point, index) => point.x === route[index].x || point.y === route[index].y)).to.equal(true); + expect(crosses(route, obstacles[0])).to.equal(false); + // Right, over the obstacle, then down and in from the left: four bends, the shorter way round + expect(route).to.have.length(6); + expect(route[2].y).to.equal(-50); + }); + + it("should arrive going into the end, turning round beside it if it has to", () => { + // The end faces up, so the route comes down into it, from above + const route = findOrthogonalRoute({ point: { x: 0, y: 0 }, angle: 0 }, { point: { x: 200, y: 100 }, angle: 270 }, MARGIN, [ + box(180, 100, 220, 140), + ])!; + const [before, last] = route.slice(-2); + expect(before.x).to.equal(last.x); + expect(before.y).to.be.lessThan(last.y); + }); + + it("should find nothing when the end is walled in", () => { + const walls = [box(150, -100, 160, 100), box(240, -100, 250, 100), box(150, -110, 250, -100), box(150, 100, 250, 110)]; + expect(findOrthogonalRoute({ point: { x: 0, y: 0 }, angle: 0 }, { point: { x: 200, y: 0 }, angle: 180 }, MARGIN, walls)).to.equal( + undefined, + ); + }); +}); diff --git a/src/shapes/connector/orthogonal-route.ts b/src/shapes/connector/orthogonal-route.ts new file mode 100644 index 0000000000..680d5bb6f0 --- /dev/null +++ b/src/shapes/connector/orthogonal-route.ts @@ -0,0 +1,223 @@ +/** + * Finds a route with right-angled bends around shapes when an elbow connector can't get around them with the four + * bends its presets allow. Not part of the public API. + * + * The route is made of horizontal and vertical lines on a grid: lines a margin away from each shape, halfway between + * shapes, and through the ends. It is found by trying routes with no bends, then one, then two and so on (Lee's + * method), so it has as few bends as it can, then is as short as it can be. + * + * @module + */ +import type { Bounds, ConnectorEndpoint, Point } from "./connector-route"; + +type Axis = "x" | "y"; + +/** + * A point on the grid a route reaches, with the way it was going and the route to it. + */ +type Reached = { + readonly column: number; + readonly row: number; + /** The axis the route was going along when it reached the point, and which way along it */ + readonly axis: Axis; + readonly step: 1 | -1; + readonly length: number; + readonly previous?: Reached; +}; + +const unitOf = (angle: number): Point => { + const quarter = (((Math.round(angle / 90) % 4) + 4) % 4) as 0 | 1 | 2 | 3; + return [ + { x: 1, y: 0 }, + { x: 0, y: 1 }, + { x: -1, y: 0 }, + { x: 0, y: -1 }, + ][quarter]; +}; + +const sortedUnique = (values: readonly number[]): readonly number[] => [...new Set(values.map(Math.round))].sort((a, b) => a - b); + +// Whether an open interval of a line passes through the inside of a range, such as an obstacle's width +const passesThrough = (from: number, to: number, low: number, high: number): boolean => + Math.max(Math.min(from, to), low + 1) < Math.min(Math.max(from, to), high - 1); + +const isInside = (value: number, low: number, high: number): boolean => value > low + 1 && value < high - 1; + +/** + * The obstacles a route between two points might have to go around: those near the points, and those near them, and so on. + */ +const nearbyObstacles = (points: readonly Point[], obstacles: readonly Bounds[], margin: number): readonly Bounds[] => { + const grow = (region: Bounds, found: readonly Bounds[]): readonly Bounds[] => { + const touching = obstacles.filter( + (obstacle) => + !found.includes(obstacle) && + obstacle.left <= region.right && + region.left <= obstacle.right && + obstacle.top <= region.bottom && + region.top <= obstacle.bottom, + ); + if (touching.length === 0) { + return found; + } + const all = [...found, ...touching]; + return grow( + { + left: Math.min(region.left, ...touching.map(({ left }) => left - 2 * margin)), + top: Math.min(region.top, ...touching.map(({ top }) => top - 2 * margin)), + right: Math.max(region.right, ...touching.map(({ right }) => right + 2 * margin)), + bottom: Math.max(region.bottom, ...touching.map(({ bottom }) => bottom + 2 * margin)), + }, + all, + ); + }; + return grow( + { + left: Math.min(...points.map(({ x }) => x)) - 2 * margin, + top: Math.min(...points.map(({ y }) => y)) - 2 * margin, + right: Math.max(...points.map(({ x }) => x)) + 2 * margin, + bottom: Math.max(...points.map(({ y }) => y)) + 2 * margin, + }, + [], + ); +}; + +/** + * The lines of the grid along one axis: through the ends, a margin outside each obstacle, and halfway between the + * edges of obstacles, so routes can pass between shapes that are close together. A line a margin outside one obstacle + * that is nearer than that to another is left out, and routes between them go halfway between. + */ +const gridLines = (ends: readonly number[], edges: readonly (readonly [number, number])[], margin: number): readonly number[] => { + const sides = sortedUnique(edges.flat()); + const isClear = (line: number): boolean => sides.every((side) => Math.abs(side - line) >= margin - 1); + return sortedUnique([ + ...ends, + ...edges.flatMap(([low, high]) => [low - margin, high + margin]).filter(isClear), + ...sides.slice(1).map((side, index) => (sides[index] + side) / 2), + ]); +}; + +/** + * Finds a route with right-angled bends from one end to the other that goes through none of the obstacles. It leaves + * each end at right angles to its shape and goes at least `margin` before turning. + * + * @returns The ends and corners of the route, or nothing if there is no such route + */ +export const findOrthogonalRoute = ( + start: ConnectorEndpoint, + end: ConnectorEndpoint, + margin: number, + allObstacles: readonly Bounds[], +): readonly Point[] | undefined => { + const leaving = unitOf(start.angle); + const arriving = unitOf(end.angle); + // The first and last corners can be no nearer the shapes than the margin + const first = { x: start.point.x + leaving.x * margin, y: start.point.y + leaving.y * margin }; + const last = { x: end.point.x + arriving.x * margin, y: end.point.y + arriving.y * margin }; + const obstacles = nearbyObstacles([start.point, end.point], allObstacles, margin); + + const xs = gridLines( + [first.x, last.x], + obstacles.map(({ left, right }) => [left, right] as const), + margin, + ); + const ys = gridLines( + [first.y, last.y], + obstacles.map(({ top, bottom }) => [top, bottom] as const), + margin, + ); + const pointAt = (column: number, row: number): Point => ({ x: xs[column], y: ys[row] }); + // Whether a line between two neighboring points of the grid goes through an obstacle + const blocked = (from: Point, to: Point): boolean => + obstacles.some((obstacle) => + from.y === to.y + ? isInside(from.y, obstacle.top, obstacle.bottom) && passesThrough(from.x, to.x, obstacle.left, obstacle.right) + : isInside(from.x, obstacle.left, obstacle.right) && passesThrough(from.y, to.y, obstacle.top, obstacle.bottom), + ); + + // The points a straight line from a point reaches along an axis, both ways, until an obstacle stops it + const ray = (from: Reached, axis: Axis, step: 1 | -1): readonly Reached[] => { + const reach = (current: Reached): readonly Reached[] => { + const column = axis === "x" ? current.column + step : current.column; + const row = axis === "y" ? current.row + step : current.row; + if (column < 0 || row < 0 || column >= xs.length || row >= ys.length) { + return []; + } + const here = pointAt(current.column, current.row); + const there = pointAt(column, row); + if (blocked(here, there)) { + return []; + } + const next = { + column, + row, + axis, + step, + length: current.length + Math.abs(there.x - here.x) + Math.abs(there.y - here.y), + previous: from, + }; + return [next, ...reach(next)]; + }; + return reach(from); + }; + const keyOf = ({ column, row, axis, step }: Reached): string => `${column},${row},${axis},${step}`; + // Of the points reached the same way, the one with the shortest route + const shortest = (reached: readonly Reached[]): readonly Reached[] => [ + ...new Map([...reached].sort((a, b) => b.length - a.length).map((point) => [keyOf(point), point])).values(), + ]; + + const leavingAxis: Axis = leaving.x === 0 ? "y" : "x"; + const leavingStep = (leavingAxis === "x" ? leaving.x : leaving.y) as 1 | -1; + const arrivingAxis: Axis = arriving.x === 0 ? "y" : "x"; + // The way the route goes from the last corner into the end + const arrivingStep = -(arrivingAxis === "x" ? arriving.x : arriving.y); + const origin: Reached = { + column: xs.indexOf(Math.round(first.x)), + row: ys.indexOf(Math.round(first.y)), + axis: leavingAxis, + step: leavingStep, + length: margin, + }; + const goal = { column: xs.indexOf(Math.round(last.x)), row: ys.indexOf(Math.round(last.y)) }; + + // The route goes straight on from the first corner, then turns once more with each round. A route that reaches the + // last corner going along the other axis turns once more there, and one going the other way along the same axis + // would have to turn back, so it doesn't count + const search = (frontier: readonly Reached[], seen: ReadonlySet): Reached | undefined => { + if (frontier.length === 0) { + return undefined; + } + const arrived = frontier + .filter( + ({ column, row, axis, step }) => + column === goal.column && row === goal.row && (axis !== arrivingAxis || step === arrivingStep), + ) + .map((point) => ({ point, bends: point.axis === arrivingAxis ? 0 : 1 })) + .sort((a, b) => a.bends - b.bends || a.point.length - b.point.length); + if (arrived.length > 0) { + return arrived[0].point; + } + const next = shortest( + frontier.flatMap((point) => { + const across: Axis = point.axis === "x" ? "y" : "x"; + return [...ray(point, across, 1), ...ray(point, across, -1)]; + }), + ).filter((point) => !seen.has(keyOf(point))); + return search(next, new Set([...seen, ...next.map(keyOf)])); + }; + const leaves = shortest([origin, ...ray(origin, leavingAxis, leavingStep)]); + const found = search(leaves, new Set(leaves.map(keyOf))); + if (!found) { + return undefined; + } + + // The corners, from the start: the route back through each point where it turned + const turns = (point: Reached | undefined): readonly Point[] => + point ? [...turns(point.previous), pointAt(point.column, point.row)] : []; + const corners = [start.point, ...turns(found), end.point]; + // Points in the middle of a straight line aren't corners + return corners.filter((point, index) => { + const before = corners[index - 1]; + const after = corners[index + 1]; + return !before || !after || !((before.x === point.x && point.x === after.x) || (before.y === point.y && point.y === after.y)); + }); +}; diff --git a/src/shapes/drawing/styled-drawing.ts b/src/shapes/drawing/styled-drawing.ts new file mode 100644 index 0000000000..f14ec4e378 --- /dev/null +++ b/src/shapes/drawing/styled-drawing.ts @@ -0,0 +1,60 @@ +/** + * Drawings whose layout depends on the document's styles, such as a shape sized to fit its text. + * + * @module + */ +import { type IContext, type IXmlableObject, type Paragraph, XmlComponent } from "docx"; + +import { createTextParagraphs } from "../shape-text-size"; +import { type TextStyles, WORD_DEFAULT_STYLES, getTextStyles, hasDefaultParagraphSpacing, readTextParagraphs } from "../shape-text-styles"; + +/** + * Everything about a drawing's text that the document's styles can change: how its paragraphs, and those written for + * `text`, are formatted, and whether `text` is written without paragraph spacing. Two styles with the same key lay + * the drawing out the same way. + */ +const stylesKey = (paragraphs: readonly Paragraph[], styles: TextStyles): string => + JSON.stringify([hasDefaultParagraphSpacing(styles), readTextParagraphs([...createTextParagraphs("", styles), ...paragraphs], styles)]); + +/** + * A drawing that is laid out again, in the document's styles, when it is written. A shape doesn't know which document + * it is in until then. + * + * It is also laid out in Word's default styles when it is created, so mistakes in its options throw straight away, + * and that layout is written when the document's styles format its text the same way. The drawing ids are given + * before either layout, so both have the same ids. + */ +class StyledDrawing extends XmlComponent { + // The drawing laid out in each document's styles, so writing a document twice lays it out once + private readonly drawings = new WeakMap(); + private readonly defaultKey: string; + + public constructor( + private readonly create: (styles: TextStyles) => XmlComponent, + private readonly paragraphs: readonly Paragraph[], + ) { + super("w:drawing"); + this.drawings.set(WORD_DEFAULT_STYLES, create(WORD_DEFAULT_STYLES)); + this.defaultKey = stylesKey(paragraphs, WORD_DEFAULT_STYLES); + } + + public prepForXml(context: IContext): IXmlableObject | undefined { + const styles = getTextStyles(context); + const drawing = + this.drawings.get(styles) ?? + (stylesKey(this.paragraphs, styles) === this.defaultKey ? this.drawings.get(WORD_DEFAULT_STYLES)! : this.create(styles)); + this.drawings.set(styles, drawing); + return drawing.prepForXml(context); + } +} + +/** + * Creates a drawing, or a drawing that is laid out again in the document's styles when it is written if its layout + * depends on them. + * + * @param create - Lays out and creates the drawing in the given styles + * @param paragraphs - The paragraphs of text in the drawing, other than those written for `text`, or nothing if the + * drawing's layout doesn't depend on the document's styles + */ +export const createStyledDrawing = (create: (styles: TextStyles) => XmlComponent, paragraphs?: readonly Paragraph[]): XmlComponent => + paragraphs ? new StyledDrawing(create, paragraphs) : create(WORD_DEFAULT_STYLES); diff --git a/src/shapes/drawing/text-flow.spec.ts b/src/shapes/drawing/text-flow.spec.ts new file mode 100644 index 0000000000..f4f651f09e --- /dev/null +++ b/src/shapes/drawing/text-flow.spec.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; + +import { Formatter } from "@export/formatter"; +import { File } from "@file/file"; +import { type IContext, type IXmlableObject, Paragraph } from "docx"; + +import { ShapeRun } from "../shape-run"; + +// The text box of a shape in its drawing, and its text properties +const textOf = (tree: IXmlableObject): readonly IXmlableObject[] => { + const shape = tree["w:r"][0]["w:drawing"][0]["wp:inline"].find((child: object) => "a:graphic" in child)["a:graphic"][1][ + "a:graphicData" + ][1]["wps:wsp"] as readonly IXmlableObject[]; + return shape.slice(2); +}; + +const flowing = (flow: string, text?: string): ShapeRun => + new ShapeRun({ type: "rectangle", transformation: { width: 100, height: 50 }, text, textFlow: flow }); + +describe("text flows", () => { + it("should put the text in the first shape of a flow, and link the shapes after it to it, in the order they are written", () => { + const context = { file: new File({ sections: [] }), stack: [] } as unknown as IContext; + const first = flowing("article", "A long article"); + const second = flowing("article"); + const sidebar = flowing("sidebar", "A sidebar"); + const third = flowing("article"); + + const [box, properties] = textOf(new Formatter().format(first, context)); + expect(box["wps:txbx"][0]).to.deep.equal({ _attr: { id: 1 } }); + expect(box["wps:txbx"][1]["w:txbxContent"]).to.have.length(1); + // Text starts at the top of the first shape, and flows on from its bottom + expect(properties).to.deep.equal({ "wps:bodyPr": { _attr: {} } }); + + expect(textOf(new Formatter().format(second, context))[0]).to.deep.equal({ "wps:linkedTxbx": { _attr: { id: 1, seq: 1 } } }); + expect(textOf(new Formatter().format(sidebar, context))[0]["wps:txbx"][0]).to.deep.equal({ _attr: { id: 2 } }); + expect(textOf(new Formatter().format(third, context))[0]).to.deep.equal({ "wps:linkedTxbx": { _attr: { id: 1, seq: 2 } } }); + + // Writing the document again writes the same flows + expect(textOf(new Formatter().format(second, context))[0]).to.deep.equal({ "wps:linkedTxbx": { _attr: { id: 1, seq: 1 } } }); + expect(textOf(new Formatter().format(first, context))[0]["wps:txbx"][0]).to.deep.equal({ _attr: { id: 1 } }); + + // In another document, the flows start again + const other = { file: new File({ sections: [] }), stack: [] } as unknown as IContext; + expect(textOf(new Formatter().format(third, other))[0]["wps:txbx"][0]).to.deep.equal({ _attr: { id: 1 } }); + }); + + it("should write a flow without a document, and give the first shape of a flow its paragraphs", () => { + const shape = new ShapeRun({ + type: "rectangle", + transformation: { width: 100, height: 50 }, + children: [new Paragraph("One"), new Paragraph("Two")], + textFlow: "notes", + }); + const [box] = textOf(new Formatter().format(shape)); + expect(box["wps:txbx"][1]["w:txbxContent"]).to.have.length(2); + }); +}); diff --git a/src/shapes/drawing/text-flow.ts b/src/shapes/drawing/text-flow.ts new file mode 100644 index 0000000000..9429ef42ab --- /dev/null +++ b/src/shapes/drawing/text-flow.ts @@ -0,0 +1,62 @@ +/** + * Text that flows from one shape to the next (`wps:txbx` with an `id`, and `wps:linkedTxbx`), as in a newsletter whose + * article continues in another text box. + * + * Reference: ECMA-376 Part 1, 20.4.2.37 txbx (Textual Contents of Shape) and 20.4.2.18 linkedTxbx (Linked Textbox) + * + * @module + */ +// cspell:ignore txbx Txbx +import { BuilderElement, type IContext, type IXmlableObject, type Paragraph, XmlComponent } from "docx"; + +// A stand-in for the document when a shape is written without one +const NO_DOCUMENT = {}; + +// The shapes of each document's text flows, by name, in the order they were first written +const flows = new WeakMap>(); + +/** + * The text box of a shape in a text flow. The first shape of the flow written in a document has the text, and the + * shapes after it continue it, in the order they are written. A document numbers its flows from 1, in the order they + * are first written, so writing a document twice writes the same flows. + */ +class TextFlowBox extends XmlComponent { + public constructor( + private readonly flow: string, + private readonly children: readonly Paragraph[], + ) { + super("wps:txbx"); + } + + public prepForXml(context: IContext): IXmlableObject | undefined { + const document = (context as Partial).file ?? NO_DOCUMENT; + const byName = flows.get(document) ?? new Map(); + const shapes = byName.get(this.flow) ?? []; + const written = shapes.includes(this) ? byName : new Map([...byName, [this.flow, [...shapes, this]]]); + flows.set(document, written); + + const id = [...written.keys()].indexOf(this.flow) + 1; + const sequence = written.get(this.flow)!.indexOf(this); + return ( + sequence === 0 + ? new BuilderElement<{ readonly id: number }>({ + name: "wps:txbx", + attributes: { id: { key: "id", value: id } }, + children: [new BuilderElement({ name: "w:txbxContent", children: [...this.children] })], + }) + : new BuilderElement<{ readonly id: number; readonly sequence: number }>({ + name: "wps:linkedTxbx", + attributes: { id: { key: "id", value: id }, sequence: { key: "seq", value: sequence } }, + }) + ).prepForXml(context); + } +} + +/** + * Creates the text box of a shape in a text flow: the flow's text in the first shape of the flow in the document, and + * a link to it in the shapes after it. + * + * @param flow - The flow's name + * @param children - The flow's paragraphs, which the first shape of the flow writes + */ +export const createTextFlowBox = (flow: string, children: readonly Paragraph[]): XmlComponent => new TextFlowBox(flow, children); diff --git a/src/shapes/preset-shape/preset-shape.ts b/src/shapes/preset-shape/preset-shape.ts index 59b60c67af..1377f4acd9 100644 --- a/src/shapes/preset-shape/preset-shape.ts +++ b/src/shapes/preset-shape/preset-shape.ts @@ -19,6 +19,7 @@ import type { ShapeFill } from "./shape-fill"; import type { ShapeLine } from "./shape-line"; import { type ShapeTextOptions, createShapeTextProperties } from "./shape-text"; import { createTextBox } from "../drawing/drawing-parts"; +import { createTextFlowBox } from "../drawing/text-flow"; /** * Non-visual properties (`wps:cNvPr`) that identify a shape inside a group: its id, name and alternative text, @@ -47,6 +48,8 @@ export type PresetShapeCoreOptions = { readonly children?: readonly Paragraph[]; readonly textOptions?: ShapeTextOptions; readonly nonVisualDrawingProperties?: PresetShapeNonVisualProperties; + /** The name of the text flow the shape is in, whose text flows from one shape to the next */ + readonly textFlow?: string; }; export type PresetShapeOptions = PresetShapeCoreOptions & { @@ -130,6 +133,7 @@ export const createPresetShape = ({ textOptions, nonVisualDrawingProperties, transformation, + textFlow, }: PresetShapeOptions): XmlComponent => new BuilderElement({ name: "wps:wsp", @@ -139,7 +143,8 @@ export const createPresetShape = ({ ? createNonVisualConnectorProperties(connections) : new BuilderElement({ name: "wps:cNvSpPr" }), createPresetShapeProperties({ transformation, geometry, fill, line, effects }), - ...(children ? [createTextBox(children)] : []), - createShapeTextProperties(children ? { verticalAlignment: "center", ...textOptions } : textOptions), + ...(textFlow === undefined ? (children ? [createTextBox(children)] : []) : [createTextFlowBox(textFlow, children ?? [])]), + // Text flows from the top of each shape of a flow into the next + createShapeTextProperties(textFlow === undefined && children ? { verticalAlignment: "center", ...textOptions } : textOptions), ], }); diff --git a/src/shapes/shape-canvas-run.spec.ts b/src/shapes/shape-canvas-run.spec.ts index b49f6f5384..4ff5886390 100644 --- a/src/shapes/shape-canvas-run.spec.ts +++ b/src/shapes/shape-canvas-run.spec.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Formatter } from "@export/formatter"; +import { File } from "@file/file"; import * as convenienceFunctions from "@util/convenience-functions"; import { HorizontalPositionRelativeFrom, type IContext, type IXmlableObject, VerticalPositionRelativeFrom } from "docx"; @@ -76,7 +77,7 @@ describe("ShapeCanvasRun", () => { "wp:extent": { _attr: { cx: 130 * 9525 + 6350, cy: 150 * 9525 + 6350 } }, }); expect(getChild(container, "wp:effectExtent")).to.deep.equal({ "wp:effectExtent": { _attr: { t: 0, r: 0, b: 0, l: 0 } } }); - expect(getChild(container, "wp:docPr")).to.deep.equal({ "wp:docPr": { _attr: { id: 4, name: "Flowchart" } } }); + expect(getChild(container, "wp:docPr")).to.deep.equal({ "wp:docPr": { _attr: { id: "4", name: "Flowchart" } } }); }); it("should draw the same shapes as a group for applications that can't draw canvases", () => { @@ -104,7 +105,10 @@ describe("ShapeCanvasRun", () => { { "a:chOff": { _attr: { x: 0, y: 0 } } }, { "a:chExt": { _attr: { cx: 300 * 9525, cy: 200 * 9525 } } }, ]); - expect(group[2]["wps:wsp"][0]).to.deep.equal({ "wps:cNvPr": { _attr: { id: 8, name: "Canvas 8" } } }); + // The background is decorative, so screen readers skip it + const background = group[2]["wps:wsp"][0]["wps:cNvPr"]; + expect(background[0]).to.deep.equal({ _attr: { id: 8, name: "Canvas 8" } }); + expect(background[1]).to.have.property("a:extLst"); expect(JSON.stringify(group[2])).to.include("F2F2F2"); // The shapes and connector are laid out again, with ids of their own expect(group.slice(3).map((child: IXmlableObject) => child["wps:wsp"][0]["wps:cNvPr"]._attr.id)).to.deep.equal([5, 6, 7]); @@ -226,4 +230,35 @@ describe("ShapeCanvasRun", () => { "wp:extent": { _attr: { cx: 300 * 9525 + 2 * halfLine, cy: 50 * 9525 + loop + 2 * halfLine } }, }); }); + + it("should lay out a canvas and its fallback in the document's styles when it is written", () => { + const canvas = new ShapeCanvasRun({ + children: [{ type: "rectangle", text: "Start", transformation: { width: "fitText", height: "fitText" } }], + }); + const context = { + file: new File({ styles: { default: { document: { run: { size: 40 } } } }, sections: [] }), + stack: [], + } as unknown as IContext; + const plain = new Formatter().format(canvas); + const styled = new Formatter().format(canvas, context); + + const extent = (tree: IXmlableObject, part: "mc:Choice" | "mc:Fallback"): IXmlableObject => + getChild(getContainer(tree, part), "wp:extent")["wp:extent"]._attr; + for (const part of ["mc:Choice", "mc:Fallback"] as const) { + expect(extent(styled, part).cx).to.be.greaterThan(extent(plain, part).cx); + expect(extent(styled, part).cy).to.be.greaterThan(extent(plain, part).cy); + expect(getChild(getContainer(styled, part), "wp:docPr")).to.deep.equal(getChild(getContainer(plain, part), "wp:docPr")); + } + }); + + it("should leave out the group for applications that can't draw canvases", () => { + const tree = new Formatter().format( + new ShapeCanvasRun({ fallback: false, children: [{ type: "rectangle", transformation: { width: 10, height: 10 } }] }), + ); + const drawing = tree["w:r"][0]["w:drawing"]; + expect(drawing[0]["wp:inline"].find((child: IXmlableObject) => "wp:docPr" in child)).to.deep.equal({ + "wp:docPr": { _attr: { id: "2", name: "", descr: "", title: "" } }, + }); + expect(tree["w:r"]).to.have.length(1); + }); }); diff --git a/src/shapes/shape-canvas-run.ts b/src/shapes/shape-canvas-run.ts index 4a4c309b36..9b2c2dfb1f 100644 --- a/src/shapes/shape-canvas-run.ts +++ b/src/shapes/shape-canvas-run.ts @@ -6,16 +6,33 @@ * * @module */ -import { type DocPropertiesOptions, Drawing, type DrawingLinkOptions, type IFloating, Run, docPropertiesUniqueNumericId } from "docx"; +import { + type DocPropertiesOptions, + Drawing, + type DrawingLinkOptions, + type IFloating, + Run, + type XmlComponent, + docPropertiesUniqueNumericId, +} from "docx"; import { createAlternateContent } from "./drawing/alternate-content"; import { CANVAS_URI, GROUP_URI, type ShapeDrawingChildMediaData, createShapeDrawingChild } from "./drawing/shape-drawing-child"; import { createShapeGroup } from "./drawing/shape-group"; +import { createStyledDrawing } from "./drawing/styled-drawing"; import { createWpcCanvas } from "./drawing/wpc-canvas"; import { type ShapeFill, type ShapeLine, getShapeLineOverhang } from "./preset-shape"; -import { type IShapeGroupChildOptions, getGroupEffectExtent, layoutShapeDrawing } from "./shape-drawing"; +import { describeDrawing } from "./shape-description"; +import { + type IShapeGroupChildOptions, + createShapeDrawingNodes, + drawingStyledParagraphs, + getGroupEffectExtent, + layoutShapeDrawing, +} from "./shape-drawing"; import type { ShapeLayout } from "./shape-layout"; -import { createUniformEffectExtent } from "./shape-run-data"; +import { createDrawingProperties, createUniformEffectExtent } from "./shape-run-data"; +import type { TextStyles } from "./shape-text-styles"; /** * A shape, picture, group or connector on a canvas. It takes the same options as a child of a {@link ShapeGroupRun}. @@ -54,6 +71,11 @@ export type IShapeCanvasOptions = DrawingLinkOptions & { readonly layout?: ShapeLayout; /** Floats the canvas on the page instead of placing it inline with text */ readonly floating?: IFloating; + /** + * Whether to write the same diagram as a group too, for applications that can't draw canvases, such as Apple Pages. + * Default is `true`. Without it, the canvas takes up half as much of the document, and those applications draw nothing + */ + readonly fallback?: boolean; /** Name, description and title used by screen readers */ readonly altText?: DocPropertiesOptions; }; @@ -70,7 +92,7 @@ const EMUS_PER_PIXEL = 9525; * The shapes are positioned with `transformation.offset`, in pixels from the canvas's top-left corner, or by a `layout`. * * Applications that can't draw canvases, such as Apple Pages, draw the same shapes as a group instead: the canvas is - * written in `mc:AlternateContent`, with the group as its fallback. + * written in `mc:AlternateContent`, with the group as its fallback, unless `fallback` is `false`. * * @publicApi * @@ -89,78 +111,97 @@ export class ShapeCanvasRun extends Run { public constructor(options: IShapeCanvasOptions) { super({}); - // Canvas coordinates start at its top-left corner, and Word cuts off anything outside the canvas, so everything - // that is drawn, including lines, arrowheads and effects, is moved onto it - const { children, reach } = layoutShapeDrawing(options.children, { keepPositive: true, layout: options.layout }); - const emus = options.transformation - ? { - x: Math.round(options.transformation.width * EMUS_PER_PIXEL), - y: Math.round(options.transformation.height * EMUS_PER_PIXEL), - } - : { x: Math.ceil(reach.right), y: Math.ceil(reach.bottom) }; + // Drawing ids, in the order they are written: the canvas's shapes, the canvas, then the fallback's shapes, its + // background and the group + // Without a description of its own, the canvas is described from its shapes' text and connectors + const altText = describeDrawing(options); + const canvasNodes = createShapeDrawingNodes(options.children, options.layout); + const canvasOptions = createDrawingProperties({ ...options, altText }); + const fallback = + options.fallback === false + ? undefined + : { + nodes: createShapeDrawingNodes(options.children, options.layout), + backgroundId: docPropertiesUniqueNumericId(), + options: createDrawingProperties({ ...options, altText }), + }; - const transformation = { pixels: { x: Math.round(emus.x / EMUS_PER_PIXEL), y: Math.round(emus.y / EMUS_PER_PIXEL) }, emus }; - const lineOverhang = options.line ? getShapeLineOverhang(options.line) : 0; - const drawingOptions = { - floating: options.floating, - docProperties: options.altText, - link: options.link, - decorative: options.decorative, - }; + const create = (styles: TextStyles): XmlComponent => { + // Canvas coordinates start at its top-left corner, and Word cuts off anything outside the canvas, so everything + // that is drawn, including lines, arrowheads and effects, is moved onto it + const { children, reach } = layoutShapeDrawing(canvasNodes, { keepPositive: true, layout: options.layout, styles }); + const emus = options.transformation + ? { + x: Math.round(options.transformation.width * EMUS_PER_PIXEL), + y: Math.round(options.transformation.height * EMUS_PER_PIXEL), + } + : { x: Math.ceil(reach.right), y: Math.ceil(reach.bottom) }; - const canvas = new Drawing( - { - type: "graphic", - uri: CANVAS_URI, - transformation, - content: createWpcCanvas({ - children: children.map((child) => createShapeDrawingChild(child, "wpg:wgp")), - fill: options.fill, - line: options.line, - }), - }, - // Only the canvas's own outline reaches past its edges - { ...drawingOptions, effectExtent: createUniformEffectExtent(lineOverhang) }, - ); + const transformation = { pixels: { x: Math.round(emus.x / EMUS_PER_PIXEL), y: Math.round(emus.y / EMUS_PER_PIXEL) }, emus }; + const lineOverhang = options.line ? getShapeLineOverhang(options.line) : 0; - // Applications that can't draw canvases, such as Apple Pages, draw the same diagram as a group. It is laid out - // again so its shapes have ids of their own, and a rectangle behind them draws the canvas's background and outline - const fallback = layoutShapeDrawing(options.children, { keepPositive: true, layout: options.layout }); - const backgroundId = docPropertiesUniqueNumericId(); - const background: ShapeDrawingChildMediaData = { - type: "wps", - transformation: { offset: { pixels: { x: 0, y: 0 }, emus: { x: 0, y: 0 } }, ...transformation }, - data: { - geometry: { type: "rectangle" }, - fill: options.fill, - line: options.line ?? "none", - nonVisualDrawingProperties: { id: backgroundId, name: `Canvas ${backgroundId}` }, - }, - }; - const groupReach = { - left: Math.min(-lineOverhang, fallback.reach.left), - top: Math.min(-lineOverhang, fallback.reach.top), - right: Math.max(emus.x + lineOverhang, fallback.reach.right), - bottom: Math.max(emus.y + lineOverhang, fallback.reach.bottom), - }; - const group = new Drawing( - { - type: "graphic", - uri: GROUP_URI, - transformation, - content: createShapeGroup({ + const canvas = new Drawing( + { + type: "graphic", + uri: CANVAS_URI, transformation, - childOffset: { x: 0, y: 0 }, - childExtent: emus, - children: [background, ...fallback.children].map((child) => createShapeDrawingChild(child, "wpg:grpSp")), - }), - }, - { - ...drawingOptions, - effectExtent: getGroupEffectExtent({ reach: groupReach }, { x: 0, y: 0 }, emus, { width: emus.x, height: emus.y }), - }, - ); + content: createWpcCanvas({ + children: children.map((child) => createShapeDrawingChild(child, "wpg:wgp")), + fill: options.fill, + line: options.line, + }), + }, + // Only the canvas's own outline reaches past its edges + { ...canvasOptions, effectExtent: createUniformEffectExtent(lineOverhang) }, + ); - this.root.push(createAlternateContent({ requires: "wpc", choice: canvas, fallback: group })); + if (!fallback) { + return canvas; + } + + // Applications that can't draw canvases, such as Apple Pages, draw the same diagram as a group. Its shapes + // have ids of their own, and a rectangle behind them draws the canvas's background and outline + const { backgroundId } = fallback; + const group = layoutShapeDrawing(fallback.nodes, { keepPositive: true, layout: options.layout, styles }); + const background: ShapeDrawingChildMediaData = { + type: "wps", + transformation: { offset: { pixels: { x: 0, y: 0 }, emus: { x: 0, y: 0 } }, ...transformation }, + data: { + geometry: { type: "rectangle" }, + fill: options.fill, + line: options.line ?? "none", + // Screen readers skip it: it is only the canvas's background + nonVisualDrawingProperties: { id: backgroundId, name: `Canvas ${backgroundId}`, decorative: true }, + }, + }; + const groupReach = { + left: Math.min(-lineOverhang, group.reach.left), + top: Math.min(-lineOverhang, group.reach.top), + right: Math.max(emus.x + lineOverhang, group.reach.right), + bottom: Math.max(emus.y + lineOverhang, group.reach.bottom), + }; + const groupDrawing = new Drawing( + { + type: "graphic", + uri: GROUP_URI, + transformation, + content: createShapeGroup({ + transformation, + childOffset: { x: 0, y: 0 }, + childExtent: emus, + children: [background, ...group.children].map((child) => createShapeDrawingChild(child, "wpg:grpSp")), + }), + }, + { + ...fallback.options, + effectExtent: getGroupEffectExtent({ reach: groupReach }, { x: 0, y: 0 }, emus, { width: emus.x, height: emus.y }), + }, + ); + + return createAlternateContent({ requires: "wpc", choice: canvas, fallback: groupDrawing }); + }; + + // A canvas whose shapes fit their text is laid out in the document's styles when it is written + this.root.push(createStyledDrawing(create, drawingStyledParagraphs(options.children, options.layout))); } } diff --git a/src/shapes/shape-description.spec.ts b/src/shapes/shape-description.spec.ts new file mode 100644 index 0000000000..61cf42287a --- /dev/null +++ b/src/shapes/shape-description.spec.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from "vitest"; + +import { Paragraph, TextRun } from "docx"; + +import { describeDiagram, describeDrawing } from "./shape-description"; +import type { IShapeGroupChildOptions } from "./shape-drawing"; + +const step = (id: string, text: string): IShapeGroupChildOptions => ({ + id, + type: "rectangle", + text, + transformation: { width: 10, height: 10 }, +}); + +const connect = (from: string, to: string, label?: string): IShapeGroupChildOptions => ({ type: "connector", from, to, label }); + +describe("describeDiagram", () => { + it("should tell a flowchart from its start, with each branch of a decision and the way back round a loop", () => { + expect( + describeDiagram([ + step("start", "Start"), + step("draft", "Write the draft"), + step("review", "Approved?"), + step("publish", "Publish"), + step("fix", "Fix it"), + step("end", "End"), + connect("start", "draft"), + connect("draft", "review"), + connect("review", "publish", "Yes"), + connect("review", "fix", "No"), + connect("publish", "end"), + connect("fix", "draft"), + ]), + ).to.equal("Start, then Write the draft, then Approved? Yes: Publish, then End. No: Fix it, then back to Write the draft."); + }); + + it("should name a shape again where branches meet, and tell branches without labels", () => { + expect( + describeDiagram([ + step("a", "Split"), + step("b", "Left"), + step("c", "Right"), + step("d", "Join"), + step("e", "Ask again?"), + connect("a", "b"), + connect("a", "c"), + connect("b", "d"), + connect("c", "d"), + connect("a", "e", "Stuck"), + // A connector to a shape that doesn't exist is left out + connect("d", "missing"), + ]), + ).to.equal("Split. Then Left, then Join. Then Right, then Join. Stuck: Ask again?"); + }); + + it("should list the shapes a shape leads to without labels, as in an org chart, then tell each that leads on", () => { + expect( + describeDiagram([ + step("ceo", "Chief Executive"), + step("cto", "Technology"), + step("cfo", "Finance"), + step("coo", "Operations"), + step("dev", "Development"), + step("qa", "Quality"), + step("infra", "Infrastructure"), + connect("ceo", "cto"), + connect("ceo", "cfo"), + connect("ceo", "coo"), + connect("cto", "dev"), + connect("cto", "qa"), + connect("coo", "infra"), + ]), + ).to.equal( + "Chief Executive leads to Technology, Finance and Operations. Technology leads to Development and Quality. Operations, then Infrastructure.", + ); + }); + + it("should tell shapes that aren't connected, and loops without a start, in the order they are given", () => { + expect( + describeDiagram([ + { type: "rectangle", text: "Title", transformation: { width: 10, height: 10 } }, + step("a", "Ping"), + step("b", "Pong"), + connect("a", "b"), + connect("b", "a"), + ]), + ).to.equal("Title. Ping, then Pong, then back to Ping."); + }); + + it("should read text from paragraphs and labels, alternative text, pictures and groups, and leave out shapes that say nothing", () => { + expect( + describeDiagram([ + { + id: "a", + type: "rectangle", + children: [new Paragraph({ children: [new TextRun("Two"), new TextRun({ text: " words", break: 1 })] })], + transformation: { width: 10, height: 10 }, + }, + { id: "blank", type: "ellipse", transformation: { width: 10, height: 10 } }, + { + id: "logo", + type: "picture", + image: { type: "png", data: "" }, + transformation: { width: 1, height: 1 }, + altText: { name: "Logo" }, + }, + { id: "photo", type: "picture", image: { type: "png", data: "" }, transformation: { width: 1, height: 1 } }, + { + type: "group", + children: [{ ...step("inner", "Hidden text"), altText: { name: "Inner" } } as IShapeGroupChildOptions], + }, + { type: "connector", from: "a", to: "logo", label: { text: [new Paragraph("Then")] } }, + { type: "connector", from: "logo", to: { id: "inner", side: "top" }, label: { text: "Last", width: 20, height: 10 } }, + connect("a", "blank"), + connect("a", "a"), + ]), + ).to.equal("Two words, then Logo, then Inner."); + }); + + it("should say nothing for a diagram without text", () => { + expect(describeDiagram([{ type: "rectangle", transformation: { width: 10, height: 10 } }])).to.equal(""); + }); +}); + +describe("describeDrawing", () => { + const children = [step("a", "Start"), step("b", "End"), connect("a", "b")]; + + it("should describe a drawing without a description of its own", () => { + expect(describeDrawing({ children })).to.deep.equal({ name: "", description: "Start, then End.", title: "" }); + expect(describeDrawing({ children, altText: { name: "Process" } })).to.deep.equal({ + name: "Process", + description: "Start, then End.", + }); + }); + + it("should keep a drawing's own description, and not describe decorative drawings or ones without text", () => { + const altText = { name: "Process", description: "Mine" }; + expect(describeDrawing({ children, altText })).to.equal(altText); + expect(describeDrawing({ children, decorative: true })).to.equal(undefined); + expect(describeDrawing({ children: [{ type: "rectangle", transformation: { width: 10, height: 10 } }] })).to.equal(undefined); + }); +}); diff --git a/src/shapes/shape-description.ts b/src/shapes/shape-description.ts new file mode 100644 index 0000000000..65e101053a --- /dev/null +++ b/src/shapes/shape-description.ts @@ -0,0 +1,174 @@ +/** + * Describes a diagram for screen readers, from the text of its shapes and the connectors between them. Not part of the + * public API. + * + * @module + */ +import type { DocPropertiesOptions, DrawingLinkOptions, Paragraph } from "docx"; + +import type { IShapeConnectorOptions } from "./shape-connector"; +import type { IShapeGroupChildOptions } from "./shape-drawing"; +import { WORD_DEFAULT_STYLES, readTextParagraphs } from "./shape-text-styles"; + +type Step = { + readonly id?: string; + /** What the shape says: its alternative text's name, or its text */ + readonly name: string; +}; + +type Link = { + readonly from: string; + readonly to: string; + readonly label?: string; +}; + +const textOf = (paragraphs: readonly Paragraph[]): string => + readTextParagraphs(paragraphs, WORD_DEFAULT_STYLES) + .map(({ spans }) => spans.map(({ text }) => text).join("")) + .join(" ") + .replace(/\s+/g, " ") + .trim(); + +const endId = (end: IShapeConnectorOptions["from"]): string => (typeof end === "string" ? end : end.id); + +/** + * The shapes and pictures in a diagram that say something, and those in the groups inside it, in the order they are given. + */ +const stepsOf = (children: readonly IShapeGroupChildOptions[]): readonly Step[] => + children.flatMap((child): readonly Step[] => { + switch (child.type) { + case "connector": + return []; + case "group": + return stepsOf(child.children); + case "picture": + return [{ id: child.id, name: child.altText?.name ?? "" }]; + default: { + const text = [child.text ?? "", textOf(child.children ?? [])].join(" ").replace(/\s+/g, " ").trim(); + return [{ id: child.id, name: child.altText?.name ?? text }]; + } + } + }); + +const linksOf = (children: readonly IShapeGroupChildOptions[]): readonly Link[] => + children.flatMap((child): readonly Link[] => { + if (child.type === "group") { + return linksOf(child.children); + } + if (child.type !== "connector") { + return []; + } + const label = + typeof child.label === "string" + ? child.label + : typeof child.label?.text === "string" + ? child.label.text + : textOf(child.label?.text ?? []); + return [{ from: endId(child.from), to: endId(child.to), label: label.trim() || undefined }]; + }); + +const endsSentence = (text: string): boolean => /[.?!]$/.test(text); + +/** + * Describes a diagram: each flow of connected shapes from its start, such as "Start, then Write the draft, then + * Approved? Yes: Publish. No: Fix it, then back to Write the draft.", then the shapes that aren't connected. + * Shapes and pictures without text or alternative text are left out. + * + * @returns The description, or an empty string if nothing in the diagram says anything + */ +export const describeDiagram = (children: readonly IShapeGroupChildOptions[]): string => { + const steps = stepsOf(children); + const named = steps.filter(({ name }) => name.length > 0); + const links = linksOf(children).filter(({ from, to }) => from !== to); + const stepWith = (id: string): Step | undefined => steps.find((step) => step.id === id); + const nameOf = (id: string): string => stepWith(id)?.name ?? ""; + + /** A sentence being told, the shapes told so far, and sentences about the shapes it leads to, told after it */ + type Told = { readonly text: string; readonly seen: ReadonlySet; readonly after: readonly string[] }; + + const sentence = (text: string): string => (endsSentence(text) ? text : `${text}.`); + + // Tells the flow from a shape along its connectors. Shapes already told are named, not told again, and a + // connector back to a shape on the way to this one goes "back to" it + const tell = (id: string, path: readonly string[], seen: ReadonlySet): Told => { + const name = nameOf(id); + if (seen.has(id)) { + return { text: path.includes(id) ? `back to ${name}` : name, seen, after: [] }; + } + const told = new Set([...seen, id]); + const next = links.filter(({ from, to }) => from === id && nameOf(to).length > 0); + if (next.length === 0) { + return { text: name, seen: told, after: [] }; + } + if (next.length === 1) { + const rest = tell(next[0].to, [...path, id], told); + return { ...rest, text: `${name}, then ${rest.text}` }; + } + // A shape with several ways on without labels, such as a box in an org chart: the shapes it leads to, then + // a sentence for each of them that leads on + if (next.every(({ label }) => label === undefined)) { + const names = next.map(({ to }) => nameOf(to)); + const list = names.length === 2 ? names.join(" and ") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`; + return next.reduce( + (done, { to }) => { + const branch = tell(to, [...path, id], done.seen); + const onward = branch.text === nameOf(to) ? [] : [sentence(branch.text)]; + return { ...done, seen: branch.seen, after: [...done.after, ...onward, ...branch.after] }; + }, + { text: `${name} leads to ${list}`, seen: told, after: [] }, + ); + } + // A shape with several ways on, such as a decision: each way, with its connector's label + return next.reduce( + (done, { to, label }) => { + const branch = tell(to, [...path, id], done.seen); + return { + text: `${done.text} ${sentence(`${label ? `${label}: ` : "Then "}${branch.text}`)}`, + seen: branch.seen, + after: [...done.after, ...branch.after], + }; + }, + { text: sentence(name), seen: told, after: [] }, + ); + }; + + // Flows start at the shapes no connector leads to, then any shapes left, such as those in a loop + const starts = [ + ...named.filter(({ id }) => id === undefined || !links.some(({ to }) => to === id)), + ...named.filter(({ id }) => id !== undefined && links.some(({ to }) => to === id)), + ]; + return starts + .reduce<{ readonly seen: ReadonlySet; readonly sentences: readonly string[] }>( + (done, step) => { + if (step.id !== undefined && done.seen.has(step.id)) { + return done; + } + const told = step.id === undefined ? { text: step.name, seen: done.seen, after: [] } : tell(step.id, [], done.seen); + return { seen: told.seen, sentences: [...done.sentences, sentence(told.text), ...told.after] }; + }, + { seen: new Set(), sentences: [] }, + ) + .sentences.join(" "); +}; + +/** + * The alternative text of a group or canvas: its own, with a description of the diagram when it has none and isn't + * decorative. + */ +export const describeDrawing = ({ + altText, + decorative, + children, +}: DrawingLinkOptions & { + readonly altText?: DocPropertiesOptions; + readonly children: readonly IShapeGroupChildOptions[]; +}): DocPropertiesOptions | undefined => { + if (decorative || altText?.description) { + return altText; + } + const description = describeDiagram(children); + if (description.length === 0) { + return altText; + } + return altText ? { ...altText, description } : { name: "", description, title: "" }; +}; diff --git a/src/shapes/shape-drawing.spec.ts b/src/shapes/shape-drawing.spec.ts index 552b8b0ad4..8cccd410e8 100644 --- a/src/shapes/shape-drawing.spec.ts +++ b/src/shapes/shape-drawing.spec.ts @@ -1,3 +1,4 @@ +// cspell:ignore DEEBF import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as convenienceFunctions from "@util/convenience-functions"; @@ -6,7 +7,13 @@ import { Paragraph } from "docx"; import type { ShapeDrawingChildMediaData } from "./drawing/shape-drawing-child"; import type { PresetShapeCoreOptions } from "./preset-shape"; import type { ConnectorEnd } from "./shape-connector"; -import { type IShapeGroupChildOptions, layoutShapeDrawing } from "./shape-drawing"; +import { + type IShapeGroupChildOptions, + type ShapeDrawingLayout, + createShapeDrawingNodes, + drawingStyledParagraphs, + layoutShapeDrawing, +} from "./shape-drawing"; import { measureTextWidth } from "./text-metrics"; const EMUS_PER_PIXEL = 9525; @@ -576,6 +583,29 @@ describe("layoutShapeDrawing", () => { expect(offsetOf(children[2])).to.deep.equal([500, 0]); }); + it("should place the layout around a shape with an offset that connects to the shapes it places", () => { + // b is pinned, and a leads to it, so a goes on the level before it + const { children } = layoutShapeDrawing([shape("a"), box("b", 300, 200), shape("c"), connect("a", "b"), connect("b", "c")], { + layout: { type: "flow" }, + }); + expect(children.slice(0, 3).map(offsetOf)).to.deep.equal([ + [300, 100], + [300, 200], + [300, 300], + ]); + expect(sitesOf(children[3])).to.deep.equal([2, 0]); + + // With two, the layout is placed as near both as it can be, and they stay where they are + const two = layoutShapeDrawing([box("a", 0, 0), shape("b"), box("c", 0, 300), connect("a", "b"), connect("b", "c")], { + layout: { type: "flow" }, + }); + expect(two.children.slice(0, 3).map(offsetOf)).to.deep.equal([ + [0, 0], + [0, 150], + [0, 300], + ]); + }); + it("should keep children with an offset where they are when there is nothing else to place", () => { const { children } = layoutShapeDrawing([box("a", 10, 20)], { layout: { type: "tree" } }); expect(offsetOf(children[0])).to.deep.equal([10, 20]); @@ -611,6 +641,42 @@ describe("layoutShapeDrawing", () => { ]); }); + it("should place a shape on the side of its parent that its connector leaves from or arrives at", () => { + const placed = (from: ConnectorEnd, to: ConnectorEnd, direction?: "down" | "right"): readonly (readonly [number, number])[] => + layoutShapeDrawing([shape("a"), shape("no"), shape("yes"), connect(from, to), connect("a", "yes")], { + layout: { type: "flow", direction }, + }).children.map(offsetOf); + + // "no" is given before "yes", and goes to the right when its connector leaves the decision's right side + const [a, no, yes] = placed({ id: "a", side: "right" }, "no"); + expect(no[0]).to.be.greaterThan(yes[0]); + expect(yes[0]).to.equal(a[0]); + // or arrives at its left side + const [, arriving, below] = placed("a", { id: "no", side: "left" }); + expect(arriving[0]).to.be.greaterThan(below[0]); + // Leaving the left side, or arriving at the right, puts it on the left + const [, leftNo, leftYes] = placed({ id: "a", side: "left" }, "no"); + expect(leftNo[0]).to.be.lessThan(leftYes[0]); + const [, rightArriving, rightYes] = placed("a", { id: "no", side: "right" }); + expect(rightArriving[0]).to.be.lessThan(rightYes[0]); + // In a flow that runs right, the bottom side is across the levels + const [, bottomNo, bottomYes] = placed({ id: "a", side: "bottom" }, "no", "right"); + expect(bottomNo[1]).to.be.greaterThan(bottomYes[1]); + // A side along the levels changes nothing + const [, topNo, topYes] = placed("a", { id: "no", side: "top" }); + expect(topNo[0]).to.be.lessThan(topYes[0]); + }); + + it("should leave room between levels for connector labels", () => { + const flow = (direction: "down" | "right", label: string): readonly (readonly [number, number])[] => + layoutShapeDrawing([shape("a"), shape("b"), connect("a", "b", { label })], { + layout: { type: "flow", direction, levelSpacing: 10 }, + }).children.map(offsetOf); + // A label two lines tall moves the next level further down, and a long one further right + expect(flow("down", "Two\nlines")[1][1]).to.be.greaterThan(flow("down", "One")[1][1]); + expect(flow("right", "A much longer label")[1][0]).to.be.greaterThan(flow("right", "Short")[1][0]); + }); + it("should lay out pictures", () => { const { children } = layoutShapeDrawing( [shape("a"), { type: "picture", image: { type: "png", data: Buffer.from("") }, transformation: { width: 30, height: 30 } }], @@ -673,8 +739,11 @@ describe("layoutShapeDrawing", () => { it("should face each other in a grid, and for shapes the layout didn't place", () => { const grid = layoutShapeDrawing([shape("a"), shape("b"), connect("a", "b")], { layout: { type: "grid", columns: 1 } }); expect(sitesOf(grid.children[2])).to.deep.equal([2, 0]); - const pinned = layoutShapeDrawing([shape("a"), box("b", 300, 0), connect("a", "b")], { layout: { type: "flow" } }); - expect(sitesOf(pinned.children[2])).to.deep.equal([3, 1]); + // Shapes with an offset that only connect to each other are left out of the layout + const pinned = layoutShapeDrawing([shape("a"), box("b", 300, 0), box("c", 600, 0), connect("b", "c")], { + layout: { type: "flow" }, + }); + expect(sitesOf(pinned.children[3])).to.deep.equal([3, 1]); }); }); }); @@ -908,6 +977,39 @@ describe("layoutShapeDrawing", () => { expect(secondTop).to.equal(31); }); + it("should keep a label off the lines of other connectors", () => { + // A connector from c down to d crosses the middle of the connector from a to b + const { children } = layoutShapeDrawing([ + box("a", 0, 0), + box("b", 300, 0), + box("c", 150, -150), + box("d", 150, 150), + connect("a", "b", { label: { text: "", width: 30, height: 10 } }), + connect("c", "d"), + ]); + const [left, top] = offsetOf(children[5]); + // On its own connector, but not across the line at x = 200 + expect(top).to.equal(20); + expect(left + 30 < 200 || left > 200).to.equal(true); + }); + + it("should put a label beside its route on the side away from the shapes", () => { + // A thin shape on the route leaves no room on it, and another shape is above or below the route + const beside = (below: boolean): number => + offsetOf( + layoutShapeDrawing([ + box("a", 0, 0, { transformation: { width: 100, height: 40 } }), + box("b", 160, 0, { transformation: { offset: { left: 160 }, width: 100, height: 40 } }), + box("bar", 120, 17, { transformation: { offset: { left: 120, top: 17 }, width: 20, height: 6 } }), + box("x", 110, 0, { transformation: { offset: { left: 110, top: below ? 50 : -50 }, width: 40, height: 40 } }), + connect("a", "b", { route: "straight", label: { text: "", width: 40, height: 20 } }), + ]).children[5], + )[1]; + // Above the route when there is a shape below it, and below it when there is one above + expect(beside(true)).to.equal(-4); + expect(beside(false)).to.equal(24); + }); + it("should stay where it is wanted when nowhere is clear", () => { const { children } = layoutShapeDrawing([ box("a", 0, 0, { transformation: { width: 100, height: 200 } }), @@ -924,3 +1026,172 @@ describe("layoutShapeDrawing", () => { expect(() => layoutShapeDrawing([box("a", 0, 0), connect("a", "missing")])).to.throw('No shape has the id "missing"'); }); }); + +describe("lanes", () => { + beforeEach(() => { + let id = 0; + vi.spyOn(convenienceFunctions, "docPropertiesUniqueNumericId").mockImplementation(() => ++id); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("should draw each lane's band and header behind the shapes, with the lanes' ids first", () => { + const { children } = layoutShapeDrawing([shape("a", { lane: "Team" }), shape("b", { lane: "Other team" }), connect("a", "b")], { + layout: { type: "flow", lanes: [{ name: "Team", fill: "DEEBF7", headerFill: "FFFFFF", line: "000000" }, "Other team"] }, + }); + expect(children).to.have.length(7); + const [band, header, otherBand, otherHeader] = children.map(dataOf); + expect(band).to.deep.include({ fill: "DEEBF7", line: "000000" }); + expect(band.nonVisualDrawingProperties).to.deep.include({ id: 1, name: "Team" }); + expect(header).to.deep.include({ fill: "FFFFFF", line: "000000" }); + expect(header.nonVisualDrawingProperties).to.deep.include({ id: 2, name: "Text Box 2" }); + expect(header.children).to.have.length(1); + // Without a fill, a band has none, and its header is light grey with a thin grey line + expect(otherBand.fill).to.equal(undefined); + expect(otherHeader).to.deep.include({ fill: "F2F2F2", line: { color: "A5A5A5", width: 0.75 } }); + // The shapes come after the lanes, and each is in its own lane + expect(dataOf(children[4]).nonVisualDrawingProperties?.id).to.equal(5); + expect(offsetOf(children[5])[0]).to.be.greaterThan(offsetOf(children[4])[0]); + }); + + it("should lay out lanes in a group inside the drawing", () => { + const { children } = layoutShapeDrawing([ + { type: "group", layout: { type: "flow", lanes: ["Inner"] }, children: [shape("a", { lane: "Inner" })] }, + ]); + const group = children[0]; + expect(group.type === "group" && group.children).to.have.length(3); + }); + + it("should throw for a lane the layout doesn't have, or two lanes with the same name", () => { + expect(() => layoutShapeDrawing([shape("a", { lane: "Missing" })], { layout: { type: "flow", lanes: ["Team"] } })).to.throw( + 'Invalid lane "Missing". The layout has no lane with that name', + ); + expect(() => layoutShapeDrawing([shape("a", { lane: "Team" })])).to.throw('Invalid lane "Team"'); + expect(() => layoutShapeDrawing([shape("a")], { layout: { type: "flow", lanes: ["Team", "Team"] } })).to.throw( + 'Invalid lane "Team". Each lane in a layout needs a different name', + ); + }); + + it("should make headers fit their names across the page when the flow runs across it", () => { + const [band, header] = layoutShapeDrawing([shape("a", { lane: "A long lane name" })], { + layout: { type: "flow", direction: "right", lanes: ["A long lane name"] }, + }).children; + expect(header.transformation.pixels.x).to.equal(Math.ceil(measureTextWidth("A long lane name") * (4 / 3)) + 12); + expect(band.transformation.pixels.y).to.equal(header.transformation.pixels.y); + }); + + it("should depend on the document's styles, which headers are measured in", () => { + expect(drawingStyledParagraphs([shape("a")], { type: "flow", lanes: ["A"] })).to.deep.equal([]); + expect(drawingStyledParagraphs([shape("a")], { type: "flow", lanes: [] })).to.equal(undefined); + expect(drawingStyledParagraphs([{ type: "group", layout: { type: "flow", lanes: ["A"] }, children: [shape("a")] }])).to.deep.equal( + [], + ); + }); +}); + +describe("connectors that would lie on top of each other", () => { + it("should be moved apart, and stay attached to their shapes", () => { + // Two connectors loop round the right of a column of shapes, along the same line + const { children } = layoutShapeDrawing([ + box("a", 0, 0), + box("b", 0, 100), + box("c", 0, 200), + box("d", 0, 300), + connect({ id: "a", side: "right" }, { id: "c", side: "right" }, { route: "elbow" }), + connect({ id: "b", side: "right" }, { id: "d", side: "right" }, { route: "elbow" }), + ]); + const loops = [children[4], children[5]]; + // Each loop's bend is outside its box, a margin (24 pixels) past the pixel-wide box, and 3 pixels either way + const bends = loops.map((child) => { + const { adjustments } = dataOf(child).geometry as { readonly adjustments: Readonly> }; + return Math.round( + ((child.transformation.offset?.emus?.x ?? 0) + (child.transformation.emus.x * adjustments.bendX) / 100) / EMUS_PER_PIXEL, + ); + }); + expect(bends).to.deep.equal([122, 128]); + expect(loops.map((child) => dataOf(child).connections?.start)).to.not.include(undefined); + + // A shape just past the lines stops one from moving into it + const blocked = layoutShapeDrawing([ + box("a", 0, 0), + box("b", 0, 100), + box("c", 0, 200), + box("d", 0, 300), + box("e", 126, 150, { transformation: { offset: { left: 126, top: 150 }, width: 50, height: 30 } }), + connect({ id: "a", side: "right" }, { id: "c", side: "right" }, { route: "elbow" }), + connect({ id: "b", side: "right" }, { id: "d", side: "right" }, { route: "elbow" }), + ]).children; + expect( + [blocked[5], blocked[6]].map((child) => { + const { adjustments } = dataOf(child).geometry as { readonly adjustments: Readonly> }; + return Math.round( + ((child.transformation.offset?.emus?.x ?? 0) + (child.transformation.emus.x * adjustments.bendX) / 100) / + EMUS_PER_PIXEL, + ); + }), + ).to.deep.equal([122, 125]); + }); +}); + +describe("connectors that need more bends than the presets have", () => { + it("should be drawn as a freeform line that isn't attached to the shapes", () => { + const square = (id: string, left: number, top: number, width: number, height: number): IShapeGroupChildOptions => + ({ id, type: "rectangle", transformation: { offset: { left, top }, width, height } }) as IShapeGroupChildOptions; + const { children } = layoutShapeDrawing([ + square("a", 0, 0, 20, 20), + square("z", 260, -40, 20, 20), + square("b0", 40, 20, 80, 20), + square("b1", 100, 20, 20, 60), + square("b2", 180, -20, 40, 40), + square("b3", 80, -40, 20, 60), + connect({ id: "a", side: "right" }, { id: "z", side: "bottom" }, { route: "elbow", line: arrow }), + ]); + const connector = children[6]; + const data = dataOf(connector); + expect(data.geometry.type).to.equal("custom"); + expect(data.geometry.type === "custom" && data.geometry.path.startsWith("M 0 ")).to.equal(true); + expect(data.connections).to.equal(undefined); + expect(data.line).to.deep.equal(arrow); + expect(data.nonVisualDrawingProperties?.name).to.match(/^Freeform \d+$/); + }); +}); + +describe("drawingStyledParagraphs", () => { + const square = { type: "rectangle", transformation: { width: 10, height: 10 } } as const; + const paragraph = new Paragraph("A"); + + it("should depend on the styles when a shape fits its text or has text, and give the shapes' paragraphs", () => { + expect(drawingStyledParagraphs([square, { ...square, children: [paragraph] }])).to.equal(undefined); + expect(drawingStyledParagraphs([{ ...square, transformation: { width: "fitText", height: 10 } }])).to.deep.equal([]); + expect( + drawingStyledParagraphs([{ ...square, transformation: { width: 10, height: "fitText" }, children: [paragraph] }]), + ).to.deep.equal([paragraph]); + expect(drawingStyledParagraphs([{ ...square, text: "A" }])).to.deep.equal([]); + expect(drawingStyledParagraphs([{ type: "group", children: [{ ...square, text: "A", children: [paragraph] }] }])).to.deep.equal([ + paragraph, + ]); + expect( + drawingStyledParagraphs([{ type: "picture", image: { type: "png", data: "" }, transformation: { width: 1, height: 1 } }]), + ).to.equal(undefined); + }); + + it("should depend on the styles when a label is sized to its text or its text is a string", () => { + const connector = { type: "connector", from: "a", to: "b" } as const; + expect(drawingStyledParagraphs([connector])).to.equal(undefined); + expect(drawingStyledParagraphs([{ ...connector, label: "Yes" }])).to.deep.equal([]); + expect(drawingStyledParagraphs([{ ...connector, label: { text: "Yes", width: 20, height: 10 } }])).to.deep.equal([]); + expect(drawingStyledParagraphs([{ ...connector, label: { text: [paragraph], width: 20 } }])).to.deep.equal([paragraph]); + expect(drawingStyledParagraphs([{ ...connector, label: { text: [paragraph], width: 20, height: 10 } }])).to.equal(undefined); + }); +}); + +describe("createShapeDrawingNodes", () => { + it("should give the children their ids once, so laying them out again keeps them", () => { + const nodes = createShapeDrawingNodes([{ type: "rectangle", transformation: { width: 10, height: 10 } }]); + const ids = (layout: ShapeDrawingLayout): readonly unknown[] => + layout.children.map((child) => (child.type === "wps" ? child.data.nonVisualDrawingProperties?.id : undefined)); + expect(ids(layoutShapeDrawing(nodes))).to.deep.equal(ids(layoutShapeDrawing(nodes))); + }); +}); diff --git a/src/shapes/shape-drawing.ts b/src/shapes/shape-drawing.ts index f20aefc2ce..98134d6c91 100644 --- a/src/shapes/shape-drawing.ts +++ b/src/shapes/shape-drawing.ts @@ -12,10 +12,23 @@ import { type ICropOptions, type IMediaDataTransformation, type IMediaTransformation, + type Paragraph, docPropertiesUniqueNumericId, } from "docx"; -import { type Bounds, type ConnectionSite, type ConnectorEndpoint, type Point, getConnectionSites, routeConnector } from "./connector"; +import { + type Bounds, + type ConnectionSite, + type ConnectorEndpoint, + type ConnectorGeometry, + type ConnectorRoute, + type Point, + countRouteCrossings, + fitElbowConnector, + getConnectionSites, + routeConnector, + separateChannels, +} from "./connector"; import { createCustomGeometryPath, outwardAngle } from "./custom-geometry"; import type { ShapeDrawingChildMediaData } from "./drawing/shape-drawing-child"; import type { ImageSource } from "./picture/image-data"; @@ -24,15 +37,17 @@ import { type PresetShapeCoreOptions, type PresetShapeNonVisualProperties, type ShapeEffects, + type ShapeFill, type ShapeLine, createShapeGuides, getShapeEffectsOverhang, getShapeLineOverhang, } from "./preset-shape"; import type { ConnectorEnd, ConnectorLabel, ConnectorSide, IShapeConnectorOptions } from "./shape-connector"; -import { type ShapeLayout, type ShapeLayoutDirection, layoutItems } from "./shape-layout"; +import { type ShapeLane, type ShapeLayout, type ShapeLayoutDirection, layoutItems } from "./shape-layout"; import { type ShapeBaseOptions, type WithPresetShape, createPresetShapeData, getShapeOverhang } from "./shape-run-data"; -import { createTextParagraphs, getParagraphSpans, resolveShapeSize } from "./shape-text-size"; +import { createTextParagraphs, resolveShapeSize } from "./shape-text-size"; +import { type TextStyles, WORD_DEFAULT_STYLES, readTextParagraphs } from "./shape-text-styles"; import { measureText } from "./text-metrics"; /** @@ -48,6 +63,8 @@ export type IShapePictureOptions = DrawingLinkOptions & { readonly transformation: IMediaTransformation; /** A name that connectors use to attach to this picture. It must be unique within the group or canvas */ readonly id?: string; + /** The lane of the flow the picture goes in, by its name. See `ShapeFlowLayout.lanes` */ + readonly lane?: string; /** Crops the picture by a percentage of each side, from 0 to 100 */ readonly crop?: ICropOptions; /** An outline around the picture. Default is none */ @@ -81,6 +98,8 @@ export type IShapeNestedGroupOptions = DrawingLinkOptions & { }; /** Places the children that have no `offset`, such as in a flowchart, tree or grid */ readonly layout?: ShapeLayout; + /** The lane of the flow the group goes in, by its name. See `ShapeFlowLayout.lanes` */ + readonly lane?: string; /** Name, description and title used by screen readers */ readonly altText?: DocPropertiesOptions; }; @@ -98,6 +117,8 @@ export type IShapeGroupChildOptions = ShapeBaseOptions & { /** A name that connectors use to attach to this shape. It must be unique within the group or canvas */ readonly id?: string; + /** The lane of the flow the shape goes in, by its name. See `ShapeFlowLayout.lanes` */ + readonly lane?: string; } > | IShapeConnectorOptions @@ -119,8 +140,13 @@ type Node = readonly options: IShapeNestedGroupOptions; readonly drawingId: number; readonly children: readonly Node[]; + /** The drawing ids of the band and header of each lane of the group's layout */ + readonly laneIds: readonly LaneIds[]; }; +/** The drawing ids of a lane's band and header */ +type LaneIds = readonly [number, number]; + type Box = { readonly x: number; readonly y: number; @@ -223,6 +249,14 @@ const LABEL_PADDING = { width: 8, height: 4 }; // How far a label at the start or end of a connector is from the shape, and how far it moves at a time to get off a shape, in pixels const LABEL_GAP = 4; const LABEL_STEP = 4; +// How far apart elbow connectors that would lie on top of each other are moved, in pixels +const CHANNEL_SPACING = 6; +// Space around the name in a lane's header, in pixels +const LANE_PADDING = 6; +// A lane's line, unless it is given one: a thin grey line +const LANE_LINE: ShapeLine = { color: "A5A5A5", width: 0.75 }; +// A lane's header's background, unless it is given one +const LANE_HEADER_FILL: ShapeFill = "F2F2F2"; const SIDE_ANGLES: Readonly> = { right: 0, bottom: 90, left: 180, top: 270 }; @@ -319,6 +353,9 @@ const centreOf = ({ left, top, right, bottom }: Bounds): Point => ({ x: (left + const overlaps = (a: Bounds, b: Bounds): boolean => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; +const overlapArea = (a: Bounds, b: Bounds): number => + Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)); + const shrink = ({ left, top, right, bottom }: Bounds, by: number): Bounds => ({ left: left + by, top: top + by, @@ -411,6 +448,14 @@ const shapeSites = (options: ShapeChildOptions, width: number, height: number): return sites.map((site, index) => ({ ...site, index })); }; +/** + * Gives the band and header of each lane of a layout drawing ids. + */ +const assignLaneIds = (layout?: ShapeLayout): readonly LaneIds[] => + layout?.type === "flow" + ? (layout.lanes ?? []).map(() => [docPropertiesUniqueNumericId(), docPropertiesUniqueNumericId()] as const) + : []; + /** * Gives every shape, picture, group, connector and label a drawing id, in the order they are written. */ @@ -425,7 +470,9 @@ const assignIds = (children: readonly IShapeGroupChildOptions[]): readonly Node[ return { kind: "picture", options, drawingId: docPropertiesUniqueNumericId() }; case "group": { const drawingId = docPropertiesUniqueNumericId(); - return { kind: "group", options, drawingId, children: assignIds(options.children) }; + // A group's lanes are drawn first, behind its children + const laneIds = assignLaneIds(options.layout); + return { kind: "group", options, drawingId, laneIds, children: assignIds(options.children) }; } default: return { kind: "shape", options, drawingId: docPropertiesUniqueNumericId() }; @@ -468,7 +515,13 @@ type ConnectorNode = Extract; * * @param transformation - The shape's transformation, with its size worked out if it fits its text */ -const layoutShape = (options: ShapeChildOptions, transformation: IMediaTransformation, drawingId: number, position: Point): PlacedShape => { +const layoutShape = ( + options: ShapeChildOptions, + transformation: IMediaTransformation, + drawingId: number, + position: Point, + styles: TextStyles, +): PlacedShape => { const { rotation: degrees, flip } = transformation; const box = boxAt(position, transformation); const matrix = placement(box, degrees, flip); @@ -491,7 +544,7 @@ const layoutShape = (options: ShapeChildOptions, transformation: IMediaTransform rotation: degrees, flip, data: { - ...createPresetShapeData(options), + ...createPresetShapeData(options, styles), nonVisualDrawingProperties: createNonVisualDrawingProperties(drawingId, kind, options), }, }, @@ -645,20 +698,48 @@ const pointAlong = (points: readonly Point[], distance: number): { readonly poin return { point: { x: segment.start.x + direction.x * along, y: segment.start.y + direction.y * along }, direction }; }; +/** + * The paragraphs a label is written with: centred lines of text given as a string, or the paragraphs it is given. + */ +const labelParagraphs = (label: string | ConnectorLabel, styles: TextStyles): readonly Paragraph[] => { + const text = typeof label === "string" ? label : label.text; + return typeof text === "string" ? createTextParagraphs(text, styles) : text; +}; + +/** + * The size of a connector's label in pixels: as big as its text, unless it is given a size. + * + * @param paragraphs - The label's paragraphs, as they are written + */ +const labelSize = ( + label: string | ConnectorLabel, + paragraphs: readonly Paragraph[], + styles: TextStyles, +): { readonly width: number; readonly height: number } => { + const { width, height } = typeof label === "string" ? { width: undefined, height: undefined } : label; + const measured = + width === undefined || height === undefined ? measureText(readTextParagraphs(paragraphs, styles)) : { width: 0, height: 0 }; + return { + width: width ?? Math.ceil(measured.width * PIXELS_PER_POINT) + LABEL_PADDING.width, + height: height ?? Math.ceil(measured.height * PIXELS_PER_POINT) + LABEL_PADDING.height, + }; +}; + /** * A connector's label: a text box without a line, centred on the connector's route. At the start or end of the * route it is just clear of the shape, and it moves along the route until it is off every shape and label, if it can, * or else beside the route. */ -const layoutLabel = (label: string | ConnectorLabel, points: readonly Point[], drawingId: number, avoid: readonly Bounds[]): Placed => { - const { text, width, height, fill = "none", line = "none", position = "middle" } = typeof label === "string" ? { text: label } : label; - const paragraphs = typeof text === "string" ? createTextParagraphs(text) : text; - // The label is as big as its text, unless it is given a size - const measured = width === undefined || height === undefined ? measureText(getParagraphSpans(paragraphs)) : { width: 0, height: 0 }; - const size = { - width: width ?? Math.ceil(measured.width * PIXELS_PER_POINT) + LABEL_PADDING.width, - height: height ?? Math.ceil(measured.height * PIXELS_PER_POINT) + LABEL_PADDING.height, - }; +const layoutLabel = ( + label: string | ConnectorLabel, + points: readonly Point[], + drawingId: number, + avoid: { readonly boxes: readonly Bounds[]; readonly lines: readonly (readonly Point[])[] }, + styles: TextStyles, +): Placed => { + const { fill = "none", line = "none", position = "middle" } = typeof label === "string" ? {} : label; + const paragraphs = labelParagraphs(label, styles); + const size = labelSize(label, paragraphs, styles); const half = { x: (size.width * EMUS_PER_PIXEL) / 2, y: (size.height * EMUS_PER_PIXEL) / 2 }; // How far the label reaches from its centre in a direction, and a little more const reach = ({ x, y }: Point): number => Math.abs(x) * half.x + Math.abs(y) * half.y + LABEL_GAP * EMUS_PER_PIXEL; @@ -681,14 +762,25 @@ const layoutLabel = (label: string | ConnectorLabel, points: readonly Point[], d height: Math.round(half.y * 2), }; }; - // Places further and further along the route, either way, then the same beside the route + // Places further and further along the route, either way, then the same beside the route: first on the side + // further from the shapes and labels const step = LABEL_STEP * EMUS_PER_PIXEL; const distances = [ wanted, ...Array.from({ length: Math.ceil(total / step) }, (_, index) => [wanted + (index + 1) * step, wanted - (index + 1) * step]).flat(), ].filter((distance) => distance >= 0 && distance <= total); - const places = [0, 1, -1].flatMap((side) => distances.map((distance) => labelBox(distance, side))); - const box = places.find((place) => !avoid.some((other) => overlaps(shrink(boundsOfBox(place), 1), other))) ?? places[0]; + // How much of the space around a place beside the route, as far again as the label is big, is taken up + const crowding = (side: number): number => { + const { x, y, width, height } = labelBox(wanted, side); + const around = { left: x - width, top: y - height, right: x + 2 * width, bottom: y + 2 * height }; + return avoid.boxes.reduce((taken, other) => taken + overlapArea(around, other), 0); + }; + const sides = [0, ...(crowding(-1) < crowding(1) ? [-1, 1] : [1, -1])]; + const places = sides.flatMap((side) => distances.map((distance) => labelBox(distance, side))); + const isClear = (place: Box): boolean => + !avoid.boxes.some((other) => overlaps(shrink(boundsOfBox(place), 1), other)) && + !avoid.lines.some((route) => route.slice(1).some((to, index) => crossesBox(route[index], to, boundsOfBox(place)))); + const box = places.find(isClear) ?? places[0]; return { child: { @@ -887,49 +979,117 @@ const crossesBox = (from: Point, to: Point, bounds: Bounds): boolean => { }; /** - * Routes a connector between the shapes it joins, and places its label clear of the shapes and of `labels`. + * A connector with its route. + */ +type RoutedConnector = ResolvedConnector & { + readonly route: ConnectorRoute; + readonly geometry: ConnectorGeometry; +}; + +/** + * Routes a connector between the shapes it joins. A connector without a `route` is straight, unless a straight line + * would go through another shape, when it bends around it. + */ +const routeResolved = (connector: ResolvedConnector, leaves: readonly Leaf[]): RoutedConnector => { + const { + node: { options }, + ends: [start, finish], + } = connector; + const others = leaves.filter((leaf) => leaf !== start.leaf && leaf !== finish.leaf).map(leafBounds); + const route = options.route ?? (others.some((shape) => crossesBox(start.site.point, finish.site.point, shape)) ? "elbow" : "straight"); + return { + ...connector, + route, + geometry: routeConnector(route, start.site, finish.site, { margin: marginOf(options), obstacles: leaves.map(leafBounds) }), + }; +}; + +const marginOf = ({ margin }: IShapeConnectorOptions): number => (margin ?? DEFAULT_CONNECTOR_MARGIN) * EMUS_PER_PIXEL; + +/** + * Moves apart the lines of elbow connectors that would lie on top of each other, unless moving one would take it + * through more shapes. + */ +const separateRoutes = (routed: readonly RoutedConnector[], leaves: readonly Leaf[]): readonly RoutedConnector[] => { + const obstacles = leaves.map(leafBounds); + const separated = separateChannels( + routed.map(({ route, geometry }) => ({ points: geometry.points, movable: route === "elbow" })), + CHANNEL_SPACING * EMUS_PER_PIXEL, + ); + return routed.map((connector, index) => { + const points = separated[index]; + if (points === connector.geometry.points) { + return connector; + } + const [start, finish] = connector.ends; + const geometry = fitElbowConnector(start.site, finish.site, points, marginOf(connector.node.options)); + return countRouteCrossings(geometry.points, obstacles) > countRouteCrossings(connector.geometry.points, obstacles) + ? connector + : { ...connector, geometry }; + }); +}; + +/** + * Writes a routed connector, and places its label clear of the shapes, of `labels` and of the other connectors' `lines`. * A connector without a `route` is straight, unless a straight line would go through another shape, when it bends * around it. */ const layoutConnector = ( - { node, ends: [start, finish] }: ResolvedConnector, + { node, ends: [start, finish], route, geometry }: RoutedConnector, leaves: readonly Leaf[], - labels: readonly Bounds[], + avoid: { readonly labels: readonly Bounds[]; readonly lines: readonly (readonly Point[])[] }, + styles: TextStyles, ): readonly Placed[] => { const { options: connector, drawingId, labelId } = node; const obstacles = leaves.map(leafBounds); - const others = leaves.filter((leaf) => leaf !== start.leaf && leaf !== finish.leaf).map(leafBounds); - const route = - connector.route ?? (others.some((shape) => crossesBox(start.site.point, finish.site.point, shape)) ? "elbow" : "straight"); - const geometry = routeConnector(route, start.site, finish.site, { - margin: (connector.margin ?? DEFAULT_CONNECTOR_MARGIN) * EMUS_PER_PIXEL, - obstacles, - }); const path = boundsOf(geometry.points); + const data: PresetShapeCoreOptions = + geometry.type === "freeform" + ? { + // A route with more bends than the connector presets have is a line that isn't attached to the shapes + geometry: { + type: "custom", + path: geometry.points + .map(({ x, y }, index) => `${index === 0 ? "M" : "L"} ${x - path.left} ${y - path.top}`) + .join(" "), + }, + line: connector.line, + nonVisualDrawingProperties: createNonVisualDrawingProperties(drawingId, "freeform", connector), + } + : { + geometry: { type: geometry.type, adjustments: geometry.adjustments }, + line: connector.line, + // Attach the connector to shapes with connection sites + connections: { + start: start.site.index === undefined ? undefined : { id: start.leaf.drawingId, index: start.site.index }, + end: finish.site.index === undefined ? undefined : { id: finish.leaf.drawingId, index: finish.site.index }, + }, + nonVisualDrawingProperties: createNonVisualDrawingProperties(drawingId, ROUTE_NAMES[route], connector), + }; const placed: Placed = { child: { type: "wps", box: { ...geometry.offset, width: geometry.width, height: geometry.height }, rotation: geometry.rotation, flip: { horizontal: geometry.flip.horizontal || undefined, vertical: geometry.flip.vertical || undefined }, - data: { - geometry: { type: geometry.type, adjustments: geometry.adjustments }, - line: connector.line, - // Attach the connector to shapes with connection sites - connections: { - start: start.site.index === undefined ? undefined : { id: start.leaf.drawingId, index: start.site.index }, - end: finish.site.index === undefined ? undefined : { id: finish.leaf.drawingId, index: finish.site.index }, - }, - nonVisualDrawingProperties: createNonVisualDrawingProperties(drawingId, ROUTE_NAMES[route], connector), - }, + data, }, box: path, reach: expand(path, uniformExtent(getShapeLineOverhang(connector.line))), }; return connector.label && labelId !== undefined - ? [placed, layoutLabel(connector.label, geometry.points, labelId, [...obstacles, ...labels])] + ? [ + placed, + layoutLabel( + connector.label, + geometry.points, + labelId, + { boxes: [...obstacles, ...avoid.labels], lines: avoid.lines }, + styles, + ), + ] : [placed]; }; @@ -945,8 +1105,8 @@ type InnerGroup = { readonly height: number; }; -const layoutInnerGroup = (node: Extract, allIds: ReadonlySet): InnerGroup => { - const inner = layoutGroup(node.children, allIds, node.options.layout); +const layoutInnerGroup = (node: Extract, allIds: ReadonlySet, styles: TextStyles): InnerGroup => { + const inner = layoutGroup(node.children, allIds, styles, node.options.layout, node.laneIds); const childOffset = { x: Math.round(inner.box.left), y: Math.round(inner.box.top) }; const childExtent = { x: Math.round(inner.box.right) - childOffset.x, y: Math.round(inner.box.bottom) - childOffset.y }; const { width, height } = node.options.transformation ?? {}; @@ -1014,10 +1174,10 @@ type Sized = { /** * Places a shape, picture or group with the top-left corner of its box, before rotation, at a point. */ -const placeSized = ({ node, transformation, inner }: Sized, position: Point): PlacedShape => { +const placeSized = ({ node, transformation, inner }: Sized, position: Point, styles: TextStyles): PlacedShape => { switch (node.kind) { case "shape": - return layoutShape(node.options, transformation!, node.drawingId, position); + return layoutShape(node.options, transformation!, node.drawingId, position, styles); case "picture": return layoutPicture(node.options, node.drawingId, position); default: @@ -1025,10 +1185,10 @@ const placeSized = ({ node, transformation, inner }: Sized, position: Point): Pl } }; -const sizeNode = (node: Exclude, allIds: ReadonlySet): Sized => { +const sizeNode = (node: Exclude, allIds: ReadonlySet, styles: TextStyles): Sized => { switch (node.kind) { case "shape": { - const transformation = resolveShapeSize(node.options); + const transformation = resolveShapeSize(node.options, styles); const { width, height } = boxAt({ x: 0, y: 0 }, transformation); return { node, @@ -1050,7 +1210,7 @@ const sizeNode = (node: Exclude, allIds: ReadonlySet; + /** The lanes of a flow, with where their bands and headers go */ + readonly lanes: readonly PlacedLane[]; +}; + +type PlacedLane = { + readonly lane: ShapeLane; + readonly band: Box; + readonly header: Box; + /** The lane's name, written in its header */ + readonly paragraphs: readonly Paragraph[]; }; /** * Where to place each shape, picture and group: at its `offset`, or where the layout puts it. The layout places the * box around each rotated child, and follows the connectors between the children it places. */ -const arrange = (sized: readonly Sized[], connectors: readonly ConnectorNode[], layout?: ShapeLayout): Arrangement => { +const arrange = (sized: readonly Sized[], connectors: readonly ConnectorNode[], styles: TextStyles, layout?: ShapeLayout): Arrangement => { const origin = { x: 0, y: 0 }; + const lanes = lanesOf(layout); + const laneIndex = ({ node }: Sized): number => { + const { lane } = node.options; + const index = lane === undefined ? 0 : lanes.findIndex(({ name }) => name === lane); + if (index === -1) { + throw new Error(`Invalid lane "${lane}". The layout has no lane with that name`); + } + return index; + }; + sized.forEach(laneIndex); if (!layout) { - return { positions: sized.map(({ offset }) => offset ?? origin), levels: new Map() }; + return { positions: sized.map(({ offset }) => offset ?? origin), levels: new Map(), lanes: [] }; } + // A connector to a shape inside a group follows the group + const has = (item: Sized, connectorEnd: ConnectorEnd): boolean => idsOf(item.node).includes(endId(connectorEnd)); const free = sized.filter((item) => item.offset === undefined); - const turned = free.map((item) => { + // Shapes with an offset that connect to shapes the layout places take part in it, and the layout is placed around them + const anchors = sized.filter( + (item) => + item.offset !== undefined && + connectors.some( + ({ options: { from, to } }) => + (has(item, from) && free.some((other) => has(other, to))) || (has(item, to) && free.some((other) => has(other, from))), + ), + ); + const placed = sized.filter((item) => item.offset === undefined || anchors.includes(item)); + const turned = placed.map((item) => { const radians = ((item.rotation ?? 0) * Math.PI) / 180; const cos = Math.abs(Math.cos(radians)); const sin = Math.abs(Math.sin(radians)); - return { width: item.width * cos + item.height * sin, height: item.width * sin + item.height * cos }; + return { width: item.width * cos + item.height * sin, height: item.width * sin + item.height * cos, lane: laneIndex(item) }; }); - // A connector to a shape inside a group follows the group - const itemWith = (connectorEnd: ConnectorEnd): number => free.findIndex((item) => idsOf(item.node).includes(endId(connectorEnd))); + const itemWith = (connectorEnd: ConnectorEnd): number => placed.findIndex((item) => has(item, connectorEnd)); + // The levels of a flow or tree leave room for labels along the direction they run in + const vertical = layout.type === "grid" || layout.direction === undefined || layout.direction === "down" || layout.direction === "up"; + const labelLength = ({ label }: IShapeConnectorOptions): number | undefined => { + if (label === undefined) { + return undefined; + } + const size = labelSize(label, labelParagraphs(label, styles), styles); + return (vertical ? size.height : size.width) * EMUS_PER_PIXEL; + }; const edges = connectors - .map(({ options }) => ({ from: itemWith(options.from), to: itemWith(options.to) })) + .map(({ options }) => ({ + from: itemWith(options.from), + to: itemWith(options.to), + across: layout.type === "grid" ? undefined : sideAcross(options, layout.direction), + labelLength: layout.type === "grid" ? undefined : labelLength(options), + })) .filter(({ from, to }) => from !== -1 && to !== -1); - const { positions, levels } = layoutItems(layout, turned, edges); + // A lane's header fits its name: when the flow runs down, the header is as long as the name is tall and the lane at + // least as wide as the name, and when it runs across, the header is as long as the longest name + const headerParagraphs = lanes.map(({ name }) => createTextParagraphs(name, styles)); + const headerSizes = headerParagraphs.map((paragraphs) => { + const { width, height } = measureText(readTextParagraphs(paragraphs, styles)); + const [along, across] = vertical ? [height, width] : [width, height]; + return { + along: (Math.ceil(along * PIXELS_PER_POINT) + 2 * LANE_PADDING) * EMUS_PER_PIXEL, + across: (Math.ceil(across * PIXELS_PER_POINT) + 2 * LANE_PADDING) * EMUS_PER_PIXEL, + }; + }); + const headers = { length: Math.max(0, ...headerSizes.map(({ along }) => along)), widths: headerSizes.map(({ across }) => across) }; + const { positions, levels, lanes: laneBoxes = [] } = layoutItems(layout, turned, edges, headers); // Centred on whole pixels, with the box before rotation centred in the box around the rotated child const snap = (centre: number, length: number): number => Math.round(Math.round(centre / EMUS_PER_PIXEL) * EMUS_PER_PIXEL - length / 2); const laidOut = new Map( - free.map((item, index) => [ + placed.map((item, index) => [ item, { x: snap(positions[index].x + turned[index].width / 2, item.width), @@ -1106,12 +1323,115 @@ const arrange = (sized: readonly Sized[], connectors: readonly ConnectorNode[], }, ]), ); + // Moved, by whole pixels, so the shapes with an offset are where it puts them, or as near as they can all be + const shiftBy = (axis: "x" | "y"): number => + Math.round((mean(anchors.map((item) => item.offset![axis] - laidOut.get(item)![axis])) ?? 0) / EMUS_PER_PIXEL) * EMUS_PER_PIXEL; + const shift = { x: shiftBy("x"), y: shiftBy("y") }; + const shifted = ({ x, y, width, height }: Box): Box => ({ x: Math.round(x + shift.x), y: Math.round(y + shift.y), width, height }); return { - positions: sized.map((item) => item.offset ?? laidOut.get(item)!), - levels: new Map(levels ? free.map((item, index) => [item.node, levels[index]]) : []), + positions: sized.map((item) => { + const position = laidOut.get(item); + return item.offset ?? { x: position!.x + shift.x, y: position!.y + shift.y }; + }), + levels: new Map(levels ? placed.map((item, index) => [item.node, levels[index]]) : []), + lanes: laneBoxes.map(({ band, header }, index) => ({ + lane: lanes[index], + band: shifted(band), + header: shifted(header), + paragraphs: headerParagraphs[index], + })), }; }; +const mean = (values: readonly number[]): number | undefined => + values.length > 0 ? values.reduce((total, value) => total + value, 0) / values.length : undefined; + +/** + * The lanes of a flow, with a name for each. + * + * @throws If two lanes have the same name + */ +const lanesOf = (layout?: ShapeLayout): readonly ShapeLane[] => { + const lanes = layout?.type === "flow" ? (layout.lanes ?? []).map((lane) => (typeof lane === "string" ? { name: lane } : lane)) : []; + const repeated = lanes.find(({ name }, index) => lanes.findIndex((other) => other.name === name) !== index); + if (repeated) { + throw new Error(`Invalid lane "${repeated.name}". Each lane in a layout needs a different name`); + } + return lanes; +}; + +/** + * A lane's band, drawn behind the shapes in it, and its header, with its name in it. + */ +const layoutLane = ({ lane, band, header, paragraphs }: PlacedLane, [bandId, headerId]: LaneIds, styles: TextStyles): readonly Placed[] => { + const line = lane.line ?? LANE_LINE; + const overhang = uniformExtent(getShapeLineOverhang(line)); + const pixels = ({ width, height }: Box): { readonly width: number; readonly height: number } => ({ + width: width / EMUS_PER_PIXEL, + height: height / EMUS_PER_PIXEL, + }); + return [ + { + child: { + type: "wps", + box: band, + data: { + ...createPresetShapeData({ type: "rectangle", transformation: pixels(band), fill: lane.fill, line }, styles), + // Screen readers read the lane's name in its header, and skip its band + nonVisualDrawingProperties: createNonVisualDrawingProperties(bandId, "rectangle", { + altText: { name: lane.name }, + decorative: true, + }), + }, + }, + box: boundsOfBox(band), + reach: expand(boundsOfBox(band), overhang), + }, + { + child: { + type: "wps", + box: header, + data: { + ...createPresetShapeData( + { + type: "rectangle", + transformation: pixels(header), + fill: lane.headerFill ?? LANE_HEADER_FILL, + line, + children: paragraphs, + textOptions: { margins: { top: 0, right: 0, bottom: 0, left: 0 }, wrap: false, verticalAlignment: "center" }, + }, + styles, + ), + nonVisualDrawingProperties: createNonVisualDrawingProperties(headerId, "textBox", {}), + }, + }, + box: boundsOfBox(header), + reach: expand(boundsOfBox(header), overhang), + }, + ]; +}; + +/** + * Which way across the levels a connector with a side goes: leaving the right of a shape in a flow that runs down puts + * the shape it leads to on the right, and so does arriving at the left of it. + */ +const sideAcross = (connector: IShapeConnectorOptions, direction: ShapeLayoutDirection = "down"): -1 | 1 | undefined => { + const [before, after]: readonly [ConnectorSide, ConnectorSide] = + direction === "down" || direction === "up" ? ["left", "right"] : ["top", "bottom"]; + const sideOf = (connectorEnd: ConnectorEnd): ConnectorSide | undefined => + typeof connectorEnd === "string" ? undefined : connectorEnd.side; + const from = sideOf(connector.from); + if (from === before || from === after) { + return from === after ? 1 : -1; + } + const to = sideOf(connector.to); + if (to === before || to === after) { + return to === before ? 1 : -1; + } + return undefined; +}; + // The sides connectors leave and arrive at between levels of a flow or tree, and the side connectors that lead back use const LEVEL_SIDES: Readonly< Record @@ -1149,7 +1469,13 @@ const levelSides = ( /** * Lays out the children of a group: first the shapes, pictures and groups, then the connectors between them. */ -const layoutGroup = (nodes: readonly Node[], allIds: ReadonlySet, layout?: ShapeLayout): GroupLayout => { +const layoutGroup = ( + nodes: readonly Node[], + allIds: ReadonlySet, + styles: TextStyles, + layout?: ShapeLayout, + laneIds: readonly LaneIds[] = [], +): GroupLayout => { if (nodes.length === 0) { throw new Error("Invalid shape group. Expected at least 1 child shape"); } @@ -1158,9 +1484,9 @@ const layoutGroup = (nodes: readonly Node[], allIds: ReadonlySet, layout const connectors = nodes.filter((node): node is ConnectorNode => node.kind === "connector"); const sized = nodes .filter((node): node is Exclude => node.kind !== "connector") - .map((node) => sizeNode(node, allIds)); - const { positions, levels } = arrange(sized, connectors, layout); - const shapes = new Map(sized.map((item, index) => [item.node, placeSized(item, positions[index])] as const)); + .map((node) => sizeNode(node, allIds, styles)); + const { positions, levels, lanes } = arrange(sized, connectors, styles, layout); + const shapes = new Map(sized.map((item, index) => [item.node, placeSized(item, positions[index], styles)] as const)); const leaves = [...shapes.values()].flatMap(({ leaves: shapeLeaves }) => shapeLeaves); const levelOf = (id: string): number | undefined => { const item = sized.find(({ node }) => idsOf(node).includes(id)); @@ -1176,10 +1502,16 @@ const layoutGroup = (nodes: readonly Node[], allIds: ReadonlySet, layout ), ), ); - // Connectors are routed in order, and each label keeps clear of the labels before it - const routed = resolved.reduce( + // Connectors are routed, then moved apart where they lie on top of each other, and each label keeps clear of the + // other connectors and the labels before it + const separated = separateRoutes( + resolved.map((connector) => routeResolved(connector, leaves)), + leaves, + ); + const routed = separated.reduce( ({ connectors: done, labels }, connector) => { - const pieces = layoutConnector(connector, leaves, labels); + const lines = separated.filter((other) => other !== connector).map(({ geometry }) => geometry.points); + const pieces = layoutConnector(connector, leaves, { labels, lines }, styles); return { connectors: new Map([...done, [connector.node, pieces]]), labels: [...labels, ...pieces.slice(1).map(({ box }) => box)], @@ -1188,8 +1520,11 @@ const layoutGroup = (nodes: readonly Node[], allIds: ReadonlySet, layout { connectors: new Map(), labels: [] as readonly Bounds[] }, ).connectors; - // Everything is drawn in the order it is given - const placed = nodes.flatMap((node) => (node.kind === "connector" ? routed.get(node)! : [shapes.get(node)!.placed])); + // The lanes are drawn first, then everything in the order it is given + const placed = [ + ...lanes.flatMap((lane, index) => layoutLane(lane, laneIds[index], styles)), + ...nodes.flatMap((node) => (node.kind === "connector" ? routed.get(node)! : [shapes.get(node)!.placed])), + ]; return { children: placed.map(({ child }) => child), box: union(placed.map(({ box }) => box)), @@ -1227,21 +1562,50 @@ const toMediaData = (child: LaidOutChild, shift: Point): ShapeDrawingChildMediaD } }; +/** + * The children of a group or canvas, with the drawing ids they are written with. + */ +export type ShapeDrawingNodes = { + readonly nodes: readonly Node[]; + /** The `id` of every shape and picture */ + readonly ids: ReadonlySet; + /** The drawing ids of the band and header of each lane of the layout */ + readonly laneIds: readonly LaneIds[]; +}; + +/** + * Gives the children of a group or canvas their drawing ids. Every shape, picture, group and connector identifies + * itself with a cNvPr, which needs an id that is unique in the document. + * + * @throws If two shapes or pictures have the same `id` + */ +export const createShapeDrawingNodes = (children: readonly IShapeGroupChildOptions[], layout?: ShapeLayout): ShapeDrawingNodes => { + // The lanes are drawn first, behind the children + const laneIds = assignLaneIds(layout); + const nodes = assignIds(children); + return { nodes, ids: collectIds(nodes), laneIds }; +}; + /** * Lays out the shapes, pictures, groups and connectors of a group or canvas. They are drawn in the order given, * and connectors can attach to shapes that come after them. * + * @param children - The children, or the children with their drawing ids * @param options.keepPositive - Moves everything right and down, if needed, so nothing that is drawn is above or to the left of (0, 0) * @param options.layout - Places the children that have no `offset` - * @throws If a group has no children, two shapes have the same `id`, or a connector refers to an `id` no shape in its group has + * @param options.styles - The document's styles, which text is measured in. Default is Word's own defaults + * @throws If a group has no children, two shapes have the same `id`, a connector refers to an `id` no shape in its group has, or a shape to a lane the layout doesn't have */ export const layoutShapeDrawing = ( - children: readonly IShapeGroupChildOptions[], - { keepPositive = false, layout: shapeLayout }: { readonly keepPositive?: boolean; readonly layout?: ShapeLayout } = {}, + children: readonly IShapeGroupChildOptions[] | ShapeDrawingNodes, + { + keepPositive = false, + layout: shapeLayout, + styles = WORD_DEFAULT_STYLES, + }: { readonly keepPositive?: boolean; readonly layout?: ShapeLayout; readonly styles?: TextStyles } = {}, ): ShapeDrawingLayout => { - // Every shape, picture, group and connector identifies itself with a cNvPr, which needs a unique id - const nodes = assignIds(children); - const layout = layoutGroup(nodes, collectIds(nodes), shapeLayout); + const { nodes, ids, laneIds } = "nodes" in children ? children : createShapeDrawingNodes(children, shapeLayout); + const layout = layoutGroup(nodes, ids, styles, shapeLayout, laneIds); const shift = keepPositive ? { x: Math.max(0, -layout.reach.left), y: Math.max(0, -layout.reach.top) } : { x: 0, y: 0 }; const move = ({ left, top, right, bottom }: Bounds): Bounds => ({ left: left + shift.x, @@ -1257,6 +1621,47 @@ export const layoutShapeDrawing = ( }; }; +/** + * The paragraphs of text in a shape whose size or text depends on the document's styles, or nothing if they don't: + * its size fits its text, or its `text` is written to suit them. + */ +export const shapeStyledParagraphs = ({ + transformation, + text, + children = [], +}: Pick): readonly Paragraph[] | undefined => + transformation.width === "fitText" || transformation.height === "fitText" || text !== undefined ? children : undefined; + +/** + * The paragraphs of text in a group or canvas whose layout depends on the document's styles, or nothing if it doesn't: + * a shape in it fits its text or has `text`, a label is sized to its text or has text given as a string, or its layout + * has lanes, whose headers fit their names. + */ +export const drawingStyledParagraphs = ( + children: readonly IShapeGroupChildOptions[], + layout?: ShapeLayout, +): readonly Paragraph[] | undefined => { + const found = children.map((child): readonly Paragraph[] | undefined => { + switch (child.type) { + case "connector": { + const label = typeof child.label === "string" ? { text: child.label } : child.label; + if (label === undefined || (typeof label.text !== "string" && label.width !== undefined && label.height !== undefined)) { + return undefined; + } + return typeof label.text === "string" ? [] : label.text; + } + case "picture": + return undefined; + case "group": + return drawingStyledParagraphs(child.children, child.layout); + default: + return shapeStyledParagraphs(child); + } + }); + const hasLanes = layout?.type === "flow" && layout.lanes !== undefined && layout.lanes.length > 0; + return hasLanes || found.some((paragraphs) => paragraphs !== undefined) ? found.flatMap((paragraphs) => paragraphs ?? []) : undefined; +}; + /** * How far, in EMUs, what a group draws reaches past each side of the group, once its children are scaled to the * group's size and the group is flipped and rotated. diff --git a/src/shapes/shape-floating.spec.ts b/src/shapes/shape-floating.spec.ts new file mode 100644 index 0000000000..b4e520f5da --- /dev/null +++ b/src/shapes/shape-floating.spec.ts @@ -0,0 +1,178 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { Formatter } from "@export/formatter"; +import * as convenienceFunctions from "@util/convenience-functions"; +import { + HorizontalPositionAlign, + HorizontalPositionRelativeFrom, + type IXmlableObject, + VerticalPositionAlign, + VerticalPositionRelativeFrom, +} from "docx"; + +import { layoutShapeDrawing } from "./shape-drawing"; +import { ShapeRun } from "./shape-run"; + +const anchorOf = (shape: ShapeRun): readonly IXmlableObject[] => new Formatter().format(shape)["w:r"][0]["w:drawing"][0]["wp:anchor"]; + +const find = (children: readonly IXmlableObject[], key: string): IXmlableObject => children.find((child) => key in child)!; + +describe("shapes that float with percentages", () => { + beforeEach(() => { + vi.spyOn(convenienceFunctions, "docPropertiesUniqueNumericId").mockReturnValue(1); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("should draw a rule as wide as the space between the margins, however wide the page is", () => { + const anchor = anchorOf( + new ShapeRun({ + type: "line", + transformation: { width: "100%", height: 0 }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, offset: 0 }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 }, + }, + }), + ); + // As wide as on an A4 page with 1-inch margins, for applications that don't read the percentage + expect(find(anchor, "wp:extent")["wp:extent"]._attr.cx).to.equal(Math.round((11906 / 15 - 192) * 9525)); + // After the graphic, where Word writes it + expect(anchor.map((child) => Object.keys(child)[0]).slice(-2)).to.deep.equal(["a:graphic", "wp14:sizeRelH"]); + expect(find(anchor, "wp14:sizeRelH")).to.deep.equal({ + "wp14:sizeRelH": [{ _attr: { relativeFrom: "margin" } }, { "wp14:pctWidth": ["100000"] }], + }); + expect(find(anchor, "wp:positionH")["wp:positionH"][1]).to.deep.equal({ "wp:posOffset": ["0"] }); + }); + + it("should write percentage offsets in place of the offsets, and sizes relative to other parts of the page", () => { + const anchor = anchorOf( + new ShapeRun({ + type: "rectangle", + transformation: { width: "25%", height: "50%" }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.PAGE, offset: "70%" }, + verticalPosition: { relative: VerticalPositionRelativeFrom.TOP_MARGIN, offset: "12.5%" }, + sizeRelativeTo: { width: "page", height: "bottomMargin" }, + }, + }), + ); + // The percentage for applications that read it, and the offset on the default page for those that don't + expect(find(anchor, "wp:positionH")).to.deep.equal({ + "wp:positionH": [ + { _attr: { relativeFrom: "page" } }, + { + "mc:AlternateContent": [ + { "mc:Choice": [{ _attr: { Requires: "wp14" } }, { "wp14:pctPosHOffset": ["70000"] }] }, + { "mc:Fallback": [{ "wp:posOffset": [`${Math.round((11906 / 15) * 0.7 * 9525)}`] }] }, + ], + }, + ], + }); + expect(find(anchor, "wp:positionV")["wp:positionV"][1]["mc:AlternateContent"][0]).to.deep.equal({ + "mc:Choice": [{ _attr: { Requires: "wp14" } }, { "wp14:pctPosVOffset": ["12500"] }], + }); + expect(anchor.slice(-2)).to.deep.equal([ + { "wp14:sizeRelH": [{ _attr: { relativeFrom: "page" } }, { "wp14:pctWidth": ["25000"] }] }, + { "wp14:sizeRelV": [{ _attr: { relativeFrom: "bottomMargin" } }, { "wp14:pctHeight": ["50000"] }] }, + ]); + // A quarter of the page's width, and half the bottom margin, on the default page + const extent = find(anchor, "wp:extent")["wp:extent"]._attr; + expect(extent.cx).to.be.closeTo((11906 / 15) * 0.25 * 9525, 1); + expect(extent.cy).to.equal(48 * 9525); + }); + + it("should size a shape that fits its text in a percentage width", () => { + const anchor = anchorOf( + new ShapeRun({ + type: "rectangle", + text: "A banner", + transformation: { width: "50%", height: "fitText" }, + floating: { + horizontalPosition: { offset: 0 }, + verticalPosition: { offset: 0 }, + sizeRelativeTo: { width: "leftMargin" }, + }, + }), + ); + expect(find(anchor, "wp14:sizeRelH")["wp14:sizeRelH"][0]._attr.relativeFrom).to.equal("leftMargin"); + expect(anchor.some((child) => "wp14:sizeRelV" in child)).to.equal(false); + }); + + it("should write percentage offsets without percentage sizes, and percentage sizes with aligned positions", () => { + const offsets = anchorOf( + new ShapeRun({ + type: "rectangle", + transformation: { width: 10, height: 10 }, + floating: { horizontalPosition: { offset: "50%" }, verticalPosition: { offset: "50%" } }, + }), + ); + expect(offsets.some((child) => "wp14:sizeRelH" in child || "wp14:sizeRelV" in child)).to.equal(false); + expect(find(offsets, "wp:positionH")["wp:positionH"][1]["mc:AlternateContent"][0]["mc:Choice"][1]).to.deep.equal({ + "wp14:pctPosHOffset": ["50000"], + }); + + const aligned = anchorOf( + new ShapeRun({ + type: "rectangle", + transformation: { width: 10, height: "10%" }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, align: HorizontalPositionAlign.CENTER }, + verticalPosition: { relative: VerticalPositionRelativeFrom.MARGIN, align: VerticalPositionAlign.TOP }, + }, + }), + ); + expect(find(aligned, "wp:positionH")["wp:positionH"][1]).to.deep.equal({ "wp:align": ["center"] }); + expect(find(aligned, "wp14:sizeRelV")["wp14:sizeRelV"][1]).to.deep.equal({ "wp14:pctHeight": ["10000"] }); + }); + + it("should write a floating shape without percentages as an image would be", () => { + const floating = { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.PAGE, offset: 914400 }, + verticalPosition: { relative: VerticalPositionRelativeFrom.PAGE, offset: 914400 }, + }; + const anchor = anchorOf(new ShapeRun({ type: "rectangle", transformation: { width: 10, height: 10 }, floating })); + expect(anchor.some((child) => Object.keys(child)[0].startsWith("wp14:"))).to.equal(false); + expect(find(anchor, "wp:positionH")["wp:positionH"][1]).to.deep.equal({ "wp:posOffset": ["914400"] }); + }); + + it("should throw for a percentage that isn't one, of something it can't be of, or on a shape that doesn't float", () => { + const floating = { horizontalPosition: { offset: 0 }, verticalPosition: { offset: 0 } }; + expect(() => new ShapeRun({ type: "rectangle", transformation: { width: "-5%", height: 10 }, floating })).to.throw( + 'Invalid width "-5%". Expected a percentage of 0 or more', + ); + expect(() => new ShapeRun({ type: "rectangle", transformation: { width: "%" as "0%", height: 10 }, floating })).to.throw( + 'Invalid width "%"', + ); + expect( + () => + new ShapeRun({ + type: "rectangle", + transformation: { width: 10, height: 10 }, + floating: { + horizontalPosition: { relative: HorizontalPositionRelativeFrom.COLUMN, offset: "10%" }, + verticalPosition: { offset: 0 }, + }, + }), + ).to.throw('Invalid offset "10%". A percentage offset needs a position relative to the page'); + expect( + () => + new ShapeRun({ + type: "rectangle", + transformation: { width: 10, height: 10 }, + floating: { + horizontalPosition: { offset: 0 }, + verticalPosition: { relative: VerticalPositionRelativeFrom.LINE, offset: "10%" }, + }, + }), + ).to.throw('Invalid offset "10%"'); + expect(() => new ShapeRun({ type: "rectangle", transformation: { width: "50%", height: 10 } })).to.throw( + 'Invalid width "50%". Only a floating shape can be a percentage of the page', + ); + expect(() => layoutShapeDrawing([{ type: "rectangle", transformation: { width: 10, height: "50%" } }])).to.throw( + 'Invalid height "50%"', + ); + }); +}); diff --git a/src/shapes/shape-floating.ts b/src/shapes/shape-floating.ts new file mode 100644 index 0000000000..c08dcffb4d --- /dev/null +++ b/src/shapes/shape-floating.ts @@ -0,0 +1,305 @@ +/** + * Floating shapes whose size or position is a percentage of the page, its margins or the space between them + * (`wp14:sizeRelH`, `wp14:sizeRelV`, `wp14:pctPosHOffset` and `wp14:pctPosVOffset`), which Word keeps as percentages + * when the page changes. + * + * Reference: [MS-ODRAWXML] 2.3.2, the wordprocessingDrawing 2010 schema + * + * @module + */ +// cspell:ignore ODRAWXML +import { + HorizontalPositionRelativeFrom, + type IContext, + type IFloating, + type IHorizontalPositionOptions, + type IVerticalPositionOptions, + type IXmlableObject, + VerticalPositionRelativeFrom, + XmlComponent, +} from "docx"; + +/** + * A percentage, such as `"100%"`. + * + * @publicApi + */ +export type ShapePercentage = `${number}%`; + +/** + * Where a floating shape is across the page: as for an image, but the offset can also be a percentage. + * + * @publicApi + */ +export type ShapeHorizontalPosition = Omit & { + /** + * Offset in EMUs from the horizontal base, or a percentage of the base's width, such as `"10%"`. A percentage needs + * a base of the page, the space between its margins, or one of its margins + */ + readonly offset?: number | ShapePercentage; +}; + +/** + * Where a floating shape is down the page: as for an image, but the offset can also be a percentage. + * + * @publicApi + */ +export type ShapeVerticalPosition = Omit & { + /** + * Offset in EMUs from the vertical base, or a percentage of the base's height, such as `"10%"`. A percentage needs + * a base of the page, the space between its margins, or one of its margins + */ + readonly offset?: number | ShapePercentage; +}; + +/** + * What a percentage width is a percentage of. + * + * @publicApi + */ +export type ShapeWidthRelativeTo = "betweenMargins" | "page" | "leftMargin" | "rightMargin" | "insideMargin" | "outsideMargin"; + +/** + * What a percentage height is a percentage of. + * + * @publicApi + */ +export type ShapeHeightRelativeTo = "betweenMargins" | "page" | "topMargin" | "bottomMargin" | "insideMargin" | "outsideMargin"; + +/** + * How a shape floats on the page. It takes the options of a floating image, and offsets can also be percentages. + * + * @publicApi + */ +export type ShapeFloating = Omit & { + readonly horizontalPosition: ShapeHorizontalPosition; + readonly verticalPosition: ShapeVerticalPosition; + /** What a percentage `width` or `height` is a percentage of. Default is the space between the margins, where the text goes */ + readonly sizeRelativeTo?: { + readonly width?: ShapeWidthRelativeTo; + readonly height?: ShapeHeightRelativeTo; + }; +}; + +/** + * The sizes, in pixels, of the areas of the library's default page, A4 with 1-inch margins, which a percentage size or + * offset is written with for applications that don't read percentages. + */ +const PAGE = { width: 11906 / 15, height: 16838 / 15, margin: 96 }; +const BETWEEN_MARGINS = { width: PAGE.width - 2 * PAGE.margin, height: PAGE.height - 2 * PAGE.margin }; + +// Each relative size's OOXML name (`ST_SizeRelFromH` and `ST_SizeRelFromV`), and the length on the default page +const WIDTH_BASES: Readonly> = { + betweenMargins: ["margin", BETWEEN_MARGINS.width], + page: ["page", PAGE.width], + leftMargin: ["leftMargin", PAGE.margin], + rightMargin: ["rightMargin", PAGE.margin], + insideMargin: ["insideMargin", PAGE.margin], + outsideMargin: ["outsideMargin", PAGE.margin], +}; + +const HEIGHT_BASES: Readonly> = { + betweenMargins: ["margin", BETWEEN_MARGINS.height], + page: ["page", PAGE.height], + topMargin: ["topMargin", PAGE.margin], + bottomMargin: ["bottomMargin", PAGE.margin], + insideMargin: ["insideMargin", PAGE.margin], + outsideMargin: ["outsideMargin", PAGE.margin], +}; + +// The width or height of each base a position can be relative to, on the default page, for those a percentage can be of +const POSITION_BASES: Readonly> = { + [HorizontalPositionRelativeFrom.MARGIN]: BETWEEN_MARGINS.width, + [HorizontalPositionRelativeFrom.PAGE]: PAGE.width, + [HorizontalPositionRelativeFrom.LEFT_MARGIN]: PAGE.margin, + [HorizontalPositionRelativeFrom.RIGHT_MARGIN]: PAGE.margin, + [HorizontalPositionRelativeFrom.INSIDE_MARGIN]: PAGE.margin, + [HorizontalPositionRelativeFrom.OUTSIDE_MARGIN]: PAGE.margin, +}; + +const VERTICAL_POSITION_BASES: Readonly> = { + [VerticalPositionRelativeFrom.MARGIN]: BETWEEN_MARGINS.height, + [VerticalPositionRelativeFrom.PAGE]: PAGE.height, + [VerticalPositionRelativeFrom.TOP_MARGIN]: PAGE.margin, + [VerticalPositionRelativeFrom.BOTTOM_MARGIN]: PAGE.margin, + [VerticalPositionRelativeFrom.INSIDE_MARGIN]: PAGE.margin, + [VerticalPositionRelativeFrom.OUTSIDE_MARGIN]: PAGE.margin, +}; + +const EMUS_PER_PIXEL = 9525; + +/** + * Reads a percentage, such as `"50%"`, as a number, such as 50. + * + * @returns The number, or nothing if the value is a number of pixels or EMUs + * @throws If the value is a percentage that isn't a number of 0 or more + */ +export const percentageOf = (value: number | string, option: string): number | undefined => { + if (typeof value === "number" || !value.endsWith("%")) { + return undefined; + } + const percentage = Number(value.slice(0, -1)); + if (!(value.length > 1 && percentage >= 0)) { + throw new Error(`Invalid ${option} "${value}". Expected a percentage of 0 or more, such as "50%"`); + } + return percentage; +}; + +/** + * The size, in pixels, of what a floating shape's percentage width and height are percentages of, on the library's + * default page. + */ +export const relativeSizeBase = (floating: ShapeFloating): { readonly width: number; readonly height: number } => ({ + width: WIDTH_BASES[floating.sizeRelativeTo?.width ?? "betweenMargins"][1], + height: HEIGHT_BASES[floating.sizeRelativeTo?.height ?? "betweenMargins"][1], +}); + +/** + * An offset in EMUs, for a position given as a percentage: the percentage of the base on the library's default page. + * + * @throws If the percentage is of a base it can't be of, such as a column + */ +const offsetOf = ( + offset: number | ShapePercentage | undefined, + relative: string, + bases: Readonly>, +): number | undefined => { + const percentage = offset === undefined ? undefined : percentageOf(offset, "offset"); + if (percentage === undefined) { + return offset as number | undefined; + } + if (!(relative in bases)) { + throw new Error( + `Invalid offset "${offset}". A percentage offset needs a position relative to the page, the space between its margins, or one of its margins`, + ); + } + return Math.round(((bases[relative] * percentage) / 100) * EMUS_PER_PIXEL); +}; + +/** + * The floating options for a drawing, with percentage offsets turned into EMUs, as they are on the library's default page. + * + * @throws If a percentage offset is of a base it can't be of, such as a column + */ +export const toImageFloating = ({ horizontalPosition, verticalPosition, sizeRelativeTo: _, ...rest }: ShapeFloating): IFloating => ({ + ...rest, + horizontalPosition: { + ...horizontalPosition, + offset: offsetOf(horizontalPosition.offset, horizontalPosition.relative ?? HorizontalPositionRelativeFrom.PAGE, POSITION_BASES), + }, + verticalPosition: { + ...verticalPosition, + offset: offsetOf(verticalPosition.offset, verticalPosition.relative ?? VerticalPositionRelativeFrom.PAGE, VERTICAL_POSITION_BASES), + }, +}); + +/** + * The percentages a floating drawing is sized and positioned by, in thousandths of a percent, as OOXML writes them. + */ +type RelativePlacement = { + readonly width?: { readonly relativeFrom: string; readonly percentage: number }; + readonly height?: { readonly relativeFrom: string; readonly percentage: number }; + readonly horizontal?: number; + readonly vertical?: number; +}; + +const thousandths = (percentage: number | undefined): number | undefined => + percentage === undefined ? undefined : Math.round(percentage * 1000); + +/** + * A position with a percentage offset, for applications that read the Word 2010 drawing extensions, and its offset in + * EMUs for those that don't, as Word writes a position that older versions can't read. + */ +const withPercentage = ([attributes, offset]: readonly IXmlableObject[], name: string, percentage: number): readonly IXmlableObject[] => [ + attributes, + { + "mc:AlternateContent": [ + { "mc:Choice": [{ _attr: { Requires: "wp14" } }, { [name]: [`${percentage}`] }] }, + { "mc:Fallback": [offset] }, + ], + }, +]; + +/** + * Adds the percentages to a formatted drawing: offsets in place of the positions' offsets, and sizes after the graphic, + * where Word writes them. + */ +const addPercentages = (xml: IXmlableObject, { width, height, horizontal, vertical }: RelativePlacement): IXmlableObject => { + const anchor = (children: readonly IXmlableObject[]): readonly IXmlableObject[] => [ + ...children.map((child) => { + if ("wp:positionH" in child && horizontal !== undefined) { + return { "wp:positionH": withPercentage(child["wp:positionH"], "wp14:pctPosHOffset", horizontal) }; + } + if ("wp:positionV" in child && vertical !== undefined) { + return { "wp:positionV": withPercentage(child["wp:positionV"], "wp14:pctPosVOffset", vertical) }; + } + return child; + }), + ...(width + ? [{ "wp14:sizeRelH": [{ _attr: { relativeFrom: width.relativeFrom } }, { "wp14:pctWidth": [`${width.percentage}`] }] }] + : []), + ...(height + ? [{ "wp14:sizeRelV": [{ _attr: { relativeFrom: height.relativeFrom } }, { "wp14:pctHeight": [`${height.percentage}`] }] }] + : []), + ]; + // A floating drawing is one anchor + const [floating] = xml["w:drawing"] as readonly IXmlableObject[]; + return { "w:drawing": [{ "wp:anchor": anchor(floating["wp:anchor"]) }] }; +}; + +/** + * A floating drawing with a percentage size or position. + */ +class RelativeDrawing extends XmlComponent { + public constructor( + private readonly drawing: XmlComponent, + private readonly placement: RelativePlacement, + ) { + super("w:drawing"); + } + + public prepForXml(context: IContext): IXmlableObject | undefined { + return addPercentages(this.drawing.prepForXml(context)!, this.placement); + } +} + +/** + * Writes a floating drawing's percentage size and position, if it has any, so Word keeps them as percentages. + * + * @param drawing - The drawing, with its size and position in pixels and EMUs on the library's default page + * @param size - The width and height the shape was given + */ +export const withRelativePlacement = ( + drawing: XmlComponent, + floating: ShapeFloating | undefined, + size: { readonly width: number | string; readonly height: number | string }, +): XmlComponent => { + if (!floating) { + return drawing; + } + const widthPercentage = percentageOf(size.width, "width"); + const heightPercentage = percentageOf(size.height, "height"); + const placement: RelativePlacement = { + width: + widthPercentage === undefined + ? undefined + : { + relativeFrom: WIDTH_BASES[floating.sizeRelativeTo?.width ?? "betweenMargins"][0], + percentage: thousandths(widthPercentage)!, + }, + height: + heightPercentage === undefined + ? undefined + : { + relativeFrom: HEIGHT_BASES[floating.sizeRelativeTo?.height ?? "betweenMargins"][0], + percentage: thousandths(heightPercentage)!, + }, + horizontal: thousandths( + floating.horizontalPosition.offset === undefined ? undefined : percentageOf(floating.horizontalPosition.offset, "offset"), + ), + vertical: thousandths( + floating.verticalPosition.offset === undefined ? undefined : percentageOf(floating.verticalPosition.offset, "offset"), + ), + }; + return Object.values(placement).every((value) => value === undefined) ? drawing : new RelativeDrawing(drawing, placement); +}; diff --git a/src/shapes/shape-group-run.spec.ts b/src/shapes/shape-group-run.spec.ts index 3087c17a72..ebb88e18eb 100644 --- a/src/shapes/shape-group-run.spec.ts +++ b/src/shapes/shape-group-run.spec.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Formatter } from "@export/formatter"; +import { File } from "@file/file"; import * as convenienceFunctions from "@util/convenience-functions"; import { HorizontalPositionRelativeFrom, type IContext, type IXmlableObject, VerticalPositionRelativeFrom } from "docx"; @@ -64,7 +65,10 @@ describe("ShapeGroupRun", () => { "wp:effectExtent": { _attr: { t: 6350, r: 6350, b: 6350, l: 0 } }, }); // Children take ids 1-3 when they are created, before the group's docPr - expect(getChild(container, "wp:docPr")).to.deep.equal({ "wp:docPr": { _attr: { id: 4, name: "", descr: "", title: "" } } }); + // Described from the names of its shapes, as it has no description of its own + expect(getChild(container, "wp:docPr")).to.deep.equal({ + "wp:docPr": { _attr: { id: "4", name: "", descr: "Start. End.", title: "" } }, + }); const group = getGroup(tree); expect(group[1]).to.deep.equal({ @@ -168,7 +172,7 @@ describe("ShapeGroupRun", () => { expect(getChild(container, "wp:effectExtent")).to.deep.equal({ "wp:effectExtent": { _attr: { t: 476250, r: 0, b: 476250, l: 0 } }, }); - expect(getChild(container, "wp:docPr")).to.deep.equal({ "wp:docPr": { _attr: { id: 2, name: "Group" } } }); + expect(getChild(container, "wp:docPr")).to.deep.equal({ "wp:docPr": { _attr: { id: "2", name: "Group" } } }); expect(getGroup(tree)[1]["wpg:grpSpPr"][0]["a:xfrm"]).to.deep.equal([ { _attr: { rot: 5400000 } }, @@ -229,4 +233,31 @@ describe("ShapeGroupRun", () => { it("should reject a group without children", () => { expect(() => new ShapeGroupRun({ children: [] })).to.throw("Expected at least 1 child shape"); }); + + it("should lay out a group whose shapes fit their text in the document's styles when it is written", () => { + const group = new ShapeGroupRun({ + children: [ + { id: "a", type: "rectangle", text: "Start", transformation: { width: "fitText", height: 40 } }, + { id: "b", type: "rectangle", transformation: { offset: { left: 200 }, width: 60, height: 40 } }, + { type: "connector", from: "a", to: "b", label: "Next" }, + ], + }); + const context = { + file: new File({ styles: { default: { document: { run: { size: 40 } } } }, sections: [] }), + stack: [], + } as unknown as IContext; + const plain = getGroup(new Formatter().format(group)); + const styled = getGroup(new Formatter().format(group, context)); + + const width = (children: readonly IXmlableObject[], index: number): number => + Object.values(children[index])[0][2]["wps:spPr"][0]["a:xfrm"][2]["a:ext"]._attr.cx; + // The shape and the connector's label are wider in the bigger text, and the connector is shorter + expect(width(styled, 2)).to.be.greaterThan(width(plain, 2)); + expect(width(styled, 5)).to.be.greaterThan(width(plain, 5)); + expect(width(styled, 4)).to.be.lessThan(width(plain, 4)); + // The shapes keep their ids + const ids = (children: readonly IXmlableObject[]): readonly unknown[] => + children.slice(2).map((child) => Object.values(child)[0][0]["wps:cNvPr"]._attr.id); + expect(ids(styled)).to.deep.equal(ids(plain)); + }); }); diff --git a/src/shapes/shape-group-run.ts b/src/shapes/shape-group-run.ts index 0e8b6838c8..216899b543 100644 --- a/src/shapes/shape-group-run.ts +++ b/src/shapes/shape-group-run.ts @@ -21,11 +21,21 @@ import { import { GROUP_URI, createShapeDrawingChild } from "./drawing/shape-drawing-child"; import { createShapeGroup } from "./drawing/shape-group"; -import { type IShapeGroupChildOptions, getGroupEffectExtent, layoutShapeDrawing } from "./shape-drawing"; +import { createStyledDrawing } from "./drawing/styled-drawing"; +import { describeDrawing } from "./shape-description"; +import { + type IShapeGroupChildOptions, + createShapeDrawingNodes, + drawingStyledParagraphs, + getGroupEffectExtent, + layoutShapeDrawing, +} from "./shape-drawing"; import type { ShapeLayout } from "./shape-layout"; +import { createDrawingProperties } from "./shape-run-data"; +import type { TextStyles } from "./shape-text-styles"; export type { IShapeGroupChildOptions, IShapeNestedGroupOptions, IShapePictureOptions } from "./shape-drawing"; -export type { ShapeFlowLayout, ShapeGridLayout, ShapeLayout, ShapeLayoutDirection, ShapeTreeLayout } from "./shape-layout"; +export type { ShapeFlowLayout, ShapeGridLayout, ShapeLane, ShapeLayout, ShapeLayoutDirection, ShapeTreeLayout } from "./shape-layout"; /** * Options for creating a group of shapes. @@ -83,22 +93,27 @@ export class ShapeGroupRun extends Run { public constructor(options: IShapeGroupOptions) { super({}); - const layout = layoutShapeDrawing(options.children, { layout: options.layout }); - const { children, bounds } = layout; + // The children's drawing ids come before the group's + const nodes = createShapeDrawingNodes(options.children, options.layout); + // Without a description of its own, the group is described from its shapes' text and connectors + const drawingOptions = createDrawingProperties({ ...options, altText: describeDrawing(options) }); - // The children's coordinate space is the box around them, in EMUs - const childOffset = { x: Math.round(bounds.left), y: Math.round(bounds.top) }; - const childExtent = { x: Math.round(bounds.right) - childOffset.x, y: Math.round(bounds.bottom) - childOffset.y }; + const create = (styles: TextStyles): Drawing => { + const layout = layoutShapeDrawing(nodes, { layout: options.layout, styles }); + const { children, bounds } = layout; - const groupTransformation: IMediaDataTransformation = options.transformation - ? createTransformation({ ...options.transformation, offset: undefined }) - : { - pixels: { x: Math.round(childExtent.x / EMUS_PER_PIXEL), y: Math.round(childExtent.y / EMUS_PER_PIXEL) }, - emus: childExtent, - }; + // The children's coordinate space is the box around them, in EMUs + const childOffset = { x: Math.round(bounds.left), y: Math.round(bounds.top) }; + const childExtent = { x: Math.round(bounds.right) - childOffset.x, y: Math.round(bounds.bottom) - childOffset.y }; - this.root.push( - new Drawing( + const groupTransformation: IMediaDataTransformation = options.transformation + ? createTransformation({ ...options.transformation, offset: undefined }) + : { + pixels: { x: Math.round(childExtent.x / EMUS_PER_PIXEL), y: Math.round(childExtent.y / EMUS_PER_PIXEL) }, + emus: childExtent, + }; + + return new Drawing( { type: "graphic", uri: GROUP_URI, @@ -111,10 +126,7 @@ export class ShapeGroupRun extends Run { }), }, { - floating: options.floating, - docProperties: options.altText, - link: options.link, - decorative: options.decorative, + ...drawingOptions, // Lines, effects and rotated shapes can reach past the group's box effectExtent: getGroupEffectExtent(layout, childOffset, childExtent, { width: groupTransformation.emus.x, @@ -123,7 +135,10 @@ export class ShapeGroupRun extends Run { flip: options.transformation?.flip, }), }, - ), - ); + ); + }; + + // A group whose shapes fit their text is laid out in the document's styles when it is written + this.root.push(createStyledDrawing(create, drawingStyledParagraphs(options.children, options.layout))); } } diff --git a/src/shapes/shape-layout-coordinates.spec.ts b/src/shapes/shape-layout-coordinates.spec.ts new file mode 100644 index 0000000000..babfff484f --- /dev/null +++ b/src/shapes/shape-layout-coordinates.spec.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vitest"; + +import { type LevelGraph, type LevelLink, assignLevelCoordinates } from "./shape-layout-coordinates"; + +const SPACING = 10; + +/** + * A graph whose nodes are as wide as `sizes` gives, or 20, or points of no width, with `SPACING` between shapes. + */ +const graphOf = ( + order: readonly (readonly number[])[], + links: readonly LevelLink[], + sizes: Readonly> = {}, + points: readonly number[] = [], +): LevelGraph => ({ + order, + links, + sizes: new Map(order.flat().map((node) => [node, points.includes(node) ? 0 : (sizes[node] ?? 20)])), + points: new Set(points), + spacing: SPACING, +}); + +const gapOf = (graph: LevelGraph, a: number, b: number): number => + (graph.sizes.get(a)! + graph.sizes.get(b)!) / 2 + (graph.points.has(a) || graph.points.has(b) ? SPACING / 2 : SPACING); + +const expectGaps = (graph: LevelGraph, centres: ReadonlyMap): void => { + for (const level of graph.order) { + for (let index = 1; index < level.length; index++) { + expect(centres.get(level[index])! - centres.get(level[index - 1])!).to.be.at.least( + gapOf(graph, level[index - 1], level[index]) - 1e-9, + ); + } + } +}; + +describe("assignLevelCoordinates", () => { + it("should line up a chain of shapes", () => { + const centres = assignLevelCoordinates( + graphOf( + [[0], [1], [2]], + [ + { from: 0, to: 1 }, + { from: 1, to: 2 }, + ], + { 1: 80 }, + ), + ); + expect(centres.get(0)).to.equal(centres.get(1)); + expect(centres.get(1)).to.equal(centres.get(2)); + }); + + it("should put a shape over the middle one of the shapes it leads to, whatever their sizes", () => { + const graph = graphOf( + [[0], [1, 2, 3]], + [ + { from: 0, to: 1 }, + { from: 0, to: 2 }, + { from: 0, to: 3 }, + ], + { 1: 100, 2: 50, 3: 300 }, + ); + const centres = assignLevelCoordinates(graph); + expect(centres.get(0)).to.equal(centres.get(2)); + expectGaps(graph, centres); + }); + + it("should put a shape with two shapes before it between them", () => { + const graph = graphOf( + [[0, 1], [2]], + [ + { from: 0, to: 2 }, + { from: 1, to: 2 }, + ], + ); + const centres = assignLevelCoordinates(graph); + expect(centres.get(2)).to.be.closeTo((centres.get(0)! + centres.get(1)!) / 2, 1e-9); + }); + + it("should keep a long connector straight, and move shapes that would bend it", () => { + // 0 leads to 4 through the points 5 and 6, beside the chain 1, 2, 3, 7, whose wide shape 2 pushes against it + const graph = graphOf( + [ + [0, 1], + [5, 2], + [6, 3], + [4, 7], + ], + [ + { from: 0, to: 5 }, + { from: 5, to: 6 }, + { from: 6, to: 4 }, + { from: 1, to: 2 }, + { from: 2, to: 3 }, + { from: 3, to: 7 }, + ], + { 2: 120 }, + [5, 6], + ); + const centres = assignLevelCoordinates(graph); + expect(centres.get(5)).to.equal(centres.get(6)); + expectGaps(graph, centres); + }); + + it("should not line up a link that crosses a long connector", () => { + // 1 leads to 4, crossing the long connector from 0 through 2 and 3 to 5 + const graph = graphOf( + [ + [0, 1], + [2, 6], + [4, 3], + [5, 7], + ], + [ + { from: 0, to: 2 }, + { from: 2, to: 3 }, + { from: 3, to: 5 }, + { from: 1, to: 6 }, + { from: 6, to: 4 }, + { from: 4, to: 7 }, + ], + {}, + [2, 3], + ); + const centres = assignLevelCoordinates(graph); + expect(centres.get(2)).to.equal(centres.get(3)); + expectGaps(graph, centres); + }); + + it("should not line up shapes joined by a link that is left out of lining up", () => { + const centres = assignLevelCoordinates( + graphOf( + [[0], [1, 2]], + [ + { from: 0, to: 1 }, + { from: 0, to: 2, skipAlignment: true }, + ], + ), + ); + expect(centres.get(0)).to.equal(centres.get(1)); + }); + + it("should line the layouts up with the narrowest of them", () => { + // Lining 0 up with 1 or with 2 makes layouts of different widths + const graph = graphOf( + [[0], [1, 2, 3]], + [ + { from: 0, to: 1 }, + { from: 0, to: 2 }, + ], + { 0: 60, 1: 20, 2: 100, 3: 100 }, + ); + const centres = assignLevelCoordinates(graph); + expect(centres.get(0)).to.be.within(centres.get(1)!, centres.get(2)!); + expectGaps(graph, centres); + }); + + it("should keep long connectors that cross each other straight where they can", () => { + // Two long connectors, from 0 to 6 and from 1 to 7, cross between the points on the middle levels + const graph = graphOf( + [ + [0, 1], + [2, 3], + [4, 5], + [6, 7], + ], + [ + { from: 0, to: 2 }, + { from: 2, to: 5 }, + { from: 5, to: 7 }, + { from: 1, to: 3 }, + { from: 3, to: 4 }, + { from: 4, to: 6 }, + ], + {}, + [2, 3, 4, 5], + ); + const centres = assignLevelCoordinates(graph); + expect([...centres.values()].every(Number.isFinite)).to.equal(true); + expectGaps(graph, centres); + }); + + it("should pack shapes without links next to each other", () => { + const graph = graphOf([[0, 1, 2]], []); + const centres = assignLevelCoordinates(graph); + expect(centres.get(1)! - centres.get(0)!).to.equal(30); + expect(centres.get(2)! - centres.get(1)!).to.equal(30); + }); +}); diff --git a/src/shapes/shape-layout-coordinates.ts b/src/shapes/shape-layout-coordinates.ts new file mode 100644 index 0000000000..dcdcef3e03 --- /dev/null +++ b/src/shapes/shape-layout-coordinates.ts @@ -0,0 +1,225 @@ +/** + * Places the shapes on each level of a flow across the level, once the levels are ordered: the Brandes–Köpf method. + * Not part of the public API. + * + * Each shape is lined up with the middle one of the shapes it connects to on the level before, as far as the order + * allows, so connectors are straight, and the points long connectors pass through line up first, so long connectors + * are straight too. This is done four ways, lining shapes up with the level before and the level after, packed to the + * left and to the right, and each shape is placed between the middle two of its four positions. + * + * Reference: U. Brandes and B. Köpf, "Fast and Simple Horizontal Coordinate Assignment", Graph Drawing 2001. The shapes + * are packed as the dagre library packs them, which avoids a flaw in the paper's packing. + * + * @module + */ +// cspell:ignore Brandes Köpf dagre + +/** + * A connector between shapes, or points long connectors pass through, on neighboring levels. + */ +export type LevelLink = { + readonly from: number; + readonly to: number; + /** Whether the link is left out when shapes are lined up, such as a connector that leaves the side of a shape */ + readonly skipAlignment?: boolean; +}; + +/** + * The levels to place, and what they are placed by. + */ +export type LevelGraph = { + /** The nodes on each level, in order */ + readonly order: readonly (readonly number[])[]; + /** Links from one level to the next */ + readonly links: readonly LevelLink[]; + /** Each node's length across its level. Points that long connectors pass through have none */ + readonly sizes: ReadonlyMap; + /** The points long connectors pass through, which line up before shapes do */ + readonly points: ReadonlySet; + /** The space between two shapes next to each other on a level. Half as much is left next to a point */ + readonly spacing: number; +}; + +type Gap = (a: number, b: number) => number; + +type Visit = { + readonly order: readonly number[]; + readonly seen: ReadonlySet; +}; + +const pairKey = (a: number, b: number): string => (a < b ? `${a},${b}` : `${b},${a}`); + +const positionsOf = (levels: readonly (readonly number[])[]): ReadonlyMap => + new Map(levels.flatMap((level) => level.map((node, index) => [node, index] as const))); + +/** + * Finds the links that would cross the link between two points of a long connector. Lining shapes up along them + * would bend the long connector, so they are left out. + */ +const findConflicts = ({ order, links, points }: LevelGraph): ReadonlySet => { + const position = positionsOf(order); + const isPoint = (node: number): boolean => points.has(node); + const predecessors = (node: number): readonly number[] => links.filter(({ to }) => to === node).map(({ from }) => from); + return new Set( + order.slice(1).flatMap((level, index) => { + // The links between the points of long connectors split the level before into spans. A link to a node + // between two of them must come from the span between their upper ends + const boundaries = level + .map((node, at) => ({ at, upper: isPoint(node) ? predecessors(node).find(isPoint) : undefined })) + .filter(({ at, upper }) => upper !== undefined || at === level.length - 1); + const upperEnd = ({ upper }: (typeof boundaries)[number]): number => + upper === undefined ? order[index].length : position.get(upper)!; + return boundaries.flatMap((boundary, which) => { + const low = which === 0 ? 0 : upperEnd(boundaries[which - 1]); + const high = upperEnd(boundary); + return level.slice(which === 0 ? 0 : boundaries[which - 1].at + 1, boundary.at + 1).flatMap((node) => + predecessors(node) + .filter((upper) => { + const at = position.get(upper)!; + return (at < low || high < at) && !(isPoint(upper) && isPoint(node)); + }) + .map((upper) => pairKey(upper, node)), + ); + }); + }), + ); +}; + +/** + * Joins nodes into blocks that are lined up: each node joins the block of the middle one of its neighbors on the level + * before, unless an earlier node on its level has joined a block further along. + * + * @param levels - The levels in the order they are gone through, each in the order nodes are packed + * @param neighbors - A node's neighbors on the level before + * @returns The first node of the block each node is in + */ +const alignVertically = ( + levels: readonly (readonly number[])[], + neighbors: (node: number) => readonly number[], + conflicts: ReadonlySet, +): ReadonlyMap => { + const position = positionsOf(levels); + return levels.reduce>((root, level) => { + const { joined } = level.reduce<{ readonly furthest: number; readonly joined: ReadonlyMap }>( + ({ furthest, joined: done }, node) => { + const sorted = [...neighbors(node)].sort((a, b) => position.get(a)! - position.get(b)!); + const middle = (sorted.length - 1) / 2; + const neighbor = [sorted[Math.floor(middle)], sorted[Math.ceil(middle)]].find( + (candidate) => + candidate !== undefined && furthest < position.get(candidate)! && !conflicts.has(pairKey(node, candidate)), + ); + return neighbor === undefined + ? { furthest, joined: done } + : { furthest: position.get(neighbor)!, joined: new Map([...done, [node, neighbor]]) }; + }, + { furthest: -1, joined: new Map() }, + ); + return new Map([...root, ...level.map((node) => [node, joined.has(node) ? root.get(joined.get(node)!)! : node] as const)]); + }, new Map()); +}; + +/** + * Places blocks as near the start of each level as the gaps allow, then moves each one as far along as it can go + * without moving the blocks after it, so blocks that aren't pushed along stay next to the ones they are beside. + * + * @returns Each node's centre + */ +const compact = (levels: readonly (readonly number[])[], root: ReadonlyMap, gap: Gap): ReadonlyMap => { + const blockOf = (node: number): number => root.get(node)!; + // The least distance between blocks next to each other on a level: the largest, where they are next to each other on several + const separations = [ + ...new Map( + [ + ...levels.flatMap((level) => + level + .slice(1) + .map((node, index) => ({ before: blockOf(level[index]), after: blockOf(node), distance: gap(level[index], node) })), + ), + ] + .sort((a, b) => a.distance - b.distance) + .map((separation) => [`${separation.before},${separation.after}`, separation] as const), + ).values(), + ]; + const blocks = [...new Set(levels.flat().map(blockOf))]; + const beforeOf = new Map(blocks.map((block) => [block, separations.filter(({ after }) => after === block)])); + const afterOf = new Map(blocks.map((block) => [block, separations.filter(({ before }) => before === block)])); + + // Each block after the blocks before it + const visit = (state: Visit, block: number): Visit => { + if (state.seen.has(block)) { + return state; + } + const visited = beforeOf + .get(block)! + .map(({ before }) => before) + .reduce(visit, { order: state.order, seen: new Set([...state.seen, block]) }); + return { order: [...visited.order, block], seen: visited.seen }; + }; + const sorted = blocks.reduce(visit, { order: [], seen: new Set() }).order; + + const packed = sorted.reduce>( + (positions, block) => + new Map([ + ...positions, + [block, Math.max(0, ...beforeOf.get(block)!.map(({ before, distance }) => positions.get(before)! + distance))], + ]), + new Map(), + ); + const moved = [...sorted].reverse().reduce>((positions, block) => { + const furthest = Math.min(...afterOf.get(block)!.map(({ after, distance }) => positions.get(after)! - distance)); + return Number.isFinite(furthest) ? new Map([...positions, [block, Math.max(positions.get(block)!, furthest)]]) : positions; + }, packed); + return new Map([...root].map(([node, block]) => [node, moved.get(block)!])); +}; + +/** + * Places the nodes on each level across the level. + * + * @returns Each node's centre, by node + */ +export const assignLevelCoordinates = (graph: LevelGraph): ReadonlyMap => { + const { order, links, sizes, points, spacing } = graph; + const size = (node: number): number => sizes.get(node)!; + const gap: Gap = (a, b) => (size(a) + size(b)) / 2 + (points.has(a) || points.has(b) ? spacing / 2 : spacing); + const conflicts = findConflicts(graph); + const aligning = links.filter(({ skipAlignment }) => !skipAlignment); + const above = (node: number): readonly number[] => aligning.filter(({ to }) => to === node).map(({ from }) => from); + const below = (node: number): readonly number[] => aligning.filter(({ from }) => from === node).map(({ to }) => to); + + // Lined up with the level before or after, and packed towards the start or the end of each level + const layouts = (["before", "after"] as const).flatMap((vertical) => + (["start", "end"] as const).map((horizontal) => { + const levels = (vertical === "before" ? order : [...order].reverse()).map((level) => + horizontal === "start" ? level : [...level].reverse(), + ); + const root = alignVertically(levels, vertical === "before" ? above : below, conflicts); + const centres = compact(levels, root, horizontal === "start" ? gap : (a, b) => gap(b, a)); + return { horizontal, centres: horizontal === "start" ? centres : new Map([...centres].map(([node, x]) => [node, -x])) }; + }), + ); + + // Each layout is moved to line up with the narrowest one: its start with the narrowest's start, or its end with its end + const nodes = order.flat(); + const extent = (centres: ReadonlyMap): { readonly start: number; readonly end: number } => ({ + start: Math.min(...nodes.map((node) => centres.get(node)! - size(node) / 2)), + end: Math.max(...nodes.map((node) => centres.get(node)! + size(node) / 2)), + }); + const narrowest = extent( + layouts.reduce((best, layout) => { + const width = (centres: ReadonlyMap): number => extent(centres).end - extent(centres).start; + return width(layout.centres) < width(best.centres) ? layout : best; + }).centres, + ); + const aligned = layouts.map(({ horizontal, centres }) => { + const shift = horizontal === "start" ? narrowest.start - extent(centres).start : narrowest.end - extent(centres).end; + return new Map([...centres].map(([node, x]) => [node, x + shift])); + }); + + // Between the middle two of the four + return new Map( + nodes.map((node) => { + const values = aligned.map((centres) => centres.get(node)!).sort((a, b) => a - b); + return [node, (values[1] + values[2]) / 2]; + }), + ); +}; diff --git a/src/shapes/shape-layout.spec.ts b/src/shapes/shape-layout.spec.ts index edea854a00..66cbb0a00b 100644 --- a/src/shapes/shape-layout.spec.ts +++ b/src/shapes/shape-layout.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { type LayoutItem, type LayoutPosition, layoutItems, placeInOrder } from "./shape-layout"; +import { type LayoutItem, type LayoutPosition, layoutItems } from "./shape-layout"; const EMUS_PER_PIXEL = 9525; @@ -12,20 +12,6 @@ const pixels = (positions: readonly LayoutPosition[]): readonly (readonly [numbe const centreX = ({ x }: LayoutPosition, item: LayoutItem): number => Math.round((x + item.width / 2) / EMUS_PER_PIXEL); -describe("placeInOrder", () => { - it("should keep items at their wanted positions when they are far enough apart", () => { - expect(placeInOrder([0, 20, 40], [10, 10])).to.deep.equal([0, 20, 40]); - }); - - it("should spread items that want the same place evenly around it", () => { - expect(placeInOrder([0, 0, 0], [10, 10])).to.deep.equal([-10, 0, 10]); - }); - - it("should move only the items that are too close", () => { - expect(placeInOrder([5, 0, 20], [10, 10])).to.deep.equal([-2.5, 7.5, 20]); - }); -}); - describe("layoutItems", () => { it("should place nothing when there is nothing to place", () => { expect(layoutItems({ type: "flow" }, [], [])).to.deep.equal({ positions: [] }); @@ -136,6 +122,55 @@ describe("layoutItems", () => { expect(levels).to.deep.equal([0, 0, 0, 1, 1, 1, 0]); }); + it("should place a shape a connector leaves the side of its parent for on that side of the other shapes", () => { + // A decision leads to "No" out of its right side and to "Yes" out of its bottom. "No" is given first + const decision = [box(80, 60), box(60, 30), box(60, 30)]; + const right = layoutItems({ type: "flow" }, decision, [ + { from: 0, to: 1, across: 1 }, + { from: 0, to: 2 }, + ]); + const [parent, no, yes] = pixels(right.positions); + expect(no[0]).to.be.greaterThan(yes[0]); + // "Yes" is lined up under the decision + expect(yes[0] + 30).to.equal(parent[0] + 40); + + const left = pixels( + layoutItems({ type: "flow" }, decision, [ + { from: 0, to: 1 }, + { from: 0, to: 2, across: -1 }, + ]).positions, + ); + expect(left[2][0]).to.be.lessThan(left[1][0]); + }); + + it("should prefer fewer crossings to shapes on the side their connector leaves from", () => { + // 0 leads to 2 and 3 and 1 leads to 3. Putting 3 on 0's left would cross 1's connector + const { positions } = layoutItems( + { type: "flow" }, + [box(20, 10), box(20, 10), box(20, 10), box(20, 10)], + [ + { from: 0, to: 2 }, + { from: 0, to: 3, across: -1 }, + { from: 1, to: 3 }, + ], + ); + const [, , c, d] = pixels(positions); + expect(c[0]).to.be.lessThan(d[0]); + }); + + it("should leave room between levels for the labels of connectors between them", () => { + const { positions } = layoutItems( + { type: "flow", levelSpacing: 20 }, + [box(40, 20), box(40, 20), box(40, 20)], + [ + { from: 0, to: 1, labelLength: 50 * EMUS_PER_PIXEL }, + { from: 1, to: 2, labelLength: 4 * EMUS_PER_PIXEL }, + ], + ); + // 50 pixels and 8 either side, then the level spacing, which is more than a short label needs + expect(pixels(positions).map(([, y]) => y)).to.deep.equal([0, 86, 126]); + }); + it("should place shapes without connectors side by side, and ignore repeated connectors and loops", () => { const { positions, levels } = layoutItems({ type: "flow", spacing: 10 }, [box(20, 10), box(20, 10)], [{ from: 0, to: 0 }]); expect(levels).to.deep.equal([0, 0]); @@ -256,6 +291,98 @@ describe("layoutItems", () => { }); }); + describe("lanes", () => { + const headers = { length: 20 * EMUS_PER_PIXEL, widths: [30 * EMUS_PER_PIXEL, 30 * EMUS_PER_PIXEL, 90 * EMUS_PER_PIXEL] }; + const inLane = (lane: number, width = 40): LayoutItem => ({ ...box(width, 20), lane }); + const toPixels = ({ x, y, width, height }: LayoutPosition & LayoutItem): readonly number[] => + [x, y, width, height].map((value) => Math.round(value / EMUS_PER_PIXEL)); + + it("should keep each lane's shapes in its band, with the bands side by side and headers before the first level", () => { + // b is given before a, but a's lane comes first + const result = layoutItems( + { type: "flow", spacing: 10, levelSpacing: 20, lanes: ["A", "B", "C"] }, + [inLane(0), inLane(1), inLane(0), inLane(1, 60)], + [ + { from: 0, to: 2 }, + { from: 1, to: 3 }, + ], + headers, + ); + const positions = pixels(result.positions); + // Lane A is 50 pixels wide: its shapes and half the spacing either side. Lane B fits its wider shape + expect(result.lanes!.map(({ band }) => toPixels(band))).to.deep.equal([ + [0, 0, 50, 100], + [50, 0, 70, 100], + [120, 0, 90, 100], + ]); + expect(result.lanes!.map(({ header }) => toPixels(header))).to.deep.equal([ + [0, 0, 50, 20], + [50, 0, 70, 20], + [120, 0, 90, 20], + ]); + // The first level starts after the headers and half the level spacing + expect(positions).to.deep.equal([ + [5, 30], + [65, 30], + [5, 70], + [55, 70], + ]); + }); + + it("should order each level by lane, and put shapes without a lane in the first", () => { + const { positions } = layoutItems({ type: "flow", spacing: 10, lanes: ["A", "B"] }, [inLane(1), box(40, 20), inLane(0)], [], { + length: 0, + widths: [0, 0], + }); + const [inB, noLane, inA] = pixels(positions); + expect(inA[0]).to.be.lessThan(inB[0]); + expect(noLane[0]).to.be.lessThan(inB[0]); + }); + + it("should run the lanes across the page when the flow runs across it", () => { + const result = layoutItems( + { type: "flow", direction: "right", spacing: 10, levelSpacing: 20, lanes: ["A", "B"] }, + [inLane(0), inLane(1)], + [{ from: 0, to: 1 }], + { length: 30 * EMUS_PER_PIXEL, widths: [0, 0] }, + ); + expect(result.lanes!.map(({ band }) => toPixels(band))).to.deep.equal([ + [0, 0, 150, 30], + [0, 30, 150, 30], + ]); + expect(toPixels(result.lanes![1].header)).to.deep.equal([0, 30, 30, 30]); + }); + + it("should make lanes without headers as wide as their shapes need", () => { + const { lanes } = layoutItems({ type: "flow", spacing: 10, levelSpacing: 20, lanes: ["A"] }, [inLane(0)], []); + expect(toPixels(lanes![0].band)).to.deep.equal([0, 0, 50, 40]); + expect(toPixels(lanes![0].header)).to.deep.equal([0, 0, 50, 0]); + }); + + it("should put the headers at the start of a flow that runs up", () => { + const result = layoutItems({ type: "flow", direction: "up", lanes: ["A"] }, [inLane(0)], [], { + length: 20 * EMUS_PER_PIXEL, + widths: [0], + }); + const [band] = result.lanes!; + expect(band.header.y + band.header.height).to.equal(band.band.y + band.band.height); + }); + }); + + describe("labels in trees", () => { + it("should leave room between levels for the labels of connectors between them", () => { + const { positions } = layoutItems( + { type: "tree", levelSpacing: 20, direction: "right" }, + [box(40, 20), box(40, 20)], + [{ from: 0, to: 1, labelLength: 30 * EMUS_PER_PIXEL }], + ); + expect(pixels(positions)).to.deep.equal([ + [0, 0], + [86, 0], + ]); + }); + }); + describe("grid", () => { it("should centre each shape in its cell, in rows of the given number of columns", () => { const { positions, levels } = layoutItems( diff --git a/src/shapes/shape-layout.ts b/src/shapes/shape-layout.ts index 49feb0c387..f966e85313 100644 --- a/src/shapes/shape-layout.ts +++ b/src/shapes/shape-layout.ts @@ -5,6 +5,9 @@ * * @module */ +// cspell:ignore Brandes Köpf +import type { ShapeFill, ShapeLine } from "./preset-shape"; +import { assignLevelCoordinates } from "./shape-layout-coordinates"; /** * The way a flow or tree runs, from its first shapes to its last. @@ -13,6 +16,22 @@ */ export type ShapeLayoutDirection = "down" | "right" | "up" | "left"; +/** + * A lane of a flow: a band, with a header, that the shapes given its name go in. + * + * @publicApi + */ +export type ShapeLane = { + /** The lane's name, written in its header. A shape goes in the lane when its `lane` is this name */ + readonly name: string; + /** The lane's background. Default is none */ + readonly fill?: ShapeFill; + /** The background of the lane's header. Default is light grey */ + readonly headerFill?: ShapeFill; + /** The line around the lane and its header. Default is a thin grey line */ + readonly line?: ShapeLine; +}; + /** * Places shapes in levels along their connectors, as in a flowchart: each shape goes on a level after the shapes * that connect to it, and the shapes on each level are ordered so connectors cross as little as they can. @@ -27,6 +46,12 @@ export type ShapeFlowLayout = { readonly spacing?: number; /** Space between one level and the next, in pixels. Default is 50 */ readonly levelSpacing?: number; + /** + * Bands the flow runs along, such as the people or teams that do each step of a process (swimlanes). Each shape + * with a `lane` goes in the band of that name, and shapes without one go in the first. The bands are side by side, + * across the direction the flow runs in, each with a header at the start of the flow + */ + readonly lanes?: readonly (string | ShapeLane)[]; }; /** @@ -60,7 +85,8 @@ export type ShapeGridLayout = { /** * How a {@link ShapeGroupRun} or {@link ShapeCanvasRun} places the shapes, pictures and groups that have no `offset`. - * Shapes with an `offset` stay where it puts them. Connectors are routed after the shapes are placed. + * Shapes with an `offset` stay where it puts them: those that connect to the shapes the layout places take part in the + * layout, which is placed around them. Connectors are routed after the shapes are placed. * * @publicApi */ @@ -72,14 +98,29 @@ export type ShapeLayout = ShapeFlowLayout | ShapeTreeLayout | ShapeGridLayout; export type LayoutItem = { readonly width: number; readonly height: number; + /** The lane of a flow it goes in, by index */ + readonly lane?: number; }; +/** + * A box: where it is and how big it is. + */ +export type LayoutBox = LayoutPosition & Pick; + /** * A connector between two items, by their indexes. */ export type LayoutEdge = { readonly from: number; readonly to: number; + /** + * Which way across the levels of a flow the connector leaves `from`, when it is given a side: `-1` towards the start + * of the level (left, or the top when levels run across the page) and `1` towards the end. The item it leads to is + * placed that way from the others `from` leads to + */ + readonly across?: -1 | 1; + /** How long the connector's label is along the direction the levels run in, in EMUs. The levels leave room for it */ + readonly labelLength?: number; }; /** @@ -98,13 +139,27 @@ export type LayoutResult = { readonly positions: readonly LayoutPosition[]; /** The level of a flow or tree each item is on, counted from the first. Missing for grids */ readonly levels?: readonly number[]; + /** The band and header of each lane of a flow */ + readonly lanes?: readonly { readonly band: LayoutBox; readonly header: LayoutBox }[]; +}; + +/** + * How big the lanes of a flow need to be for their headers, in EMUs. + */ +export type LaneHeaders = { + /** How long the headers are along the direction the flow runs in */ + readonly length: number; + /** How wide each lane has to be, across the direction the flow runs in, for its header's text */ + readonly widths: readonly number[]; }; const EMUS_PER_PIXEL = 9525; -// Iterations of the passes that order and position each level of a flow +// Space either side of a label between levels, in EMUs +const LABEL_CLEARANCE = 8 * EMUS_PER_PIXEL; +// Iterations of the passes that order each level of a flow const ORDERING_PASSES = 24; -// An odd number, so the last pass lines shapes up under the shapes before them -const POSITIONING_PASSES = 9; +// How far a connector that leaves the side of a shape moves the shape it leads to, in places on a level +const SIDE_WEIGHT = 0.5; const checkSpacing = (value: number, option: string): number => { if (!(value >= 0)) { @@ -126,6 +181,8 @@ type Turned = { positions: readonly { readonly across: number; readonly along: number }[], items: readonly LayoutItem[], ) => readonly LayoutPosition[]; + /** The item with the given lengths across and along the levels */ + readonly item: (across: number, along: number) => LayoutItem; }; const normalize = (positions: readonly LayoutPosition[]): readonly LayoutPosition[] => { @@ -141,6 +198,8 @@ const turn = (direction: ShapeLayoutDirection = "down"): Turned => { return { across: (item) => (vertical ? item.width : item.height), along: (item) => (vertical ? item.height : item.width), + item: (acrossLength, alongLength) => + vertical ? { width: acrossLength, height: alongLength } : { width: alongLength, height: acrossLength }, place: (positions, items) => normalize( positions.map(({ across, along }, index) => { @@ -154,49 +213,41 @@ const turn = (direction: ShapeLayoutDirection = "down"): Turned => { /** * The start of each level along the direction the levels run in, from the length of the longest item on each level. + * + * @param spacing - The space after each level, or the same space after every level */ -const levelStarts = (thickness: readonly number[], levelSpacing: number): readonly number[] => +const levelStarts = (thickness: readonly number[], spacing: number | readonly number[]): readonly number[] => thickness.reduce( - (starts, _, index) => (index === 0 ? [0] : [...starts, starts[index - 1] + thickness[index - 1] + levelSpacing]), + (starts, _, index) => + index === 0 + ? [0] + : [...starts, starts[index - 1] + thickness[index - 1] + (typeof spacing === "number" ? spacing : spacing[index - 1])], [], ); +/** + * The space after each level: the level spacing, or more where a connector to the next level has a label that needs it. + */ +const spacingAfterLevels = ( + levelCount: number, + levelSpacing: number, + levelOf: (item: number) => number, + edges: readonly LayoutEdge[], +): readonly number[] => + range(levelCount).map((level) => + Math.max( + levelSpacing, + ...edges + .filter(({ from, to, labelLength }) => labelLength !== undefined && levelOf(from) === level && levelOf(to) === level + 1) + .map(({ labelLength }) => labelLength! + 2 * LABEL_CLEARANCE), + ), + ); + const range = (length: number, from = 0): readonly number[] => Array.from({ length: Math.max(0, length) }, (_, index) => from + index); const mean = (values: readonly number[]): number | undefined => values.length > 0 ? values.reduce((sum, value) => sum + value, 0) / values.length : undefined; -type Block = { - readonly value: number; - readonly count: number; -}; - -// Adds a block to the end of the list, merging it with the blocks before it while they are out of order -const addBlock = (blocks: readonly Block[], block: Block): readonly Block[] => { - const last = blocks[blocks.length - 1]; - if (last === undefined || last.value <= block.value) { - return [...blocks, block]; - } - const count = last.count + block.count; - return addBlock(blocks.slice(0, -1), { value: (last.value * last.count + block.value * block.count) / count, count }); -}; - -/** - * Least-squares positions for a row of items kept in order: each as near its wanted position as it can be, without - * being nearer the one before it than `gaps` allows. This is isotonic regression, solved by pooling adjacent violators. - * - * @param wanted - Each item's wanted centre - * @param gaps - The least distance from each item's centre to the next one's - */ -export const placeInOrder = (wanted: readonly number[], gaps: readonly number[]): readonly number[] => { - // With each centre less the gaps before it, the positions only have to be in order - const offsets = wanted.map((_, index) => gaps.slice(0, index).reduce((total, gap) => total + gap, 0)); - return wanted - .reduce((blocks, target, index) => addBlock(blocks, { value: target - offsets[index], count: 1 }), []) - .flatMap(({ value, count }) => range(count).map(() => value)) - .map((value, index) => value + offsets[index]); -}; - type Search = { /** Shapes the search has finished with */ readonly done: ReadonlySet; @@ -255,6 +306,8 @@ type FlowNode = { /** Length across the level. Points that long connectors pass through have none */ readonly size: number; readonly isPoint: boolean; + /** The lane it is in. A point long connectors pass through is in the lane the connector comes from */ + readonly lane: number; }; const countCrossings = (upper: readonly number[], lower: readonly number[], edges: readonly LayoutEdge[]): number => { @@ -266,150 +319,245 @@ const countCrossings = (upper: readonly number[], lower: readonly number[], edge return between.reduce((total, [a, b], index) => total + between.slice(index + 1).filter(([c, d]) => (a - c) * (b - d) < 0).length, 0); }; +/** + * How many shapes are on the wrong side of their siblings: a shape that a connector leaves the side of its parent + * for, placed on the other side of a shape the parent leads to without one. + */ +const countMisplaced = (upper: readonly number[], lower: readonly number[], edges: readonly LayoutEdge[]): number => { + const lowerIndex = new Map(lower.map((node, index) => [node, index])); + return upper.reduce((total, parent) => { + const children = edges.filter(({ from, to }) => from === parent && lowerIndex.has(to)); + return ( + total + + children.reduce( + (count, child) => + count + + children.filter( + (other) => (child.across ?? 0) > (other.across ?? 0) && lowerIndex.get(child.to)! < lowerIndex.get(other.to)!, + ).length, + 0, + ) + ); + }, 0); +}; + type Ordering = { readonly order: readonly (readonly number[])[]; readonly best: readonly (readonly number[])[]; readonly crossings: number; + readonly misplaced: number; }; /** * Orders the shapes on each level to reduce crossings: passes go down and up in turn, sorting each level by the - * average position of the shapes it connects to on the level just done (the barycenter method). The order with - * the fewest crossings is kept. + * average position of the shapes it connects to on the level just done (the barycenter method). A connector that + * leaves the side of a shape moves the shape it leads to that way. The order with the fewest crossings, then the + * fewest shapes on the wrong side of their siblings, is kept. The shapes in each lane stay together. */ -const orderLevels = (start: readonly (readonly number[])[], links: readonly LayoutEdge[]): readonly (readonly number[])[] => { +const orderLevels = ( + start: readonly (readonly number[])[], + links: readonly LayoutEdge[], + laneOf: (node: number) => number, +): readonly (readonly number[])[] => { const levelCount = start.length; - const totalCrossings = (order: readonly (readonly number[])[]): number => - order.slice(1).reduce((total, lower, index) => total + countCrossings(order[index], lower, links), 0); + const score = (order: readonly (readonly number[])[]): Pick => + order.slice(1).reduce( + (total, lower, index) => ({ + crossings: total.crossings + countCrossings(order[index], lower, links), + misplaced: total.misplaced + countMisplaced(order[index], lower, links), + }), + { crossings: 0, misplaced: 0 }, + ); const sortLevel = (order: readonly (readonly number[])[], level: number, down: boolean): readonly (readonly number[])[] => { const fixed = new Map(order[down ? level - 1 : level + 1].map((node, index) => [node, index])); const weights = order[level].map((node, index) => { const neighbors = links .filter((link) => (down ? link.to === node && fixed.has(link.from) : link.from === node && fixed.has(link.to))) - .map((link) => fixed.get(down ? link.from : link.to)!); + .map((link) => fixed.get(down ? link.from : link.to)! + (down ? 1 : -1) * (link.across ?? 0) * SIDE_WEIGHT); return { node, weight: mean(neighbors) ?? index }; }); - const sorted = [...weights].sort((a, b) => a.weight - b.weight).map(({ node }) => node); + // Each lane's shapes stay together, in the order of the lanes + const sorted = [...weights].sort((a, b) => laneOf(a.node) - laneOf(b.node) || a.weight - b.weight).map(({ node }) => node); return order.map((nodes, index) => (index === level ? sorted : nodes)); }; return range(ORDERING_PASSES).reduce( (ordering, pass) => { - if (ordering.crossings === 0) { + if (ordering.crossings === 0 && ordering.misplaced === 0) { return ordering; } const down = pass % 2 === 0; const levels = down ? range(levelCount - 1, 1) : range(levelCount - 1).map((index) => levelCount - 2 - index); const order = levels.reduce((current, level) => sortLevel(current, level, down), ordering.order); - const crossings = totalCrossings(order); - return crossings < ordering.crossings ? { order, best: order, crossings } : { ...ordering, order }; + const { crossings, misplaced } = score(order); + const better = crossings < ordering.crossings || (crossings === ordering.crossings && misplaced < ordering.misplaced); + return better ? { order, best: order, crossings, misplaced } : { ...ordering, order }; }, - { order: start, best: start, crossings: totalCrossings(start) }, + { order: start, best: start, ...score(start) }, ).best; }; /** - * Places the shapes on each level across it: packed together, then moved towards the shapes they connect to. - * Passes go down and up in turn, each shape moving towards the shapes before it, or after it on the way up, - * without coming closer to its neighbors than the gaps allow. - * - * @returns Each node's centre across its level + * Lays out a flow in levels (the Sugiyama method): leaves out connectors that lead back, puts the shapes on levels, + * adds points for connectors that skip levels, orders each level to reduce crossings, then lines each shape up with + * the shapes it connects to (the Brandes–Köpf method). Connectors that lead back are routed around the shapes + * afterwards, so they don't take up room in the layout. */ -const positionLevels = ( +/** + * Places the shapes on each level across it: lined up with the shapes they connect to, and in lanes when the flow + * has them. Each lane is as wide as its shapes, or its header, need, and the lanes are side by side. + * + * @returns Each node's centre across its level, and where each lane starts and how wide it is + */ +const placeAcross = ( order: readonly (readonly number[])[], + nodes: readonly FlowNode[], links: readonly LayoutEdge[], - gap: (a: number, b: number) => number, - nodeCount: number, -): readonly number[] => { - const gapsOf = (level: readonly number[]): readonly number[] => level.slice(1).map((node, index) => gap(level[index], node)); - const setLevel = (centres: readonly number[], level: readonly number[], placed: readonly number[]): readonly number[] => { - const positions = new Map(level.map((node, index) => [node, placed[index]])); - return centres.map((centre, node) => positions.get(node) ?? centre); + spacing: number, + lanes?: { readonly count: number; readonly widths: readonly number[] }, +): { readonly centres: ReadonlyMap; readonly lanes: readonly { readonly start: number; readonly width: number }[] } => { + const place = (lane?: number): ReadonlyMap => { + const inLane = (node: number): boolean => lane === undefined || nodes[node].lane === lane; + return assignLevelCoordinates({ + order: order.map((level) => level.filter(inLane)), + // A connector that leaves the side of a shape doesn't line the shape it leads to up with it + links: links + .filter(({ from, to }) => inLane(from) && inLane(to)) + .map(({ from, to, across: side }) => ({ from, to, skipAlignment: side !== undefined })), + sizes: new Map(nodes.map(({ size }, node) => [node, size])), + points: new Set(range(nodes.length).filter((node) => nodes[node].isPoint)), + spacing, + }); }; - const packed = order.reduce( - (centres, level) => - setLevel( - centres, - level, - placeInOrder( - level.map(() => 0), - gapsOf(level), - ), - ), - new Array(nodeCount).fill(0), + if (!lanes) { + return { centres: place(), lanes: [] }; + } + const placed = range(lanes.count).map((lane) => { + const centres = place(lane); + const edges = [...centres].flatMap(([node, centre]) => [centre - nodes[node].size / 2, centre + nodes[node].size / 2]); + // A lane without shapes has no width of its own + const low = edges.length > 0 ? Math.min(...edges) : 0; + const high = edges.length > 0 ? Math.max(...edges) : 0; + // Half the spacing either side of the lane's shapes, and room for its header + const width = Math.max(high - low + spacing, lanes.widths[lane] ?? 0); + return { centres, low, high, width }; + }); + const starts = levelStarts( + placed.map(({ width }) => width), + 0, ); - return range(POSITIONING_PASSES).reduce((centres, pass) => { - const down = pass % 2 === 0; - return (down ? order : [...order].reverse()).reduce((current, level) => { - const wanted = level.map((node) => { - const before = links.filter((link) => link.to === node).map((link) => current[link.from]); - const after = links.filter((link) => link.from === node).map((link) => current[link.to]); - return (down ? (mean(before) ?? mean(after)) : (mean(after) ?? mean(before))) ?? current[node]; - }); - return setLevel(current, level, placeInOrder(wanted, gapsOf(level))); - }, centres); - }, packed); + return { + centres: new Map( + placed.flatMap(({ centres, low, high, width }, lane) => + [...centres].map(([node, centre]) => [node, starts[lane] + (width - (high - low)) / 2 + centre - low] as const), + ), + ), + lanes: placed.map(({ width }, lane) => ({ start: starts[lane], width })), + }; }; /** * Lays out a flow in levels (the Sugiyama method): leaves out connectors that lead back, puts the shapes on levels, - * adds points for connectors that skip levels, orders each level to reduce crossings, then places each shape as near - * the middle of the shapes it connects to as the spacing allows. Connectors that lead back are routed around the - * shapes afterwards, so they don't take up room in the layout. + * adds points for connectors that skip levels, orders each level to reduce crossings, then lines each shape up with + * the shapes it connects to (the Brandes–Köpf method). Connectors that lead back are routed around the shapes + * afterwards, so they don't take up room in the layout. + * + * With lanes, the shapes in each lane stay together on each level, and the lanes' headers come before the first level. */ -const layoutFlow = (layout: ShapeFlowLayout, items: readonly LayoutItem[], allEdges: readonly LayoutEdge[]): LayoutResult => { +const layoutFlow = ( + layout: ShapeFlowLayout, + items: readonly LayoutItem[], + allEdges: readonly LayoutEdge[], + headers: LaneHeaders, +): LayoutResult => { const spacing = checkSpacing(layout.spacing ?? 40, "spacing"); const levelSpacing = checkSpacing(layout.levelSpacing ?? 50, "levelSpacing"); - const { across, along, place } = turn(layout.direction); + const { across, along, place, item: turnedItem } = turn(layout.direction); const backEdges = findBackEdges(items.length, allEdges); const edges = allEdges.filter((_, index) => !backEdges.has(index)); const levels = assignLevels(items.length, edges); const lowest = Math.min(...levels); + const laneCount = layout.lanes?.length ?? 0; - // Connectors that skip levels pass through a point on each level they skip + // Connectors that skip levels pass through a point on each level they skip. Only the first link of a connector + // that leaves the side of a shape goes that way const { nodes, links } = edges.reduce<{ readonly nodes: readonly FlowNode[]; readonly links: readonly LayoutEdge[] }>( - (graph, { from, to }) => { + (graph, { from, to, across: side }) => { const skipped = range(graph.nodes[to].level - graph.nodes[from].level - 1, graph.nodes[from].level + 1).map((level) => ({ level, size: 0, isPoint: true, + lane: graph.nodes[from].lane, })); const path = [from, ...skipped.map((_, index) => graph.nodes.length + index), to]; return { nodes: [...graph.nodes, ...skipped], - links: [...graph.links, ...path.slice(1).map((node, index) => ({ from: path[index], to: node }))], + links: [ + ...graph.links, + ...path.slice(1).map((node, index) => ({ from: path[index], to: node, across: index === 0 ? side : undefined })), + ], }; }, - { nodes: items.map((item, index) => ({ level: levels[index] - lowest, size: across(item), isPoint: false })), links: [] }, + { + nodes: items.map((item, index) => ({ + level: levels[index] - lowest, + size: across(item), + isPoint: false, + lane: item.lane ?? 0, + })), + links: [], + }, ); // Levels start in the order the shapes are given, with the points connectors pass through after them const levelCount = Math.max(...nodes.map(({ level }) => level)) + 1; const order = orderLevels( - range(levelCount).map((level) => range(nodes.length).filter((node) => nodes[node].level === level)), + range(levelCount).map((level) => + range(nodes.length) + .filter((node) => nodes[node].level === level) + .sort((a, b) => nodes[a].lane - nodes[b].lane), + ), links, + (node) => nodes[node].lane, ); - const centres = positionLevels( + const { centres, lanes } = placeAcross( order, + nodes, links, - (a, b) => (nodes[a].size + nodes[b].size) / 2 + (nodes[a].isPoint || nodes[b].isPoint ? spacing / 2 : spacing), - nodes.length, + spacing, + laneCount > 0 ? { count: laneCount, widths: headers.widths } : undefined, ); - // Positions along: each level is as thick as its longest shape, and shapes are centred on it + // Positions along: each level is as thick as its longest shape, and shapes are centred on it. Lanes' headers come + // first, with half the level spacing before the first level and after the last const thickness = range(levelCount).map((level) => Math.max(0, ...items.map((item, index) => (nodes[index].level === level ? along(item) : 0))), ); - const starts = levelStarts(thickness, levelSpacing); - return { - positions: place( - items.map((item, index) => ({ - across: centres[index] - across(item) / 2, + const before = laneCount > 0 ? headers.length + levelSpacing / 2 : 0; + const starts = levelStarts( + thickness, + spacingAfterLevels(levelCount, levelSpacing, (item) => nodes[item].level, edges), + ).map((start) => start + before); + const total = starts[levelCount - 1] + thickness[levelCount - 1] + levelSpacing / 2; + const bands = lanes.flatMap(({ start, width }) => [ + { across: start, along: 0, item: turnedItem(width, total) }, + { across: start, along: 0, item: turnedItem(width, headers.length) }, + ]); + const placed = place( + [ + ...items.map((item, index) => ({ + across: centres.get(index)! - across(item) / 2, along: starts[nodes[index].level] + (thickness[nodes[index].level] - along(item)) / 2, })), - items, - ), + ...bands.map(({ across: bandAcross, along: bandAlong }) => ({ across: bandAcross, along: bandAlong })), + ], + [...items, ...bands.map(({ item }) => item)], + ); + const boxes = bands.map(({ item }, index) => ({ ...placed[items.length + index], width: item.width, height: item.height })); + return { + positions: placed.slice(0, items.length), levels: items.map((_, index) => nodes[index].level), + lanes: laneCount > 0 ? lanes.map((_, lane) => ({ band: boxes[2 * lane], header: boxes[2 * lane + 1] })) : undefined, }; }; @@ -511,7 +659,10 @@ const layoutTree = (layout: ShapeTreeLayout, items: readonly LayoutItem[], edges const thickness = range(Math.max(...depths) + 1).map((level) => Math.max(0, ...items.map((item, index) => (depths[index] === level ? along(item) : 0))), ); - const starts = levelStarts(thickness, levelSpacing); + const starts = levelStarts( + thickness, + spacingAfterLevels(thickness.length, levelSpacing, (item) => depths[item], edges), + ); return { positions: place( items.map((item, index) => ({ across: centres.get(index)! - across(item) / 2, along: starts[depths[index]] })), @@ -552,10 +703,17 @@ const layoutGrid = (layout: ShapeGridLayout, items: readonly LayoutItem[]): Layo * * @param items - The boxes to place, in EMUs * @param edges - The connectors between them, which flow and tree layouts follow - * @returns The top-left corner of each item's box, in EMUs, and the level each is on in a flow or tree + * @param headers - How big the headers of a flow's lanes are + * @returns The top-left corner of each item's box, in EMUs, the level each is on in a flow or tree, and the boxes of a + * flow's lanes * @throws If a spacing is negative, or a grid's number of columns isn't a whole number of 1 or more */ -export const layoutItems = (layout: ShapeLayout, items: readonly LayoutItem[], edges: readonly LayoutEdge[]): LayoutResult => { +export const layoutItems = ( + layout: ShapeLayout, + items: readonly LayoutItem[], + edges: readonly LayoutEdge[], + headers: LaneHeaders = { length: 0, widths: [] }, +): LayoutResult => { if (items.length === 0) { return { positions: [] }; } @@ -564,7 +722,7 @@ export const layoutItems = (layout: ShapeLayout, items: readonly LayoutItem[], e ); switch (layout.type) { case "flow": - return layoutFlow(layout, items, links); + return layoutFlow(layout, items, links, headers); case "tree": return layoutTree(layout, items, links); default: diff --git a/src/shapes/shape-run-data.ts b/src/shapes/shape-run-data.ts index 5b4676d3bb..03388b837e 100644 --- a/src/shapes/shape-run-data.ts +++ b/src/shapes/shape-run-data.ts @@ -3,7 +3,15 @@ * * @module */ -import type { DocPropertiesOptions, DrawingLinkOptions, EffectExtentAttributes, IMediaTransformation, Paragraph } from "docx"; +import { + type DocPropertiesOptions, + type DrawingLinkOptions, + type EffectExtentAttributes, + type IFloating, + type IMediaTransformation, + type Paragraph, + docPropertiesUniqueNumericId, +} from "docx"; import { type PresetShapeCoreOptions, @@ -17,6 +25,7 @@ import { getShapeLineOverhang, } from "./preset-shape"; import { type ShapeTransformation, createTextParagraphs } from "./shape-text-size"; +import type { TextStyles } from "./shape-text-styles"; /** * Options every shape has, whatever its type. @@ -74,16 +83,38 @@ export type WithPresetShape = /** * Maps shape options to the data used to write a `wps:wsp` element. + * + * @param styles - The document's styles, which `text` is written to suit */ -export const createPresetShapeData = (options: WithPresetShape): PresetShapeCoreOptions => ({ +export const createPresetShapeData = (options: WithPresetShape, styles?: TextStyles): PresetShapeCoreOptions => ({ geometry: options.type === "custom" ? { type: "custom", path: options.path } : { type: options.type, adjustments: options.adjustments }, fill: options.fill, line: options.line, effects: options.effects, - children: options.text === undefined ? options.children : [...createTextParagraphs(options.text), ...(options.children ?? [])], + children: options.text === undefined ? options.children : [...createTextParagraphs(options.text, styles), ...(options.children ?? [])], textOptions: options.textOptions, }); +/** + * The options of a drawing that don't depend on its layout, with the drawing's id. The id is given now, so a drawing + * that is laid out again when it is written keeps it. + */ +export const createDrawingProperties = ({ + floating, + altText, + link, + decorative, +}: DrawingLinkOptions & { readonly floating?: IFloating; readonly altText?: DocPropertiesOptions }): DrawingLinkOptions & { + readonly floating?: IFloating; + readonly docProperties: DocPropertiesOptions; +} => ({ + floating, + // A drawing without alt text has an empty name, description and title, as it does without an id + docProperties: { ...(altText ?? { name: "", description: "", title: "" }), id: altText?.id ?? `${docPropertiesUniqueNumericId()}` }, + link, + decorative, +}); + /** * An effect extent reaching the same distance past every side of a drawing. */ diff --git a/src/shapes/shape-run.spec.ts b/src/shapes/shape-run.spec.ts index 88606ec40d..dd8efc28d7 100644 --- a/src/shapes/shape-run.spec.ts +++ b/src/shapes/shape-run.spec.ts @@ -1,8 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Formatter } from "@export/formatter"; +import { File } from "@file/file"; import * as convenienceFunctions from "@util/convenience-functions"; -import { HorizontalPositionAlign, type IContext, Paragraph, TextWrappingType, VerticalPositionRelativeFrom } from "docx"; +import { + HorizontalPositionAlign, + type IContext, + type IXmlableObject, + Paragraph, + TextWrappingType, + VerticalPositionRelativeFrom, +} from "docx"; import { ShapeRun } from "./shape-run"; @@ -29,7 +37,7 @@ describe("ShapeRun", () => { { _attr: { distT: 0, distB: 0, distL: 0, distR: 0 } }, { "wp:extent": { _attr: { cx: 1905000, cy: 38100 } } }, { "wp:effectExtent": { _attr: { t: 0, r: 0, b: 0, l: 0 } } }, - { "wp:docPr": { _attr: { id: 1, name: "", descr: "", title: "" } } }, + { "wp:docPr": { _attr: { id: "1", name: "", descr: "", title: "" } } }, { "wp:cNvGraphicFramePr": [ { @@ -139,7 +147,7 @@ describe("ShapeRun", () => { "wp:effectExtent": { _attr: { t: 418795, r: 116865, b: 418795, l: 116865 } }, }); expect(anchor.find((child: object) => "wp:docPr" in child)).to.deep.equal({ - "wp:docPr": { _attr: { id: 1, name: "Callout", descr: "A speech bubble", title: "Callout" } }, + "wp:docPr": { _attr: { id: "1", name: "Callout", descr: "A speech bubble", title: "Callout" } }, }); const graphic = anchor.find((child: object) => "a:graphic" in child)["a:graphic"]; @@ -194,6 +202,48 @@ describe("ShapeRun", () => { expect(Object.keys(shape[1]["wps:spPr"][1])).to.deep.equal(["a:custGeom"]); }); + describe("in the document's styles", () => { + const contextOf = (document: object): IContext => + ({ file: new File({ styles: { default: { document } }, sections: [] }), stack: [] }) as unknown as IContext; + const inlineOf = (tree: IXmlableObject): readonly IXmlableObject[] => tree["w:r"][0]["w:drawing"][0]["wp:inline"]; + const extentOf = (tree: IXmlableObject): IXmlableObject => inlineOf(tree).find((child) => "wp:extent" in child)!["wp:extent"]._attr; + + it("should size a shape to fit its text when it is written, keeping its drawing id", () => { + const shape = new ShapeRun({ type: "rectangle", text: "Hello world", transformation: { width: "fitText", height: "fitText" } }); + const plain = new Formatter().format(shape); + const context = contextOf({ run: { font: "Calibri", size: 32 } }); + const styled = new Formatter().format(shape, context); + + expect(extentOf(styled).cx).to.be.greaterThan(extentOf(plain).cx); + expect(extentOf(styled).cy).to.be.greaterThan(extentOf(plain).cy); + const docPr = (tree: IXmlableObject): IXmlableObject => inlineOf(tree).find((child) => "wp:docPr" in child)!; + expect(docPr(styled)).to.deep.equal(docPr(plain)); + // Writing the document again writes the same drawing + expect(new Formatter().format(shape, context)).to.deep.equal(styled); + }); + + it("should write text without the space the document puts after paragraphs", () => { + const tree = new Formatter().format( + new ShapeRun({ type: "rectangle", text: "Hi", transformation: { width: 50, height: 50 } }), + contextOf({ paragraph: { spacing: { after: 160 } } }), + ); + const shape = inlineOf(tree).find((child) => "a:graphic" in child)!["a:graphic"][1]["a:graphicData"][1]["wps:wsp"]; + const paragraph = shape[2]["wps:txbx"][0]["w:txbxContent"][0]["w:p"]; + expect(paragraph[0]["w:pPr"][0]).to.deep.equal({ "w:spacing": { _attr: { "w:before": 0, "w:after": 0 } } }); + }); + + it("should write the shape laid out when it was created when the document's styles format its text the same way", () => { + const shape = new ShapeRun({ type: "rectangle", text: "Hello", transformation: { width: "fitText", height: 20 } }); + // The library's default styles only format headings and other paragraphs with styles of their own + expect(new Formatter().format(shape, contextOf({}))).to.deep.equal(new Formatter().format(shape)); + }); + + it("should write shapes whose size doesn't depend on text as they are", () => { + const shape = new ShapeRun({ type: "rectangle", transformation: { width: 50, height: 50 } }); + expect(new Formatter().format(shape, contextOf({ run: { size: 40 } }))).to.deep.equal(new Formatter().format(shape)); + }); + }); + it("should link the shape, and mark it as decorative", () => { const addRelationship = vi.fn(); const tree = new Formatter().format( diff --git a/src/shapes/shape-run.ts b/src/shapes/shape-run.ts index 6499ebf52b..882f3c4819 100644 --- a/src/shapes/shape-run.ts +++ b/src/shapes/shape-run.ts @@ -8,11 +8,20 @@ * * @module */ -import { Drawing, type IFloating, Run, createTransformation } from "docx"; +import { Drawing, Run, createTransformation } from "docx"; import { SHAPE_URI } from "./drawing/shape-drawing-child"; +import { createStyledDrawing } from "./drawing/styled-drawing"; import { createPresetShape } from "./preset-shape/preset-shape"; -import { type ShapeBaseOptions, type WithPresetShape, createPresetShapeData, getShapeEffectExtent } from "./shape-run-data"; +import { shapeStyledParagraphs } from "./shape-drawing"; +import { type ShapeFloating, relativeSizeBase, toImageFloating, withRelativePlacement } from "./shape-floating"; +import { + type ShapeBaseOptions, + type WithPresetShape, + createDrawingProperties, + createPresetShapeData, + getShapeEffectExtent, +} from "./shape-run-data"; import { resolveShapeSize } from "./shape-text-size"; export type { @@ -51,6 +60,14 @@ export type { SolidShapeFill, } from "./preset-shape"; export type { ShapeSize, ShapeTransformation } from "./shape-text-size"; +export type { + ShapeFloating, + ShapeHeightRelativeTo, + ShapeHorizontalPosition, + ShapePercentage, + ShapeVerticalPosition, + ShapeWidthRelativeTo, +} from "./shape-floating"; /** * Options for creating a shape. @@ -63,8 +80,17 @@ export type { ShapeSize, ShapeTransformation } from "./shape-text-size"; */ export type IShapeOptions = WithPresetShape< ShapeBaseOptions & { - /** Floats the shape on the page instead of placing it inline with text */ - readonly floating?: IFloating; + /** + * Floats the shape on the page instead of placing it inline with text. A floating shape's size and offsets can be + * percentages of the page, its margins or the space between them + */ + readonly floating?: ShapeFloating; + /** + * The name of a text flow the shape is in: text that flows from one shape to the next, such as an article that + * continues on another page. The first shape of the flow in the document holds the text, from its `text` and + * `children`, and the text that doesn't fit flows on into the next shape of the flow, and so on + */ + readonly textFlow?: string; } >; @@ -101,25 +127,33 @@ export class ShapeRun extends Run { public constructor(options: IShapeOptions) { super({}); - const transformation = resolveShapeSize(options); - // A shape on its own is positioned by the run (or `floating`), not by an offset - const drawingTransformation = createTransformation({ ...transformation, offset: undefined }); + const floating = options.floating && toImageFloating(options.floating); + const drawingOptions = createDrawingProperties({ ...options, floating }); this.root.push( - new Drawing( - { - type: "graphic", - uri: SHAPE_URI, - transformation: drawingTransformation, - content: createPresetShape({ ...createPresetShapeData(options), transformation: drawingTransformation }), - }, - { - floating: options.floating, - docProperties: options.altText, - link: options.link, - decorative: options.decorative, - effectExtent: getShapeEffectExtent({ ...options, transformation }), - }, - ), + // A shape that fits its text is sized in the document's styles when it is written + createStyledDrawing((styles) => { + const transformation = resolveShapeSize(options, styles, options.floating && relativeSizeBase(options.floating)); + // A shape on its own is positioned by the run (or `floating`), not by an offset + const drawingTransformation = createTransformation({ ...transformation, offset: undefined }); + // A percentage size or offset is written as the size or offset on the library's default page, then as a percentage + return withRelativePlacement( + new Drawing( + { + type: "graphic", + uri: SHAPE_URI, + transformation: drawingTransformation, + content: createPresetShape({ + ...createPresetShapeData(options, styles), + textFlow: options.textFlow, + transformation: drawingTransformation, + }), + }, + { ...drawingOptions, effectExtent: getShapeEffectExtent({ ...options, transformation }) }, + ), + options.floating, + options.transformation, + ); + }, shapeStyledParagraphs(options)), ); } } diff --git a/src/shapes/shape-text-size.spec.ts b/src/shapes/shape-text-size.spec.ts index bf2c5f115c..7825628377 100644 --- a/src/shapes/shape-text-size.spec.ts +++ b/src/shapes/shape-text-size.spec.ts @@ -1,13 +1,18 @@ import { describe, expect, it } from "vitest"; import { Formatter } from "@export/formatter"; -import { ExternalHyperlink, ImageRun, InternalHyperlink, Paragraph, Tab, TextRun } from "docx"; +import { File } from "@file/file"; +import { type IContext, Paragraph } from "docx"; -import { createTextParagraphs, getParagraphSpans, resolveShapeSize } from "./shape-text-size"; +import { createTextParagraphs, resolveShapeSize } from "./shape-text-size"; +import { type TextStyles, getTextStyles } from "./shape-text-styles"; import { measureLineHeight, measureTextWidth } from "./text-metrics"; const PIXELS_PER_POINT = 4 / 3; +const stylesOf = (document: object): TextStyles => + getTextStyles({ file: new File({ styles: { default: { document } }, sections: [] }), stack: [] } as unknown as IContext); + describe("createTextParagraphs", () => { it("should make a centred paragraph for each line", () => { const paragraphs = createTextParagraphs("One\nTwo"); @@ -20,50 +25,12 @@ describe("createTextParagraphs", () => { ], }); }); -}); -describe("getParagraphSpans", () => { - it("should read the text and font of each run", () => { - const spans = getParagraphSpans([ - new Paragraph({ - children: [ - new TextRun("Plain"), - new TextRun({ text: "Big", font: "Arial", size: 24, bold: true }), - new TextRun({ text: "Not bold", font: { ascii: "Calibri" }, bold: false }), - new TextRun({ text: "caps", allCaps: true }), - ], - }), - ]); - expect(spans).to.deep.equal([ - [ - { text: "Plain", font: undefined, size: undefined, bold: undefined }, - { text: "Big", font: "Arial", size: 12, bold: true }, - { text: "Not bold", font: "Calibri", size: undefined, bold: false }, - { text: "CAPS", font: undefined, size: undefined, bold: undefined }, - ], - ]); - }); - - it("should read tabs and line breaks", () => { - const [[span]] = getParagraphSpans([ - new Paragraph({ children: [new TextRun({ text: "a", break: 1 }), new TextRun({ children: [new Tab(), "b"] })] }), - ]); - expect(span.text).to.equal("\na"); - expect(getParagraphSpans([new Paragraph({ children: [new TextRun({ children: [new Tab(), "b"] })] })])[0][0].text).to.equal("\tb"); - }); - - it("should read the text of hyperlinks, and leave out runs without text", () => { - const image = new ImageRun({ type: "png", data: Buffer.from(""), transformation: { width: 10, height: 10 } }); - const spans = getParagraphSpans([ - new Paragraph({ - children: [ - new ExternalHyperlink({ link: "https://example.com", children: [new TextRun("web")] }), - new InternalHyperlink({ anchor: "top", children: [new TextRun("inside")] }), - image, - ], - }), - ]); - expect(spans[0].map(({ text }) => text)).to.deep.equal(["web", "inside"]); + it("should leave out the space the document puts before and after paragraphs", () => { + const [paragraph] = createTextParagraphs("One", stylesOf({ paragraph: { spacing: { after: 160 } } })); + expect(new Formatter().format(paragraph)["w:p"][0]).to.deep.equal({ + "w:pPr": [{ "w:spacing": { _attr: { "w:before": 0, "w:after": 0 } } }, { "w:jc": { _attr: { "w:val": "center" } } }], + }); }); }); @@ -173,6 +140,30 @@ describe("resolveShapeSize", () => { expect(Number.isFinite(width) && width > 0).to.equal(true); }); + it("should measure text in the document's styles", () => { + const options = { type: "rectangle", text: "Hello", transformation: { width: "fitText", height: "fitText" } } as const; + const styles = stylesOf({ run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160, line: 480 } } }); + const { width, height } = resolveShapeSize(options, styles); + expect(width).to.equal(Math.ceil((measureTextWidth("Hello", { font: "Calibri", size: 11 }) + 14.4) * PIXELS_PER_POINT + 2)); + // Double spacing, and no space after: the text's paragraph leaves it out + expect(height).to.equal(Math.ceil((2 * measureLineHeight({ font: "Calibri", size: 11 }) + 7.2) * PIXELS_PER_POINT)); + + // Paragraphs of the shape's own keep the document's spacing + const own = resolveShapeSize( + { type: "rectangle", children: [new Paragraph("Hello")], transformation: { width: 100, height: "fitText" } }, + styles, + ); + expect(own.height).to.equal(Math.ceil((2 * measureLineHeight({ font: "Calibri", size: 11 }) + 8 + 7.2) * PIXELS_PER_POINT)); + }); + + it("should make a shape without text as tall as an empty paragraph in the document's styles", () => { + const { height } = resolveShapeSize( + { type: "rectangle", transformation: { width: 40, height: "fitText" } }, + stylesOf({ run: { size: 40 } }), + ); + expect(height).to.equal(Math.ceil((measureLineHeight({ size: 20 }) + 7.2) * PIXELS_PER_POINT)); + }); + it("should give up on a text box that doesn't grow with the shape", () => { // A line's text box doesn't grow with its height, so its height can't be fitted and stops growing const { height } = resolveShapeSize({ type: "line", text: "a", transformation: { width: 50, height: "fitText" } }); diff --git a/src/shapes/shape-text-size.ts b/src/shapes/shape-text-size.ts index c86f78c433..73286d1876 100644 --- a/src/shapes/shape-text-size.ts +++ b/src/shapes/shape-text-size.ts @@ -4,17 +4,20 @@ * * @module */ -import { AlignmentType, ExternalHyperlink, type IContext, type IMediaTransformation, Paragraph, Run, TextRun, XmlComponent } from "docx"; +import { AlignmentType, type IMediaTransformation, Paragraph, TextRun } from "docx"; import { type PresetShapeType, type ShapeTextOptions, createShapeGuides } from "./preset-shape"; -import { type TextSpan, getTextRectangle, measureLineHeight, measureText } from "./text-metrics"; +import { type ShapePercentage, percentageOf } from "./shape-floating"; +import { type TextStyles, WORD_DEFAULT_STYLES, hasDefaultParagraphSpacing, readTextParagraphs } from "./shape-text-styles"; +import { getTextRectangle, measureText } from "./text-metrics"; /** - * A size in pixels, or `"fitText"` to fit the shape's text. + * A size in pixels, `"fitText"` to fit the shape's text, or a percentage, such as `"100%"`, for a floating shape: a + * percentage of the space between the page's margins, or of what `floating.sizeRelativeTo` gives. * * @publicApi */ -export type ShapeSize = number | "fitText"; +export type ShapeSize = number | "fitText" | ShapePercentage; /** * A shape's size in pixels, with optional rotation (degrees) and flip. Inside a group, `offset` positions the shape. @@ -22,14 +25,15 @@ export type ShapeSize = number | "fitText"; * @publicApi */ export type ShapeTransformation = Omit & { - /** Width in pixels, or `"fitText"` for as wide as the longest line of the shape's text */ + /** + * Width in pixels, `"fitText"` for as wide as the longest line of the shape's text, or a percentage of the space + * between the margins for a floating shape, such as `"100%"` + */ readonly width: ShapeSize; - /** Height in pixels, or `"fitText"` for as tall as the shape's text, wrapped at the shape's width */ + /** Height in pixels, `"fitText"` for as tall as the shape's text, wrapped at the shape's width, or a percentage for a floating shape */ readonly height: ShapeSize; }; -type XmlObject = Readonly>; - const EMUS_PER_PIXEL = 9525; const POINTS_PER_PIXEL = 0.75; // Word's default text margins, in points @@ -37,71 +41,15 @@ const DEFAULT_MARGINS = { top: 3.6, right: 7.2, bottom: 3.6, left: 7.2 }; // Room for the difference between the estimate and how Word lays the text out, in pixels const FIT_ALLOWANCE = 2; -// XmlComponent keeps its children in a protected array. Measuring reads it, and doesn't change it -const childrenOf = (component: XmlComponent): readonly unknown[] => (component as unknown as { readonly root: readonly unknown[] }).root; - -const valueOf = (children: readonly XmlObject[], name: string): XmlObject | undefined => - children.find((child) => name in child)?.[name] as XmlObject | undefined; - -const attributesOf = (element: XmlObject | undefined): XmlObject => (element?._attr ?? {}) as XmlObject; - /** - * The text and font of a text run, read from its XML. Tabs are `"\t"` and line breaks `"\n"`. + * Creates the paragraphs for a shape's `text`: one centred paragraph for each line. When the document's paragraphs + * have space before or after them, these don't, so the text stays in the middle of the shape. */ -const spanOf = (run: TextRun): TextSpan => { - // Formatting a run needs no document, as long as it has no fields or other parts that refer to one - const xml = run.prepForXml({ stack: [] } as unknown as IContext) as { readonly "w:r": readonly XmlObject[] }; - const children = xml["w:r"]; - const properties = (valueOf(children, "w:rPr") ?? []) as readonly XmlObject[]; - const fonts = attributesOf(valueOf(properties, "w:rFonts")); - const size = attributesOf(valueOf(properties, "w:sz"))["w:val"]; - const bold = valueOf(properties, "w:b"); - const text = children - .map((child) => { - if ("w:t" in child) { - return (child["w:t"] as readonly unknown[]).filter((part) => typeof part === "string").join(""); - } - if ("w:tab" in child) { - return "\t"; - } - return "w:br" in child || "w:cr" in child ? "\n" : ""; - }) - .join(""); - return { - text: valueOf(properties, "w:caps") ? text.toUpperCase() : text, - font: (fonts["w:ascii"] ?? fonts["w:hAnsi"]) as string | undefined, - size: typeof size === "number" ? size / 2 : undefined, - bold: bold === undefined ? undefined : attributesOf(bold)["w:val"] !== false, - }; +export const createTextParagraphs = (text: string, styles: TextStyles = WORD_DEFAULT_STYLES): readonly Paragraph[] => { + const spacing = hasDefaultParagraphSpacing(styles) ? { before: 0, after: 0 } : undefined; + return text.split("\n").map((line) => new Paragraph({ alignment: AlignmentType.CENTER, spacing, children: [new TextRun(line)] })); }; -/** - * The text runs in a paragraph, including those in hyperlinks. Pictures, shapes and other runs without text are left out. - */ -const spansIn = (children: readonly unknown[]): readonly TextSpan[] => - children.flatMap((child): readonly TextSpan[] => { - if (child instanceof TextRun) { - return [spanOf(child)]; - } - if (child instanceof ExternalHyperlink) { - return spansIn(child.options.children); - } - return child instanceof XmlComponent && !(child instanceof Run) ? spansIn(childrenOf(child)) : []; - }); - -/** - * Creates the paragraphs for a shape's `text`: one centred paragraph for each line. - */ -export const createTextParagraphs = (text: string): readonly Paragraph[] => - text.split("\n").map((line) => new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun(line)] })); - -/** - * The text of a shape's paragraphs, with the font of each run. Styles aren't known when a shape is created, so text - * without a font or size of its own is measured in Word's defaults. - */ -export const getParagraphSpans = (paragraphs: readonly Paragraph[]): readonly (readonly TextSpan[])[] => - paragraphs.map((paragraph) => spansIn(childrenOf(paragraph))); - /** * What a shape needs to be sized to fit its text. */ @@ -132,21 +80,47 @@ const solveLength = (needed: number, textLength: (length: number) => number): nu }; /** - * Works out a shape's width or height when it is `"fitText"`, from its text, font, margins and text box. - * The size is an estimate: text is measured with the widths of common fonts, without the document's styles. + * A size in pixels, or `"fitText"`: a percentage becomes the pixels it is of `base`. * - * @returns The transformation with both sizes in pixels + * @throws If the size is a percentage and there is nothing it can be a percentage of */ -export const resolveShapeSize = (options: TextSizingOptions): IMediaTransformation => { - const { transformation } = options; +const resolvePercentage = (size: ShapeSize, option: string, base?: number): number | "fitText" => { + const percentage = size === "fitText" ? undefined : percentageOf(size, option); + if (percentage === undefined) { + return size as number | "fitText"; + } + if (base === undefined) { + throw new Error(`Invalid ${option} "${size}". Only a floating shape can be a percentage of the page`); + } + return (base * percentage) / 100; +}; + +/** + * Works out a shape's width or height when it is `"fitText"`, from its text, the document's styles, and the shape's + * margins and text box. The size is an estimate: text is measured with the widths of common fonts. + * + * @param styles - The document's styles. Default is Word's own defaults + * @param percentageBase - What a percentage width and height are percentages of, in pixels. Without it, a size can't be a percentage + * @returns The transformation with both sizes in pixels + * @throws If a size is a percentage without a `percentageBase` + */ +export const resolveShapeSize = ( + options: TextSizingOptions, + styles: TextStyles = WORD_DEFAULT_STYLES, + percentageBase?: { readonly width: number; readonly height: number }, +): IMediaTransformation => { + const transformation = { + ...options.transformation, + width: resolvePercentage(options.transformation.width, "width", percentageBase?.width), + height: resolvePercentage(options.transformation.height, "height", percentageBase?.height), + }; if (transformation.width !== "fitText" && transformation.height !== "fitText") { return { ...transformation, width: transformation.width, height: transformation.height }; } - const paragraphs = getParagraphSpans([ - ...(options.text === undefined ? [] : createTextParagraphs(options.text)), - ...(options.children ?? []), - ]); + const written = [...(options.text === undefined ? [] : createTextParagraphs(options.text, styles)), ...(options.children ?? [])]; + // A shape without text is as tall as an empty paragraph + const paragraphs = readTextParagraphs(written.length > 0 ? written : [new Paragraph({})], styles); const { textOptions = {} } = options; const guides = options.type === "custom" ? undefined : createShapeGuides(options.type, options.adjustments); const margins = { ...DEFAULT_MARGINS, ...textOptions.margins }; @@ -167,7 +141,6 @@ export const resolveShapeSize = (options: TextSizingOptions): IMediaTransformati // Unwrapped text, for a fitted width, and a first guess at the length along the text const natural = measureText(paragraphs); - const lineHeight = measureLineHeight() / POINTS_PER_PIXEL; const guessAlong = typeof along === "number" ? along : natural.height / POINTS_PER_PIXEL + alongMargins; const acrossLength = across === "fitText" @@ -185,11 +158,9 @@ export const resolveShapeSize = (options: TextSizingOptions): IMediaTransformati along === "fitText" ? Math.ceil( solveLength( - Math.max( - measureText(paragraphs, wrapWidth === undefined ? undefined : wrapWidth * POINTS_PER_PIXEL).height / - POINTS_PER_PIXEL, - lineHeight, - ) + alongMargins, + measureText(paragraphs, wrapWidth === undefined ? undefined : wrapWidth * POINTS_PER_PIXEL).height / + POINTS_PER_PIXEL + + alongMargins, (length) => textBox(acrossLength, length).along, ), ) diff --git a/src/shapes/shape-text-styles.spec.ts b/src/shapes/shape-text-styles.spec.ts new file mode 100644 index 0000000000..2957cc40e5 --- /dev/null +++ b/src/shapes/shape-text-styles.spec.ts @@ -0,0 +1,281 @@ +import { describe, expect, it } from "vitest"; + +import { File } from "@file/file"; +import { + ExternalHyperlink, + HeadingLevel, + type IContext, + type IStylesOptions, + ImageRun, + InternalHyperlink, + LineRuleType, + Paragraph, + Tab, + TextRun, +} from "docx"; + +import { WORD_DEFAULT_STYLES, getTextStyles, hasDefaultParagraphSpacing, readTextParagraphs } from "./shape-text-styles"; + +const contextOf = (file: File): IContext => ({ file, stack: [] }) as unknown as IContext; + +const stylesOf = (styles: IStylesOptions & { readonly default?: object }): ReturnType => + getTextStyles(contextOf(new File({ styles, sections: [] }))); + +const readOne = (paragraph: Paragraph, styles = WORD_DEFAULT_STYLES): ReturnType[number] => + readTextParagraphs([paragraph], styles)[0]; + +describe("getTextStyles", () => { + it("should use Word's defaults when the context has no document", () => { + expect(getTextStyles({ stack: [] } as unknown as IContext)).to.equal(WORD_DEFAULT_STYLES); + }); + + it("should read the document's default run and paragraph formatting", () => { + const styles = stylesOf({ + default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160, line: 259 } } } }, + }); + expect(styles.run).to.deep.equal({ font: "Calibri", size: 11 }); + expect(styles.paragraph).to.deep.equal({ spaceAfter: 8, lineSpacing: { rule: "multiple", multiple: 259 / 240 } }); + }); + + it("should read the styles of a document once", () => { + const context = contextOf(new File({ sections: [] })); + expect(getTextStyles(context)).to.equal(getTextStyles(context)); + }); + + it("should use the style marked as the default, or Normal", () => { + expect(stylesOf({}).defaultParagraphStyle).to.equal(undefined); + expect(stylesOf({ paragraphStyles: [{ id: "Normal", name: "Normal" }] }).defaultParagraphStyle).to.equal("Normal"); + // A character style called Normal isn't the default for paragraphs + expect(stylesOf({ characterStyles: [{ id: "Normal", name: "Normal" }] }).defaultParagraphStyle).to.equal(undefined); + + const imported = getTextStyles( + contextOf( + new File({ + externalStyles: ` + + + + + + +`, + sections: [], + }), + ), + ); + expect(imported.defaultParagraphStyle).to.equal("Body"); + expect(imported.defaultCharacterStyle).to.equal("DefaultParagraphFont"); + }); + + it("should read styles imported from another document, whose values are text", () => { + const styles = getTextStyles( + contextOf( + new File({ + externalStyles: ` + + + + + + + + + + + + + + + +`, + sections: [], + }), + ), + ); + // The theme font isn't known, so the font comes from the other attributes + expect(styles.run).to.deep.equal({ font: "Aptos", size: 12, bold: false }); + expect(styles.paragraph).to.deep.equal({ spaceAfter: 8, lineSpacing: { rule: "multiple", multiple: 278 / 240 } }); + expect(styles.styles.get("Quote")).to.deep.equal({ + type: "paragraph", + basedOn: undefined, + run: { allCaps: false, characterSpacing: 0.5, scale: 90 }, + paragraph: { + spaceBefore: 6, + lineSpacing: { rule: "exact", height: 15 }, + indentLeft: 36, + indentRight: 18, + firstLineIndent: -18, + contextualSpacing: true, + }, + }); + expect(styles.styles.get("Tall")).to.deep.equal({ + type: "paragraph", + basedOn: undefined, + run: { font: "Arial", hidden: true, smallCaps: true }, + paragraph: { lineSpacing: { rule: "atLeast", height: 24 }, indentLeft: 5, indentRight: 10, firstLineIndent: 15 }, + }); + }); +}); + +describe("readTextParagraphs", () => { + it("should read the text and font of each run", () => { + const { spans } = readOne( + new Paragraph({ + children: [ + new TextRun("Plain"), + new TextRun({ text: "Big", font: "Arial", size: 24, bold: true }), + new TextRun({ text: "Not bold", font: { ascii: "Calibri" }, bold: false }), + new TextRun({ text: "Spaced", characterSpacing: 40, scale: 150 }), + ], + }), + ); + expect(spans).to.deep.equal([ + { text: "Plain" }, + { text: "Big", font: "Arial", size: 12, bold: true }, + { text: "Not bold", font: "Calibri", bold: false }, + { text: "Spaced", characterSpacing: 2, scale: 150 }, + ]); + }); + + it("should read tabs and line breaks", () => { + const { spans } = readOne( + new Paragraph({ children: [new TextRun({ text: "a", break: 1 }), new TextRun({ children: [new Tab(), "b"] })] }), + ); + expect(spans.map(({ text }) => text)).to.deep.equal(["\na", "\tb"]); + }); + + it("should read the text of hyperlinks, and leave out runs without text", () => { + const image = new ImageRun({ type: "png", data: Buffer.from(""), transformation: { width: 10, height: 10 } }); + const { spans } = readOne( + new Paragraph({ + children: [ + new ExternalHyperlink({ link: "https://example.com", children: [new TextRun("web")] }), + new InternalHyperlink({ anchor: "top", children: [new TextRun("inside")] }), + image, + ], + }), + ); + expect(spans.map(({ text }) => text)).to.deep.equal(["web", "inside"]); + }); + + it("should write capitals for all caps, smaller capitals for small caps, and leave out hidden text", () => { + const { spans } = readOne( + new Paragraph({ + children: [ + new TextRun({ text: "caps", allCaps: true }), + new TextRun({ text: "Small caps", smallCaps: true, size: 20 }), + new TextRun({ text: "hidden", vanish: true }), + new TextRun({ text: "x", smallCaps: true }), + ], + }), + ); + expect(spans).to.deep.equal([ + { text: "CAPS" }, + { text: "S", size: 10 }, + { text: "MALL", size: 8 }, + { text: " ", size: 10 }, + { text: "CAPS", size: 8 }, + // Without a size, small capitals are 80% of 10pt + { text: "X", size: 8 }, + ]); + }); + + it("should combine the document's defaults, the paragraph's styles, the run's styles and the run's own formatting", () => { + const styles = stylesOf({ + default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160 } } } }, + paragraphStyles: [ + { id: "Normal", name: "Normal", run: { size: 24 }, paragraph: { spacing: { line: 360 } } }, + { id: "Note", name: "Note", basedOn: "Normal", run: { bold: true }, paragraph: { indent: { left: 400 } } }, + ], + characterStyles: [ + { id: "Code", name: "Code", run: { font: "Courier New" } }, + { id: "BigCode", name: "Big code", basedOn: "Code", run: { size: 32 } }, + ], + }); + + const normal = readOne(new Paragraph({ children: [new TextRun("Normal")] }), styles); + expect(normal.style).to.equal("Normal"); + expect(normal.spans).to.deep.equal([{ text: "Normal", font: "Calibri", size: 12 }]); + expect(normal.format).to.deep.equal({ spaceAfter: 8, lineSpacing: { rule: "multiple", multiple: 1.5 } }); + + const note = readOne( + new Paragraph({ + style: "Note", + spacing: { after: 0 }, + children: [new TextRun("Note"), new TextRun({ text: "code", style: "BigCode", bold: false })], + }), + styles, + ); + expect(note.style).to.equal("Note"); + expect(note.spans).to.deep.equal([ + { text: "Note", font: "Calibri", size: 12, bold: true }, + { text: "code", font: "Courier New", size: 16, bold: false }, + ]); + expect(note.format).to.deep.equal({ spaceAfter: 0, lineSpacing: { rule: "multiple", multiple: 1.5 }, indentLeft: 20 }); + // The paragraph's mark has the paragraph's font + expect(note.font).to.deep.equal({ font: "Calibri", size: 12, bold: true }); + }); + + it("should use headings' styles", () => { + const styles = stylesOf({ default: { heading1: { run: { size: 36 } } } }); + const { spans } = readOne(new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Title")] }), styles); + expect(spans).to.deep.equal([{ text: "Title", size: 18 }]); + }); + + it("should stop at a style based on itself, and leave out styles of the wrong type or that don't exist", () => { + const styles = stylesOf({ + paragraphStyles: [{ id: "Normal", name: "Normal", basedOn: "Normal", run: { font: "MS Gothic" } }], + characterStyles: [{ id: "Strong", name: "Strong", run: { bold: true } }], + }); + expect(readOne(new Paragraph({ children: [new TextRun("a")] }), styles).spans).to.deep.equal([{ text: "a", font: "MS Gothic" }]); + // A character style used as a paragraph style, and a missing character style, change nothing + expect( + readOne(new Paragraph({ style: "Strong", children: [new TextRun({ text: "a", style: "Missing" })] }), styles).spans, + ).to.deep.equal([{ text: "a" }]); + }); + + it("should read the paragraph mark's own font, and a paragraph's line spacing and indents", () => { + const paragraph = readOne( + new Paragraph({ + run: { size: 40 }, + spacing: { before: 100, line: 300, lineRule: LineRuleType.EXACT }, + indent: { left: 200, right: 100, hanging: 50 }, + contextualSpacing: true, + }), + ); + expect(paragraph.spans).to.deep.equal([]); + expect(paragraph.font).to.deep.equal({ size: 20 }); + expect(paragraph.format).to.deep.equal({ + spaceBefore: 5, + lineSpacing: { rule: "exact", height: 15 }, + indentLeft: 10, + indentRight: 5, + firstLineIndent: -2.5, + contextualSpacing: true, + }); + }); + + it("should read a numbered paragraph without adding its numbering to a document", () => { + const file = new File({ + numbering: { config: [{ reference: "list", levels: [{ level: 0, text: "%1." }] }] }, + sections: [], + }); + const numberings = file.Numbering.ConcreteNumbering.length; + const paragraph = new Paragraph({ numbering: { reference: "list", level: 0 }, children: [new TextRun("One")] }); + expect(readTextParagraphs([paragraph], getTextStyles(contextOf(file)))[0].spans).to.deep.equal([{ text: "One" }]); + expect(file.Numbering.ConcreteNumbering).to.have.length(numberings); + }); +}); + +describe("hasDefaultParagraphSpacing", () => { + it("should be whether a paragraph without formatting has space before or after it", () => { + expect(hasDefaultParagraphSpacing(WORD_DEFAULT_STYLES)).to.equal(false); + expect(hasDefaultParagraphSpacing(stylesOf({ default: { document: { paragraph: { spacing: { after: 160 } } } } }))).to.equal(true); + expect( + hasDefaultParagraphSpacing( + stylesOf({ paragraphStyles: [{ id: "Normal", name: "Normal", paragraph: { spacing: { before: 60 } } }] }), + ), + ).to.equal(true); + expect(hasDefaultParagraphSpacing(stylesOf({ default: { document: { paragraph: { spacing: { line: 276 } } } } }))).to.equal(false); + }); +}); diff --git a/src/shapes/shape-text-styles.ts b/src/shapes/shape-text-styles.ts new file mode 100644 index 0000000000..9cd7db4564 --- /dev/null +++ b/src/shapes/shape-text-styles.ts @@ -0,0 +1,342 @@ +/** + * Reads the formatting that decides how much room a shape's text takes up: the document's default font and paragraph + * spacing, its paragraph and character styles, and the formatting of each paragraph and run. Not part of the public API. + * + * Formatting is combined as Word combines it: the document's defaults, then the paragraph's style and the styles it is + * based on, then the run's character style and the styles it is based on, then the paragraph's or run's own formatting. + * + * @module + */ +import { ExternalHyperlink, type IContext, type Paragraph, Run, TextRun, XmlComponent } from "docx"; + +import type { LineSpacing, ParagraphFormat, TextFont, TextParagraph, TextSpan } from "./text-metrics"; + +type XmlObject = Readonly>; + +/** + * Run formatting that changes how much room text takes up. + */ +type RunFormat = Omit & { + /** Size in points */ + readonly size?: number; + readonly allCaps?: boolean; + readonly smallCaps?: boolean; + /** Hidden text takes up no room */ + readonly hidden?: boolean; +}; + +type StyleDefinition = { + readonly type?: string; + readonly basedOn?: string; + readonly run: RunFormat; + readonly paragraph: ParagraphFormat; +}; + +/** + * The document's default formatting and its paragraph and character styles. + */ +export type TextStyles = { + /** The document's default run formatting (`w:rPrDefault`) */ + readonly run: RunFormat; + /** The document's default paragraph formatting (`w:pPrDefault`) */ + readonly paragraph: ParagraphFormat; + readonly styles: ReadonlyMap; + /** The style of paragraphs that don't give one, usually "Normal" */ + readonly defaultParagraphStyle?: string; + /** The style of runs that don't give one */ + readonly defaultCharacterStyle?: string; +}; + +/** + * No styles: text is measured in Word's own defaults, 10pt Times New Roman with single spacing. + */ +export const WORD_DEFAULT_STYLES: TextStyles = { run: {}, paragraph: {}, styles: new Map() }; + +// Small capitals are drawn as capitals at 80% of the size of the text, as LibreOffice draws them +const SMALL_CAPS_SCALE = 0.8; +const TWIPS_PER_POINT = 20; +// Single line spacing, in 240ths of a line +const SINGLE_LINE = 240; + +/** + * A context for formatting parts of the document to read them. Formatting paragraph properties that refer to a + * numbering adds the numbering to the document, so this context's document leaves it out. + */ +const READING_CONTEXT = { + stack: [], + file: { Numbering: { createConcreteNumberingInstance: (): void => undefined } }, +} as unknown as IContext; + +// XmlComponent keeps its children in a protected array. Reading them doesn't change them +const componentChildren = (component: XmlComponent): readonly unknown[] => + (component as unknown as { readonly root: readonly unknown[] }).root; + +const isObject = (value: unknown): value is XmlObject => typeof value === "object" && value !== null && !Array.isArray(value); + +/** + * The children of an element in a formatted tree. An element with children is an array, and one without is an object. + */ +const childrenOf = (element: unknown): readonly XmlObject[] => (Array.isArray(element) ? element.filter(isObject) : []); + +const attributesOf = (element: unknown): XmlObject => { + const holder = Array.isArray(element) ? element.find((child) => isObject(child) && "_attr" in child) : element; + return isObject(holder) && isObject(holder._attr) ? holder._attr : {}; +}; + +const find = (children: readonly XmlObject[], name: string): unknown => children.find((child) => name in child)?.[name]; + +// Attributes are numbers when the library writes them, and strings when they come from an imported document +const numberOf = (value: unknown): number | undefined => { + const parsed = typeof value === "string" ? Number.parseFloat(value) : value; + return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : undefined; +}; + +const stringOf = (value: unknown): string | undefined => (typeof value === "string" && value.length > 0 ? value : undefined); + +const scaled = (value: number | undefined, divisor: number): number | undefined => (value === undefined ? undefined : value / divisor); + +const isOff = (value: unknown): boolean => value === false || value === 0 || value === "false" || value === "0" || value === "off"; + +/** + * An on/off property, such as `w:b`: on when present, unless its value says otherwise. + */ +const onOff = (children: readonly XmlObject[], name: string): boolean | undefined => { + const element = children.find((child) => name in child); + return element ? !isOff(attributesOf(element[name])["w:val"]) : undefined; +}; + +const withoutUndefined = (object: T): T => + Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined)) as T; + +/** + * Combines formatting, with later formatting overriding earlier formatting. + */ +const combine = (formats: readonly T[]): T => + formats.reduce((all, format) => ({ ...all, ...withoutUndefined(format) }), {} as T); + +/** + * Reads run properties (`w:rPr`). Fonts given by the document theme (`w:asciiTheme`) are left out: the library doesn't + * write a theme. + */ +const readRunFormat = (element: unknown): RunFormat => { + const children = childrenOf(element); + const fonts = attributesOf(find(children, "w:rFonts")); + return withoutUndefined({ + font: stringOf(fonts["w:ascii"]) ?? stringOf(fonts["w:hAnsi"]), + size: scaled(numberOf(attributesOf(find(children, "w:sz"))["w:val"]), 2), + bold: onOff(children, "w:b"), + allCaps: onOff(children, "w:caps"), + smallCaps: onOff(children, "w:smallCaps"), + hidden: onOff(children, "w:vanish"), + characterSpacing: scaled(numberOf(attributesOf(find(children, "w:spacing"))["w:val"]), TWIPS_PER_POINT), + scale: numberOf(attributesOf(find(children, "w:w"))["w:val"]), + }); +}; + +const readLineSpacing = (spacing: XmlObject): LineSpacing | undefined => { + const line = numberOf(spacing["w:line"]); + if (line === undefined) { + return undefined; + } + const rule = spacing["w:lineRule"]; + return rule === "exact" || rule === "atLeast" + ? { rule, height: line / TWIPS_PER_POINT } + : { rule: "multiple", multiple: line / SINGLE_LINE }; +}; + +/** + * Reads paragraph properties (`w:pPr`). + */ +const readParagraphFormat = (element: unknown): ParagraphFormat => { + const children = childrenOf(element); + const spacing = attributesOf(find(children, "w:spacing")); + const indent = attributesOf(find(children, "w:ind")); + const twips = (...names: readonly string[]): number | undefined => + scaled( + names.map((name) => numberOf(indent[name])).find((value) => value !== undefined), + TWIPS_PER_POINT, + ); + const hanging = twips("w:hanging"); + return withoutUndefined({ + spaceBefore: scaled(numberOf(spacing["w:before"]), TWIPS_PER_POINT), + spaceAfter: scaled(numberOf(spacing["w:after"]), TWIPS_PER_POINT), + lineSpacing: readLineSpacing(spacing), + indentLeft: twips("w:start", "w:left"), + indentRight: twips("w:end", "w:right"), + firstLineIndent: hanging === undefined ? twips("w:firstLine") : -hanging, + contextualSpacing: onOff(children, "w:contextualSpacing"), + }); +}; + +const valueOf = (children: readonly XmlObject[], name: string): string | undefined => stringOf(attributesOf(find(children, name))["w:val"]); + +/** + * Reads the document's defaults and styles from its styles part (`w:styles`), once it is formatted. + */ +export const readTextStyles = (xml: XmlObject): TextStyles => { + const root = childrenOf(xml["w:styles"]); + // A document given styles of its own can have two sets of defaults: the library's, then the document's + const defaults = root.filter((child) => "w:docDefaults" in child).map((child) => childrenOf(child["w:docDefaults"])); + const styles = root + .filter((child) => "w:style" in child) + .map((child) => { + const children = childrenOf(child["w:style"]); + const attributes = attributesOf(child["w:style"]); + return { + id: stringOf(attributes["w:styleId"]), + isDefault: attributes["w:default"] !== undefined && !isOff(attributes["w:default"]), + definition: { + type: stringOf(attributes["w:type"]), + basedOn: valueOf(children, "w:basedOn"), + run: readRunFormat(find(children, "w:rPr")), + paragraph: readParagraphFormat(find(children, "w:pPr")), + }, + }; + }) + .filter((style): style is typeof style & { readonly id: string } => style.id !== undefined); + const defaultStyle = (type: string): string | undefined => + styles.find((style) => style.isDefault && style.definition.type === type)?.id; + const byId = new Map(styles.map((style) => [style.id, style.definition] as const)); + + return { + run: combine(defaults.map((children) => readRunFormat(find(childrenOf(find(children, "w:rPrDefault")), "w:rPr")))), + paragraph: combine(defaults.map((children) => readParagraphFormat(find(childrenOf(find(children, "w:pPrDefault")), "w:pPr")))), + styles: byId, + // Word uses "Normal" for paragraphs when no paragraph style is marked as the default + defaultParagraphStyle: defaultStyle("paragraph") ?? (byId.get("Normal")?.type === "paragraph" ? "Normal" : undefined), + defaultCharacterStyle: defaultStyle("character"), + }; +}; + +const stylesRead = new WeakMap(); + +/** + * The styles of the document being written, or Word's defaults when the context has no document. + */ +export const getTextStyles = (context: IContext): TextStyles => { + const styles = (context as Partial).file?.Styles; + if (!styles) { + return WORD_DEFAULT_STYLES; + } + const read = stylesRead.get(styles) ?? readTextStyles(styles.prepForXml(READING_CONTEXT) as XmlObject); + stylesRead.set(styles, read); + return read; +}; + +/** + * A style and the styles it is based on, from the one at the bottom to the style itself. A style that isn't of the + * given type, or that is based on itself, ends the chain. + */ +const styleChain = ({ styles }: TextStyles, id: string | undefined, type: string): readonly StyleDefinition[] => { + const walk = (current: string | undefined, seen: ReadonlySet): readonly StyleDefinition[] => { + const style = current === undefined || seen.has(current) ? undefined : styles.get(current); + return style?.type === type ? [...walk(style.basedOn, new Set([...seen, current!])), style] : []; + }; + return walk(id, new Set()); +}; + +/** + * The text of a run, with tabs as `"\t"` and line breaks as `"\n"`, and its own formatting and character style. + */ +const readRun = (run: TextRun): { readonly text: string; readonly format: RunFormat; readonly style?: string } => { + // Formatting a run needs no document, as long as it has no fields or other parts that refer to one + const xml = run.prepForXml(READING_CONTEXT) as { readonly "w:r": readonly XmlObject[] }; + const children = xml["w:r"]; + const properties = find(children, "w:rPr"); + const text = children + .map((child) => { + if ("w:t" in child) { + return (child["w:t"] as readonly unknown[]).filter((part) => typeof part === "string").join(""); + } + if ("w:tab" in child) { + return "\t"; + } + return "w:br" in child || "w:cr" in child ? "\n" : ""; + }) + .join(""); + return { text, format: readRunFormat(properties), style: valueOf(childrenOf(properties), "w:rStyle") }; +}; + +/** + * The text runs in a paragraph, including those in hyperlinks. Pictures, shapes and other runs without text are left out. + */ +const runsIn = (children: readonly unknown[]): readonly TextRun[] => + children.flatMap((child): readonly TextRun[] => { + if (child instanceof TextRun) { + return [child]; + } + if (child instanceof ExternalHyperlink) { + return runsIn(child.options.children); + } + return child instanceof XmlComponent && !(child instanceof Run) ? runsIn(componentChildren(child)) : []; + }); + +/** + * The parts of run formatting that change the font text is measured in. + */ +const fontOf = ({ font, size, bold, characterSpacing, scale }: RunFormat): TextFont => + withoutUndefined({ font, size, bold, characterSpacing, scale }); + +/** + * A span of text in its formatting: capitals for all caps, and smaller capitals for the small letters of small caps. + */ +const spansOf = (text: string, format: RunFormat): readonly TextSpan[] => { + const { allCaps, smallCaps, hidden } = format; + const font = fontOf(format); + if (hidden) { + return []; + } + if (allCaps || !smallCaps) { + return [{ ...font, text: allCaps ? text.toUpperCase() : text }]; + } + const small = { ...font, size: (font.size ?? 10) * SMALL_CAPS_SCALE }; + return text + .split(/(\p{Ll}+)/u) + .filter((part) => part.length > 0) + .map((part) => (/^\p{Ll}/u.test(part) ? { ...small, text: part.toUpperCase() } : { ...font, text: part })); +}; + +/** + * Reads a paragraph's text and formatting, as the document's styles format it. + */ +const readParagraph = (paragraph: Paragraph, styles: TextStyles): TextParagraph => { + // A paragraph's properties come first. They format to nothing when the paragraph has none + const [properties, ...children] = componentChildren(paragraph) as readonly XmlComponent[]; + const propertyChildren = childrenOf((properties.prepForXml(READING_CONTEXT) as XmlObject | undefined)?.["w:pPr"]); + const style = valueOf(propertyChildren, "w:pStyle") ?? styles.defaultParagraphStyle; + const paragraphStyles = styleChain(styles, style, "paragraph"); + const paragraphRun = combine([styles.run, ...paragraphStyles.map(({ run }) => run)]); + + const spans = runsIn(children).flatMap((run) => { + const { text, format, style: runStyle } = readRun(run); + const characterStyles = styleChain(styles, runStyle ?? styles.defaultCharacterStyle, "character"); + return spansOf(text, combine([paragraphRun, ...characterStyles.map(({ run: styleRun }) => styleRun), format])); + }); + return { + spans, + font: fontOf(combine([paragraphRun, readRunFormat(find(propertyChildren, "w:rPr"))])), + format: combine([ + styles.paragraph, + ...paragraphStyles.map(({ paragraph: format }) => format), + readParagraphFormat(propertyChildren), + ]), + style, + }; +}; + +/** + * Reads the text and formatting of a shape's paragraphs, as the document's styles format them. + */ +export const readTextParagraphs = (paragraphs: readonly Paragraph[], styles: TextStyles): readonly TextParagraph[] => + paragraphs.map((paragraph) => readParagraph(paragraph, styles)); + +/** + * Whether a paragraph in the default style, without formatting of its own, has space before or after it. + */ +export const hasDefaultParagraphSpacing = (styles: TextStyles): boolean => { + const { spaceBefore = 0, spaceAfter = 0 } = combine([ + styles.paragraph, + ...styleChain(styles, styles.defaultParagraphStyle, "paragraph").map(({ paragraph }) => paragraph), + ]); + return spaceBefore !== 0 || spaceAfter !== 0; +}; diff --git a/src/shapes/text-metrics/text-width.spec.ts b/src/shapes/text-metrics/text-width.spec.ts index d3f65e415f..c93f6a69f0 100644 --- a/src/shapes/text-metrics/text-width.spec.ts +++ b/src/shapes/text-metrics/text-width.spec.ts @@ -101,3 +101,80 @@ describe("measureText", () => { expect(measureText([[{ text: "ab cd" }]], 0).height).to.be.closeTo(2 * line, 0.001); }); }); + +describe("measureText with paragraph formatting", () => { + const line = measureLineHeight(); + const word = measureTextWidth("word"); + const space = measureTextWidth(" "); + + it("should add space before and after each paragraph", () => { + const size = measureText([ + { spans: [{ text: "a" }], format: { spaceBefore: 6, spaceAfter: 8 } }, + { spans: [{ text: "b" }], format: { spaceAfter: 8 } }, + ]); + expect(size.height).to.be.closeTo(6 + line + 8 + line + 8, 0.001); + }); + + it("should leave out contextual spacing next to a paragraph of the same style", () => { + const item = { spans: [{ text: "a" }], style: "List", format: { spaceBefore: 6, spaceAfter: 8, contextualSpacing: true } }; + expect(measureText([item, item]).height).to.be.closeTo(6 + 2 * line + 8, 0.001); + // Next to another style, the spacing stays + expect(measureText([item, { ...item, style: "Other" }]).height).to.be.closeTo(2 * (6 + line + 8), 0.001); + }); + + it("should space lines by a multiple, exactly, or at least a height", () => { + const spans = [{ text: "a\nb" }]; + expect(measureText([{ spans, format: { lineSpacing: { rule: "multiple", multiple: 1.5 } } }]).height).to.be.closeTo( + 3 * line, + 0.001, + ); + expect(measureText([{ spans, format: { lineSpacing: { rule: "exact", height: 5 } } }]).height).to.equal(10); + expect(measureText([{ spans, format: { lineSpacing: { rule: "atLeast", height: 5 } } }]).height).to.be.closeTo(2 * line, 0.001); + expect(measureText([{ spans, format: { lineSpacing: { rule: "atLeast", height: 20 } } }]).height).to.equal(40); + }); + + it("should make an empty paragraph as tall as its mark's font", () => { + expect(measureText([{ spans: [], font: { size: 20 } }]).height).to.be.closeTo(2 * line, 0.001); + }); + + it("should indent lines, and wrap them at the right indent", () => { + const format = { indentLeft: 10, indentRight: 5 }; + const unwrapped = measureText([{ spans: [{ text: "word word" }], format }]); + expect(unwrapped.width).to.be.closeTo(10 + 2 * word + space + 5, 0.001); + + // Two words fit in 2 words and a space, but not once the indents are taken off + const wrapped = measureText([{ spans: [{ text: "word word" }], format }], 2 * word + space + 1); + expect(wrapped.height).to.be.closeTo(2 * line, 0.001); + expect(wrapped.width).to.be.closeTo(10 + word + 5, 0.001); + }); + + it("should indent the first line further, or less for a hanging indent", () => { + const first = measureText([{ spans: [{ text: "word\nword" }], format: { indentLeft: 10, firstLineIndent: 20 } }]); + expect(first.width).to.be.closeTo(30 + word, 0.001); + const hanging = measureText([{ spans: [{ text: "word\nword" }], format: { indentLeft: 10, firstLineIndent: -10 } }]); + expect(hanging.width).to.be.closeTo(10 + word, 0.001); + + // The first line has room for one word less + expect( + measureText([{ spans: [{ text: "word word" }], format: { firstLineIndent: word + space } }], 2 * word + space + 1).height, + ).to.be.closeTo(2 * line, 0.001); + }); + + it("should break a long word onto indented lines", () => { + const long = measureTextWidth("abcdefghij"); + const size = measureText([{ spans: [{ text: "abcdefghij" }], format: { indentLeft: 10 } }], 10 + long / 2); + expect(size.height).to.be.closeTo(2 * line, 0.001); + expect(size.width).to.be.closeTo(10 + long / 2, 0.001); + }); + + it("should not break words when an indent leaves no room", () => { + expect(measureText([{ spans: [{ text: "ab cd" }], format: { indentLeft: 50 } }], 40).height).to.be.closeTo(2 * line, 0.001); + }); +}); + +describe("measureTextWidth with character spacing and scale", () => { + it("should add the spacing after each character, and scale the characters", () => { + expect(measureTextWidth("ab", { characterSpacing: 2 })).to.be.closeTo(measureTextWidth("ab") + 4, 0.001); + expect(measureTextWidth("ab", { scale: 50 })).to.be.closeTo(measureTextWidth("ab") / 2, 0.001); + }); +}); diff --git a/src/shapes/text-metrics/text-width.ts b/src/shapes/text-metrics/text-width.ts index 51a0840153..319602b735 100644 --- a/src/shapes/text-metrics/text-width.ts +++ b/src/shapes/text-metrics/text-width.ts @@ -18,6 +18,10 @@ export type TextFont = { /** Size in points. Default is 10, which Word uses when a document doesn't give a size */ readonly size?: number; readonly bold?: boolean; + /** Space added after each character, in points */ + readonly characterSpacing?: number; + /** How wide the characters are drawn, as a percentage of their width */ + readonly scale?: number; }; /** @@ -28,6 +32,49 @@ export type TextSpan = TextFont & { readonly text: string; }; +/** + * The spacing between a paragraph's lines. Default is single spacing. + */ +export type LineSpacing = + | { + readonly rule: "multiple"; + /** How many times single spacing, such as 1.5 */ + readonly multiple: number; + } + | { + /** Every line this tall, or single spacing if that is taller */ + readonly rule: "exact" | "atLeast"; + /** Height of a line in points */ + readonly height: number; + }; + +/** + * The formatting of a paragraph that changes how tall it is or where its lines wrap. Lengths are in points. + */ +export type ParagraphFormat = { + readonly spaceBefore?: number; + readonly spaceAfter?: number; + readonly lineSpacing?: LineSpacing; + readonly indentLeft?: number; + readonly indentRight?: number; + /** How much further in the first line starts than the others. Negative for a hanging indent */ + readonly firstLineIndent?: number; + /** Leaves out the space before and after the paragraph next to a paragraph of the same style */ + readonly contextualSpacing?: boolean; +}; + +/** + * A paragraph of text, with its formatting. + */ +export type TextParagraph = { + readonly spans: readonly TextSpan[]; + /** The font of the paragraph's mark, which sets the height of an empty paragraph */ + readonly font?: TextFont; + readonly format?: ParagraphFormat; + /** The paragraph's style, for `contextualSpacing` */ + readonly style?: string; +}; + export const DEFAULT_FONT = "Times New Roman"; export const DEFAULT_FONT_SIZE = 10; @@ -90,7 +137,7 @@ const characterWidth = (widths: readonly number[], code: number): number => { const sizeOf = ({ size = DEFAULT_FONT_SIZE }: TextFont): number => size; /** - * How wide a line of text is, in points. Tabs move to the next half inch, counted from `start`. + * How wide a line of text is, in points. Tabs move to the next half inch, counted from the start of the line. * * @param start - Where the text starts on its line, in points */ @@ -98,12 +145,13 @@ export const measureTextWidth = (text: string, font: TextFont = {}, start = 0): const { regular, bold } = widthsOf(font.font); const widths = font.bold ? bold : regular; const size = sizeOf(font); + const { characterSpacing = 0, scale = 100 } = font; return ( [...text].reduce((position, character) => { if (character === "\t") { return (Math.floor(position / TAB_STOP) + 1) * TAB_STOP; } - return position + (characterWidth(widths, character.codePointAt(0)!) * size) / 1000; + return position + (characterWidth(widths, character.codePointAt(0)!) * size * scale) / 100000 + characterSpacing; }, start) - start ); }; @@ -158,64 +206,122 @@ type LineState = { readonly position: number; /** Where the last word on the line ends: spaces at the end of a line aren't drawn */ readonly end: number; + /** Whether the line has a word on it yet */ + readonly started: boolean; }; /** - * Lays out one line of a paragraph, up to a line break, wrapping it at `maxWidth`. + * Lays out one line of a paragraph, up to a line break, wrapping it at `limit`. Positions are measured from the left + * edge of the text, so tabs line up across lines. + * + * @param start - Where the line starts: the paragraph's left indent, and its first line indent on its first line + * @param restart - Where the lines it wraps onto start + * @param limit - Where lines wrap: the width of the text less the paragraph's right indent */ -const wrapLine = (spans: readonly TextSpan[], height: number, maxWidth?: number): readonly Line[] => { - const wraps = (position: number, width: number): boolean => maxWidth !== undefined && position + width > maxWidth; +const wrapLine = (spans: readonly TextSpan[], height: number, start: number, restart: number, limit?: number): readonly Line[] => { + const wraps = (position: number, width: number): boolean => limit !== undefined && position + width > limit; + // The width of a whole line, after the indent + const room = limit === undefined ? 0 : limit - restart; const { lines, end } = tokenize(spans).reduce( (state, token) => { if (/^[ \t]/.test(token[0].text)) { return { ...state, position: state.position + measurePieces(token, state.position) }; } // A word that doesn't fit starts a new line, unless it is the first on its line - const wrapped = state.end > 0 && wraps(state.position, measurePieces(token, state.position)); + const wrapped = state.started && wraps(state.position, measurePieces(token, state.position)); const done = wrapped ? [...state.lines, { width: state.end, height }] : state.lines; - const position = wrapped ? 0 : state.position; + const position = wrapped ? restart : state.position; const width = measurePieces(token, position); - if (maxWidth === undefined || maxWidth <= 0 || !wraps(position, width)) { - return { lines: done, position: position + width, end: position + width }; + if (room <= 0 || !wraps(position, width)) { + return { lines: done, position: position + width, end: position + width, started: true }; } // A word wider than a line is broken across as many lines as it needs - const full = Math.ceil((position + width) / maxWidth) - 1; - const rest = position + width - full * maxWidth; - return { lines: [...done, ...Array.from({ length: full }, () => ({ width: maxWidth, height }))], position: rest, end: rest }; + const full = Math.ceil((position - restart + width) / room) - 1; + const last = position + width - full * room; + return { + lines: [...done, ...Array.from({ length: full }, () => ({ width: limit!, height }))], + position: last, + end: last, + started: true, + }; }, - { lines: [], position: 0, end: 0 }, + { lines: [], position: start, end: start, started: false }, ); return [...lines, { width: end, height }]; }; +/** + * How tall a paragraph's lines are: as tall as its tallest font, with its line spacing. + */ +const lineHeightOf = ({ spans, font = {}, format = {} }: TextParagraph): number => { + const single = Math.max(...(spans.length > 0 ? spans : [font]).map(measureLineHeight)); + const { lineSpacing } = format; + if (!lineSpacing) { + return single; + } + if (lineSpacing.rule === "multiple") { + return single * lineSpacing.multiple; + } + return lineSpacing.rule === "exact" ? lineSpacing.height : Math.max(single, lineSpacing.height); +}; + +/** + * Splits a paragraph's spans at line breaks. + */ +const splitLines = (spans: readonly TextSpan[]): readonly (readonly TextSpan[])[] => + spans.reduce( + (parts, span) => + span.text + .split("\n") + .reduce( + (spanParts, text, index) => + index === 0 + ? [...spanParts.slice(0, -1), [...spanParts[spanParts.length - 1], { ...span, text }]] + : [...spanParts, [{ ...span, text }]], + parts, + ), + [[]], + ); + +/** + * The space above and below a paragraph. With contextual spacing, there is none next to a paragraph of the same style. + */ +const spacingOf = ( + paragraph: TextParagraph, + before?: TextParagraph, + after?: TextParagraph, +): { readonly above: number; readonly below: number } => { + const { spaceBefore = 0, spaceAfter = 0, contextualSpacing } = paragraph.format ?? {}; + const sameStyle = (other?: TextParagraph): boolean => + contextualSpacing === true && other !== undefined && other.style === paragraph.style; + return { above: sameStyle(before) ? 0 : spaceBefore, below: sameStyle(after) ? 0 : spaceAfter }; +}; + /** * Measures text that wraps at `maxWidth`, or only at line breaks when `maxWidth` isn't given. Words wider than a - * line are broken across lines, as Word breaks them. Spaces at the ends of lines take no space. + * line are broken across lines, as Word breaks them. Spaces at the ends of lines take no space. Paragraphs take their + * space before and after, line spacing and indents from their `format`. * - * @param paragraphs - Each paragraph's spans. A paragraph without spans is one empty line in the default font + * @param paragraphs - Each paragraph, or just its spans. A paragraph without spans is one empty line * @param maxWidth - The width lines wrap at, in points */ -export const measureText = (paragraphs: readonly (readonly TextSpan[])[], maxWidth?: number): TextSize => { - const lines = paragraphs.flatMap((spans) => { - // Each line is as tall as its tallest font - const height = Math.max(...(spans.length > 0 ? spans : [{}]).map(measureLineHeight)); - const breaks = spans.reduce( - (parts, span) => - span.text - .split("\n") - .reduce( - (spanParts, text, index) => - index === 0 - ? [...spanParts.slice(0, -1), [...spanParts[spanParts.length - 1], { ...span, text }]] - : [...spanParts, [{ ...span, text }]], - parts, - ), - [[]], +export const measureText = (paragraphs: readonly (TextParagraph | readonly TextSpan[])[], maxWidth?: number): TextSize => { + const all = paragraphs.map((paragraph): TextParagraph => ("spans" in paragraph ? paragraph : { spans: paragraph })); + const measured = all.map((paragraph, index) => { + const { indentLeft = 0, indentRight = 0, firstLineIndent = 0 } = paragraph.format ?? {}; + const height = lineHeightOf(paragraph); + const limit = maxWidth === undefined ? undefined : maxWidth - indentRight; + const lines = splitLines(paragraph.spans).flatMap((line, lineIndex) => + wrapLine(line, height, indentLeft + (lineIndex === 0 ? firstLineIndent : 0), indentLeft, limit), ); - return breaks.flatMap((line) => wrapLine(line, height, maxWidth)); + const { above, below } = spacingOf(paragraph, all[index - 1], all[index + 1]); + return { + width: Math.max(0, ...lines.map(({ width }) => width + indentRight)), + height: above + lines.reduce((total, line) => total + line.height, 0) + below, + }; }); return { - width: Math.max(0, ...lines.map(({ width }) => width)), - height: lines.reduce((total, { height }) => total + height, 0), + width: Math.max(0, ...measured.map(({ width }) => width)), + height: measured.reduce((total, { height }) => total + height, 0), }; };