diff --git a/.github/workflows/demos.yml b/.github/workflows/demos.yml index 0de6eca3e7..c2bc7a62c5 100644 --- a/.github/workflows/demos.yml +++ b/.github/workflows/demos.yml @@ -265,3 +265,5 @@ jobs: # - uses: "./.github/actions/validate-docx" - run: npm run run-ts -- ./demo/119-theme-colors.ts - uses: "./.github/actions/validate-docx" + - run: npm run run-ts -- ./demo/120-custom-shapes.ts + # - uses: "./.github/actions/validate-docx" diff --git a/demo/120-custom-shapes.ts b/demo/120-custom-shapes.ts new file mode 100644 index 0000000000..4c6c8d9d23 --- /dev/null +++ b/demo/120-custom-shapes.ts @@ -0,0 +1,199 @@ +// Custom shapes with several paths, holes, text areas and connection points of their own. +// See docs/usage/shapes.md. + +import * as fs from "fs"; +import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx"; +import { type CustomShapePath, type IShapeCanvasChildOptions, ShapeCanvasRun, ShapeRun } from "docx/shapes"; + +const heading = (text: string): Paragraph => new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(text)] }); + +const space = (): TextRun => new TextRun(" "); + +const centred = (text: string): Paragraph => new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun(text)] }); + +// A cylinder: its body, and its top in a lighter shade of the fill +const cylinder: readonly CustomShapePath[] = [ + { path: "M 0 12 A 50 12 0 0 0 100 12 V 88 A 50 12 0 0 1 0 88 Z" }, + { path: "M 0 12 A 50 12 0 0 1 100 12 A 50 12 0 0 1 0 12 Z", fill: "lighter" }, +]; + +const circle = (radius: number): string => + `M ${50 - radius} 50 A ${radius} ${radius} 0 0 1 ${50 + radius} 50 A ${radius} ${radius} 0 0 1 ${50 - radius} 50 Z`; + +const BUBBLE = + "M 10 0 H 150 A 10 10 0 0 1 160 10 V 70 A 10 10 0 0 1 150 80 H 60 L 35 105 L 40 80 H 10 A 10 10 0 0 1 0 70 V 10 A 10 10 0 0 1 10 0 Z"; + +const arrow = { color: "404040", width: 1.25, endArrow: "triangle" } as const; + +// A web app, its server and its database. The database's connection points are the middles of its top, sides and +// bottom, rather than the corners of its paths +const system: readonly IShapeCanvasChildOptions[] = [ + { + id: "app", + type: "roundedRectangle", + text: "Web app", + transformation: { offset: { left: 0, top: 45 }, width: 110, height: 44 }, + fill: "DEEBF7", + line: "5B9BD5", + }, + { + id: "server", + type: "rectangle", + text: "Server", + transformation: { offset: { left: 200, top: 45 }, width: 110, height: 44 }, + fill: "E2F0D9", + line: "70AD47", + }, + { + id: "database", + type: "custom", + paths: cylinder, + connectionPoints: [ + { x: 50, y: 0 }, + { x: 100, y: 50 }, + { x: 50, y: 100 }, + { x: 0, y: 50 }, + ], + textArea: { left: 0, top: 24, right: 100, bottom: 100 }, + text: "Orders", + transformation: { offset: { left: 400, top: 17 }, width: 90, height: 100 }, + fill: "FFC000", + line: "BF9000", + }, + { + id: "backups", + type: "custom", + paths: cylinder, + connectionPoints: [ + { x: 50, y: 0 }, + { x: 100, y: 50 }, + { x: 50, y: 100 }, + { x: 0, y: 50 }, + ], + textArea: { left: 0, top: 24, right: 100, bottom: 100 }, + text: "Backups", + transformation: { offset: { left: 400, top: 190 }, width: 90, height: 70 }, + fill: "D9D9D9", + line: "7F7F7F", + }, + { type: "connector", from: "app", to: "server", line: arrow, label: { text: "HTTPS", fill: "FFFFFF" } }, + { type: "connector", from: "server", to: "database", line: arrow, label: { text: "SQL", fill: "FFFFFF" } }, + { type: "connector", from: "database", to: "backups", line: arrow, label: { text: "Nightly", fill: "FFFFFF" } }, +]; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("Custom shapes")] }), + + heading("Several paths"), + new Paragraph({ + spacing: { after: 300 }, + children: [ + // A box whose top is lighter and whose right side is darker than its fill + new ShapeRun({ + type: "custom", + paths: [ + { path: "M 0 25 L 50 0 L 100 25 L 50 50 Z", fill: "lighter" }, + { path: "M 0 25 L 50 50 L 50 110 L 0 85 Z" }, + { path: "M 50 50 L 100 25 L 100 85 L 50 110 Z", fill: "darker" }, + ], + transformation: { width: 80, height: 88 }, + fill: "4472C4", + line: "2F5597", + }), + space(), + // A page with a folded corner, and lines of text that are only drawn, not filled + new ShapeRun({ + type: "custom", + paths: [ + { path: "M 0 0 H 70 L 100 30 V 130 H 0 Z" }, + { path: "M 70 0 V 30 H 100", fill: "darker" }, + { path: "M 15 55 H 85 M 15 75 H 85 M 15 95 H 60", fill: false }, + ], + transformation: { width: 68, height: 88 }, + fill: "F2F2F2", + line: "7F7F7F", + }), + space(), + new ShapeRun({ + type: "custom", + paths: cylinder, + transformation: { width: 80, height: 88 }, + fill: "FFC000", + line: "BF9000", + }), + ], + }), + + heading("Holes"), + new Paragraph({ + spacing: { after: 300 }, + children: [ + // A part of a path inside another is a hole in it, whichever way round either is drawn + new ShapeRun({ + type: "custom", + path: `${circle(50)} ${circle(28)}`, + transformation: { width: 88, height: 88 }, + fill: "70AD47", + line: "548235", + }), + space(), + // A part inside a hole is filled again + new ShapeRun({ + type: "custom", + path: `${circle(50)} ${circle(36)} ${circle(22)} ${circle(10)}`, + transformation: { width: 88, height: 88 }, + fill: "C00000", + line: "none", + }), + space(), + // A plate with a keyhole + new ShapeRun({ + type: "custom", + path: "M 0 6 A 6 6 0 0 1 6 0 H 54 A 6 6 0 0 1 60 6 V 84 A 6 6 0 0 1 54 90 H 6 A 6 6 0 0 1 0 84 Z M 24 44 A 12 12 0 1 1 36 44 L 40 70 H 20 Z", + transformation: { width: 59, height: 88 }, + fill: "A5A5A5", + line: "7F7F7F", + }), + ], + }), + + heading("Text areas"), + new Paragraph({ + spacing: { after: 300 }, + children: [ + // Without a text area, the text is in the middle of the whole shape, tail and all + new ShapeRun({ + type: "custom", + path: BUBBLE, + transformation: { width: 180, height: 118 }, + fill: "FBE5D6", + line: "ED7D31", + children: [centred("Without a text area")], + }), + space(), + // With one, it is in the middle of the bubble, clear of the tail + new ShapeRun({ + type: "custom", + path: BUBBLE, + textArea: { left: 0, top: 0, right: 160, bottom: 80 }, + transformation: { width: 180, height: 118 }, + fill: "FBE5D6", + line: "ED7D31", + children: [centred("With a text area")], + }), + ], + }), + + heading("Connection points"), + new Paragraph({ children: [new ShapeCanvasRun({ children: system })] }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/docs/usage/shapes.md b/docs/usage/shapes.md index 35e33c3b77..b413a1e359 100644 --- a/docs/usage/shapes.md +++ b/docs/usage/shapes.md @@ -22,6 +22,7 @@ Like an image, a shape is a run inside a `Paragraph`. It sits in the line of tex | Crop a photo to a circle | `ellipse` with a picture `fill` | Profile picture | | Add a shadow, glow or reflection | `effects` | Card with a drop shadow | | Draw a shape that isn't a preset | `type: "custom"` with an SVG `path` | Logo, badge, freeform outline | +| Draw an icon with shading, holes or details | `type: "custom"` with several `paths` | Cube, cylinder, page, ring | ## Importing @@ -558,7 +559,114 @@ new ShapeRun({ The path can use the commands `M` (move), `L` (line), `H` and `V` (horizontal and vertical lines), `C` and `S` (cubic curves), `Q` and `T` (quadratic curves), `A` (elliptical arcs) and `Z` (close), in upper case for absolute coordinates and lower case for relative ones. A path that isn't closed is still filled, as in SVG, but its line and arrowheads are drawn only along the path. -Custom shapes can hold text like any other shape. Connectors attach to the corners and ends of the path. +Custom shapes can hold text like any other shape. Connectors attach to the corners and ends of the path, unless the shape has [connection points](#connection-points) of its own. + +### Several paths + +`paths` draws a shape from several paths, in the same units, such as the faces of a box or the body and top of a cylinder. The box around all of them is scaled to fill the shape, and later paths are drawn over earlier ones. + +```ts +// A box whose top is lighter and whose right side is darker than its fill +new ShapeRun({ + type: "custom", + paths: [ + { path: "M 0 25 L 50 0 L 100 25 L 50 50 Z", fill: "lighter" }, + { path: "M 0 25 L 50 50 L 50 110 L 0 85 Z" }, + { path: "M 50 50 L 100 25 L 100 85 L 50 110 Z", fill: "darker" }, + ], + transformation: { width: 80, height: 88 }, + fill: "4472C4", +}); + +// A page with a folded corner, and lines that are drawn but not filled +new ShapeRun({ + type: "custom", + paths: [ + { path: "M 0 0 H 70 L 100 30 V 130 H 0 Z" }, + { path: "M 70 0 V 30 H 100", fill: "darker" }, + { path: "M 15 55 H 85 M 15 75 H 85 M 15 95 H 60", fill: false }, + ], + transformation: { width: 68, height: 88 }, + fill: "F2F2F2", + line: "7F7F7F", +}); +``` + +Each path is filled with the shape's `fill` and outlined with its `line`, as Word's preset shapes shade the top of a cube or the inside of a can: + +| Option | Type | Description | +| ------ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | `string` | SVG path data | +| `fill` | `CustomShapePathFill` | `true` (the default) fills the path with the shape's fill, and `false` leaves it empty. `"lighter"`, `"slightlyLighter"`, `"darker"` and `"slightlyDarker"` shade the fill | +| `line` | `boolean` | Whether the shape's line is drawn along the path. Default is `true` | + +A shape has one fill and one line, so paths can't have colours of their own. For parts in different colours, put shapes in a [group](#groups). + +### Holes + +A closed part of a path inside another part is a hole in it, and a part inside a hole is filled again. This works whichever way round each part is drawn: parts are turned round where they need to be, so that applications that fill paths by the non-zero rule, which needs a hole to go the other way, cut the same holes as LibreOffice, which fills by the even-odd rule. + +```ts +// A ring +new ShapeRun({ + type: "custom", + path: "M 0 50 A 50 50 0 0 1 100 50 A 50 50 0 0 1 0 50 Z M 22 50 A 28 28 0 0 1 78 50 A 28 28 0 0 1 22 50 Z", + transformation: { width: 88, height: 88 }, + fill: "70AD47", +}); +``` + +Holes are cut within a path. Separate paths in `paths` are filled one after the other, so they don't cut holes in each other. A path that crosses itself, such as a star drawn as one line with five points, is filled differently by different applications: LibreOffice leaves its middle empty. Draw the outline of a star instead. + +### Text area + +The text of a custom shape uses the whole shape, unless `textArea` gives the box it goes in, in the units of the paths. A speech bubble's text can then go in the bubble and not its tail. `"fitText"` sizes the shape so its text fits in the text area. + +```ts +new ShapeRun({ + type: "custom", + path: "M 10 0 H 150 A 10 10 0 0 1 160 10 V 70 A 10 10 0 0 1 150 80 H 60 L 35 105 L 40 80 H 10 A 10 10 0 0 1 0 70 V 10 A 10 10 0 0 1 10 0 Z", + textArea: { left: 0, top: 0, right: 160, bottom: 80 }, + transformation: { width: 180, height: "fitText" }, + fill: "FBE5D6", + text: "Clear of the tail", +}); +``` + +### Connection points + +Connectors attach to the corners and ends of a custom shape's paths. For a shape whose corners aren't where connectors should meet it, such as a cylinder, `connectionPoints` gives the points of its own, in the units of the paths. Each point faces the side of the shape it is nearest, or the `side` given, and connectors leave it towards that side. A connector's end with a `side` attaches to the point facing that side, and one with a `point` to the nearest point. An empty list leaves the shape without connection points, and connectors end at the middles of its sides. + +```ts +new ShapeCanvasRun({ + children: [ + { id: "server", type: "rectangle", text: "Server", transformation: { offset: { top: 28 }, width: 110, height: 44 } }, + { + id: "database", + type: "custom", + paths: [ + { path: "M 0 12 A 50 12 0 0 0 100 12 V 88 A 50 12 0 0 1 0 88 Z" }, + { path: "M 0 12 A 50 12 0 0 1 100 12 A 50 12 0 0 1 0 12 Z", fill: "lighter" }, + ], + // The middles of its top, right side, bottom and left side + connectionPoints: [ + { x: 50, y: 0 }, + { x: 100, y: 50 }, + { x: 50, y: 100 }, + { x: 0, y: 50 }, + ], + // Below the top + textArea: { left: 0, top: 24, right: 100, bottom: 100 }, + text: "Orders", + transformation: { offset: { left: 200 }, width: 90, height: 100 }, + fill: "FFC000", + }, + { type: "connector", from: "server", to: "database", line: { endArrow: "triangle" } }, + ], +}); +``` + +The connection points and text area keep their place in the shape when it is resized in Word, as the points of freeforms drawn in Office do. ## Links and Decorative Shapes @@ -883,23 +991,26 @@ Each lane is as wide as its shapes and its name need. The shapes in each lane ar ### 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` | `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 | +| 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) | +| `paths` | `CustomShapePath[]` | Optional | Several paths, for `type: "custom"`, instead of `path`. See [Several paths](#several-paths) | +| `textArea` | `CustomShapeTextArea` | Optional | Where the text of a custom shape goes. See [Text area](#text-area) | +| `connectionPoints` | `CustomShapeConnectionPoint[]` | Optional | The points connectors attach to on a custom shape. See [Connection points](#connection-points) | +| `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 @@ -953,6 +1064,7 @@ LibreOffice (checked with version 26.8) draws most shapes as Word does, but: - On a canvas, it draws connectors between their shapes' connection points in its own way, rather than on the route in the document. A connector that goes around a shape may go through it, and connector ends that are spread along a side meet at the connection point. In a group, it draws the route in the document. - It draws the text of a shape that has `resizeShapeToFitText`, or of a group or canvas that starts a new line, on the first line of the paragraph. - It doesn't turn the text of a rotated shape with the shape. +- It fills a custom shape's path by the even-odd rule, so a path that crosses itself has gaps where it encloses an area twice. Apple Pages (checked with version 15.1) draws shapes and groups, and the group in place of a canvas, but: @@ -1047,3 +1159,11 @@ A document with a theme of its own, swatches of its colours and of lighter and d [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/118-theme.ts ":include") _Source: https://github.com/dolanmiu/docx/blob/master/demo/118-theme.ts_ + +### Custom shapes + +Custom shapes drawn from several paths, with shaded faces, holes, text areas, and connection points of their own on a canvas. + +[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/120-custom-shapes.ts ":include") + +_Source: https://github.com/dolanmiu/docx/blob/master/demo/120-custom-shapes.ts_ diff --git a/scripts/render-shape-demos.sh b/scripts/render-shape-demos.sh index 7c1d4494bc..e08dd23a1a 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 115-shape-document-styles 116-shape-swimlanes 117-shape-page-layout 118-theme) + 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 118-theme 120-custom-shapes) fi SOFFICE="${SOFFICE:-soffice}" WP="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" diff --git a/scripts/shape-demos/references/120-custom-shapes-1.png b/scripts/shape-demos/references/120-custom-shapes-1.png new file mode 100644 index 0000000000..dcf5b5986c Binary files /dev/null and b/scripts/shape-demos/references/120-custom-shapes-1.png differ diff --git a/src/shapes/custom-geometry/custom-geometry.spec.ts b/src/shapes/custom-geometry/custom-geometry.spec.ts index 74582b9d88..c1618a3285 100644 --- a/src/shapes/custom-geometry/custom-geometry.spec.ts +++ b/src/shapes/custom-geometry/custom-geometry.spec.ts @@ -2,10 +2,20 @@ import { describe, expect, it } from "vitest"; import { Formatter } from "@export/formatter"; -import { type CustomPathSegment, createCustomGeometry, createCustomGeometryPath } from "./custom-geometry"; +import { type CustomPathSegment, createCustomGeometry, createCustomGeometryData, getCustomTextRectangle } from "./custom-geometry"; type Point = { readonly x: number; readonly y: number }; +// A shape with one path, and that path's segments +const withOnePath = ( + path: string, + width: number, + height: number, +): ReturnType & { readonly segments: readonly CustomPathSegment[] } => { + const geometry = createCustomGeometryData({ path }, width, height); + return { ...geometry, segments: geometry.paths[0].segments }; +}; + /** * Follows a path as Word draws it, and returns where each segment ends. An arc starts where the pen is, at the * point on its ellipse in the direction of its start angle, and ends in the direction of its start plus swing angle. @@ -43,9 +53,9 @@ const penPositions = (segments: readonly CustomPathSegment[]): readonly Point[] }); }; -describe("createCustomGeometryPath", () => { +describe("createCustomGeometryData", () => { it("should stretch the box around the path to fill the shape", () => { - const geometry = createCustomGeometryPath("M 10 10 L 110 10 L 60 60 Z", 1000, 500); + const geometry = withOnePath("M 10 10 L 110 10 L 60 60 Z", 1000, 500); expect(geometry).to.deep.include({ width: 1000, height: 500 }); expect(geometry.segments).to.deep.equal([ { type: "move", to: { x: 0, y: 0 } }, @@ -57,7 +67,7 @@ describe("createCustomGeometryPath", () => { it("should scale curves and round to whole EMUs", () => { // The box around the path is 6 by 4, stretched to 700 by 1000 EMUs - const geometry = createCustomGeometryPath("M 0 0 L 6 0 L 6 4 C 4 4 2 4 0 4 Q 0 2 0 0", 700, 1000); + const geometry = withOnePath("M 0 0 L 6 0 L 6 4 C 4 4 2 4 0 4 Q 0 2 0 0", 700, 1000); expect(geometry.segments.slice(3)).to.deep.equal([ { type: "cubic", @@ -78,13 +88,13 @@ describe("createCustomGeometryPath", () => { }); it("should draw a path with no width or height along the edge of the shape", () => { - const geometry = createCustomGeometryPath("M 5 0 L 5 10", 100, 100); + const geometry = withOnePath("M 5 0 L 5 10", 100, 100); expect(geometry.segments).to.deep.equal([ { type: "move", to: { x: 0, y: 0 } }, { type: "line", to: { x: 0, y: 100 } }, ]); - const flat = createCustomGeometryPath("M 0 5 L 10 5", 100, 0); + const flat = withOnePath("M 0 5 L 10 5", 100, 0); expect(flat.segments).to.deep.equal([ { type: "move", to: { x: 0, y: 0 } }, { type: "line", to: { x: 100, y: 0 } }, @@ -95,7 +105,7 @@ describe("createCustomGeometryPath", () => { describe("arcs", () => { it("should write an upright arc as an arcTo, with angles in 60,000ths of a degree", () => { // A half circle over the top, clockwise from the left - const geometry = createCustomGeometryPath("M 0 50 A 50 50 0 0 1 100 50", 1000, 500); + const geometry = withOnePath("M 0 50 A 50 50 0 0 1 100 50", 1000, 500); expect(geometry.segments[1]).to.deep.equal({ type: "arc", widthRadius: 500, @@ -106,7 +116,7 @@ describe("createCustomGeometryPath", () => { }); it("should end an arc where the path's arc ends, when the shape stretches it", () => { - const geometry = createCustomGeometryPath("M 0 0 A 100 50 0 0 0 100 50 L 100 100", 3000, 1000); + const geometry = withOnePath("M 0 0 A 100 50 0 0 0 100 50 L 100 100", 3000, 1000); const pen = penPositions(geometry.segments); expect(pen[1].x).to.be.closeTo(3000, 1); expect(pen[1].y).to.be.closeTo(500, 1); @@ -114,19 +124,19 @@ describe("createCustomGeometryPath", () => { }); it("should turn anticlockwise, and the long way round, as the path's arc does", () => { - const anticlockwise = createCustomGeometryPath("M 100 50 A 50 50 0 0 0 50 0", 100, 100); + const anticlockwise = withOnePath("M 100 50 A 50 50 0 0 0 50 0", 100, 100); expect(anticlockwise.segments[1]).to.deep.include({ startAngle: 0, swingAngle: -90 * 60000 }); - const long = createCustomGeometryPath("M 100 50 A 50 50 0 1 1 50 0", 100, 100); + const long = withOnePath("M 100 50 A 50 50 0 1 1 50 0", 100, 100); expect(long.segments[1]).to.deep.include({ startAngle: 0, swingAngle: 270 * 60000 }); - const longAnticlockwise = createCustomGeometryPath("M 50 0 A 50 50 0 1 0 100 50", 100, 100); + const longAnticlockwise = withOnePath("M 50 0 A 50 50 0 1 0 100 50", 100, 100); expect(longAnticlockwise.segments[1]).to.deep.include({ startAngle: 270 * 60000, swingAngle: -270 * 60000 }); }); it("should swap the radii of an ellipse turned a quarter turn", () => { // The ellipse's long axis, 200 long, is turned to point down the page. The arc bulges 50 to the right - const geometry = createCustomGeometryPath("M 0 0 A 100 50 90 0 1 0 200", 50, 200); + const geometry = withOnePath("M 0 0 A 100 50 90 0 1 0 200", 50, 200); expect(geometry.segments[1]).to.deep.include({ type: "arc", widthRadius: 50, heightRadius: 100 }); const pen = penPositions(geometry.segments); expect(pen[1].x).to.be.closeTo(0, 1); @@ -134,12 +144,12 @@ describe("createCustomGeometryPath", () => { }); it("should write a circle's arc as an arcTo however it is turned", () => { - const geometry = createCustomGeometryPath("M 0 50 A 50 50 30 0 1 100 50", 100, 50); + const geometry = withOnePath("M 0 50 A 50 50 30 0 1 100 50", 100, 50); expect(geometry.segments[1]).to.deep.include({ type: "arc", widthRadius: 50, heightRadius: 50 }); }); it("should draw an arc of a tilted ellipse with Bézier curves, a quarter turn or less each", () => { - const geometry = createCustomGeometryPath("M 0 0 A 100 50 30 1 1 100 100", 1000, 1000); + const geometry = withOnePath("M 0 0 A 100 50 30 1 1 100 100", 1000, 1000); const curves = geometry.segments.slice(1); expect(curves.every((segment) => segment.type === "cubic")).to.equal(true); expect(curves.length).to.be.within(3, 4); @@ -152,7 +162,7 @@ describe("createCustomGeometryPath", () => { it("should draw an arc as a line when the shape has no width or height", () => { // The arc goes 10 above its ends, so its ends are half way down the path's box - const geometry = createCustomGeometryPath("M 0 0 A 10 10 0 0 1 20 0 L 20 10", 0, 100); + const geometry = withOnePath("M 0 0 A 10 10 0 0 1 20 0 L 20 10", 0, 100); expect(geometry.segments[1]).to.deep.equal({ type: "line", to: { x: 0, y: 50 } }); }); }); @@ -160,7 +170,7 @@ describe("createCustomGeometryPath", () => { describe("connection sites", () => { it("should put a site at each corner, leaving away from the middle of the shape", () => { // The bottom corners are as far down as across, so connectors leave them downwards - const geometry = createCustomGeometryPath("M 50 0 L 100 100 L 0 100 Z", 1000, 1000); + const geometry = withOnePath("M 50 0 L 100 100 L 0 100 Z", 1000, 1000); expect(geometry.sites).to.deep.equal([ { x: 500, y: 0, angle: 270 }, { x: 1000, y: 1000, angle: 90 }, @@ -170,16 +180,14 @@ describe("createCustomGeometryPath", () => { it("should measure how far out a corner is as a share of the shape's width and height", () => { // Near the right end of the top of a wide shape, the corner is further up than across - const geometry = createCustomGeometryPath("M 0 0 L 90 0 L 100 5 L 90 10 L 0 10 Z", 1000, 100); + const geometry = withOnePath("M 0 0 L 90 0 L 100 5 L 90 10 L 0 10 Z", 1000, 100); expect(geometry.sites.map(({ angle }) => angle)).to.deep.equal([270, 270, 0, 90, 90]); - expect(createCustomGeometryPath("M 0 0 L 100 50 L 0 100", 1000, 1000).sites.map(({ angle }) => angle)).to.deep.equal([ - 270, 0, 90, - ]); + expect(withOnePath("M 0 0 L 100 50 L 0 100", 1000, 1000).sites.map(({ angle }) => angle)).to.deep.equal([270, 0, 90]); }); it("should put a site at the ends of curves and arcs, once for each point", () => { // The arc reaches 50 above its ends and the curve 25 below them, so the ends are two thirds of the way down - const geometry = createCustomGeometryPath("M 0 50 A 50 50 0 0 1 100 50 Q 50 100 0 50 Z", 100, 100); + const geometry = withOnePath("M 0 50 A 50 50 0 0 1 100 50 Q 50 100 0 50 Z", 100, 100); expect(geometry.sites.map(({ x, y }) => [x, y])).to.deep.equal([ [0, 67], [100, 67], @@ -187,26 +195,197 @@ describe("createCustomGeometryPath", () => { }); it("should leave a site in the middle of a shape to the right", () => { - const geometry = createCustomGeometryPath("M 0 0 L 10 10 L 5 5", 10, 10); + const geometry = withOnePath("M 0 0 L 10 10 L 5 5", 10, 10); expect(geometry.sites[2]).to.deep.equal({ x: 5, y: 5, angle: 0 }); - expect(createCustomGeometryPath("M 0 0 L 0 10", 0, 10).sites.map(({ angle }) => angle)).to.deep.equal([270, 90]); + expect(withOnePath("M 0 0 L 0 10", 0, 10).sites.map(({ angle }) => angle)).to.deep.equal([270, 90]); }); }); + + describe("several paths", () => { + it("should stretch the box around all the paths to fill the shape", () => { + const geometry = createCustomGeometryData( + { paths: [{ path: "M 0 0 L 10 0 L 10 10 Z" }, { path: "M 20 20 L 30 20" }] }, + 300, + 200, + ); + expect(geometry.paths.map(({ segments }) => segments)).to.deep.equal([ + [ + { type: "move", to: { x: 0, y: 0 } }, + { type: "line", to: { x: 100, y: 0 } }, + { type: "line", to: { x: 100, y: 100 } }, + { type: "close" }, + ], + [ + { type: "move", to: { x: 200, y: 200 } }, + { type: "line", to: { x: 300, y: 200 } }, + ], + ]); + }); + + it("should fill each path with the shape's fill, none, or the fill made lighter or darker, and draw the line unless told not to", () => { + const fills = [true, false, "lighter", "slightlyLighter", "darker", "slightlyDarker", undefined] as const; + const geometry = createCustomGeometryData( + { + paths: fills.map((fill, index) => ({ + path: `M 0 ${index} L 10 ${index}`, + fill, + line: index === 1 ? false : undefined, + })), + }, + 100, + 100, + ); + expect(geometry.paths.map(({ fill, stroke }) => [fill, stroke])).to.deep.equal([ + ["norm", true], + ["none", false], + ["lighten", true], + ["lightenLess", true], + ["darken", true], + ["darkenLess", true], + ["norm", true], + ]); + }); + + it("should put a site at the corners and ends of every path, once for each point", () => { + const geometry = createCustomGeometryData({ paths: [{ path: "M 0 0 L 10 0 L 10 10" }, { path: "M 10 10 L 0 10" }] }, 10, 10); + expect(geometry.sites.map(({ x, y }) => [x, y])).to.deep.equal([ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ]); + }); + + it("should make a part inside another a hole, whichever way it goes", () => { + // The inner square goes the same way as the outer one, so it is drawn the other way round + const geometry = createCustomGeometryData({ path: "M 0 0 H 4 V 4 H 0 Z M 1 1 H 3 V 3 H 1 Z" }, 4, 4); + expect(geometry.paths[0].segments.slice(5)).to.deep.equal([ + { type: "move", to: { x: 1, y: 1 } }, + { type: "line", to: { x: 1, y: 3 } }, + { type: "line", to: { x: 3, y: 3 } }, + { type: "line", to: { x: 3, y: 1 } }, + { type: "close" }, + ]); + }); + + it("should reject a shape without a path, with both path and paths, or with a fill that isn't one of the choices", () => { + expect(() => createCustomGeometryData({}, 10, 10)).to.throw("Invalid custom shape. Expected a path, or at least one of paths"); + expect(() => createCustomGeometryData({ paths: [] }, 10, 10)).to.throw( + "Invalid custom shape. Expected a path, or at least one of paths", + ); + expect(() => createCustomGeometryData({ path: "M 0 0 L 1 1", paths: [{ path: "M 0 0 L 1 1" }] }, 10, 10)).to.throw( + "Invalid custom shape. Expected path or paths, not both", + ); + expect(() => + createCustomGeometryData({ paths: [{ path: "M 0 0 L 1 1", fill: "none" as unknown as boolean }] }, 10, 10), + ).to.throw( + 'Invalid custom shape path fill "none". Expected true, false, "lighter", "slightlyLighter", "darker" or "slightlyDarker"', + ); + expect(() => createCustomGeometryData({ paths: [{ path: "L 1 1" }] }, 10, 10)).to.throw("A path must start with a move (M)"); + }); + }); + + describe("text area", () => { + it("should scale the text area with the paths", () => { + // A speech bubble whose body is the top 70 of its 90 + const geometry = createCustomGeometryData( + { path: "M 0 0 H 100 V 70 H 40 L 20 90 L 25 70 H 0 Z", textArea: { left: 10, top: 0, right: 90, bottom: 70 } }, + 1000, + 900, + ); + expect(geometry.textArea).to.deep.equal({ left: 100, top: 0, right: 900, bottom: 700 }); + expect(createCustomGeometryData({ path: "M 0 0 H 100 V 70 Z" }, 1000, 900).textArea).to.equal(undefined); + }); + + it("should reject a text area that isn't four numbers, or is turned inside out", () => { + const path = "M 0 0 H 100 V 100 Z"; + expect(() => createCustomGeometryData({ path, textArea: { left: 50, top: 0, right: 40, bottom: 10 } }, 10, 10)).to.throw( + 'Invalid text area {"left":50,"top":0,"right":40,"bottom":10}. Expected numbers left, top, right and bottom, with right at least left and bottom at least top', + ); + expect(() => createCustomGeometryData({ path, textArea: { left: 0, top: 50, right: 40, bottom: 10 } }, 10, 10)).to.throw( + "Invalid text area", + ); + expect(() => createCustomGeometryData({ path, textArea: { left: 0, top: 0, right: Number.NaN, bottom: 10 } }, 10, 10)).to.throw( + "Invalid text area", + ); + }); + }); + + describe("connection points", () => { + it("should use the shape's own points instead of the corners, facing the side given or the side they are nearest", () => { + const geometry = createCustomGeometryData( + { + path: "M 0 0 H 100 V 50 H 0 Z", + connectionPoints: [ + { x: 50, y: 0 }, + { x: 100, y: 25 }, + { x: 25, y: 50, side: "left" }, + { x: 50, y: 25, side: "top" }, + ], + }, + 1000, + 500, + ); + expect(geometry.sites).to.deep.equal([ + { x: 500, y: 0, angle: 270 }, + { x: 1000, y: 250, angle: 0 }, + { x: 250, y: 500, angle: 180 }, + { x: 500, y: 250, angle: 270 }, + ]); + expect(createCustomGeometryData({ path: "M 0 0 H 100 V 50 H 0 Z", connectionPoints: [] }, 10, 10).sites).to.deep.equal([]); + }); + + it("should reject a point that isn't a pair of numbers, or faces a side that isn't one of the four", () => { + const path = "M 0 0 H 100 V 100 Z"; + expect(() => createCustomGeometryData({ path, connectionPoints: [{ x: Number.NaN, y: 0 }] }, 10, 10)).to.throw( + 'Invalid connection point {"x":null,"y":0}. Expected numbers x and y, and a side of top, right, bottom or left', + ); + expect(() => createCustomGeometryData({ path, connectionPoints: [{ x: 0, y: Infinity }] }, 10, 10)).to.throw( + "Invalid connection point", + ); + expect(() => + createCustomGeometryData({ path, connectionPoints: [{ x: 0, y: 0, side: "up" as unknown as "top" }] }, 10, 10), + ).to.throw('Invalid connection point {"x":0,"y":0,"side":"up"}'); + }); + }); +}); + +describe("getCustomTextRectangle", () => { + it("should be the text area, or the whole shape without one", () => { + const path = "M 0 0 H 100 V 100 H 0 Z"; + expect(getCustomTextRectangle({ path, textArea: { left: 25, top: 25, right: 75, bottom: 50 } }, 200, 400)).to.deep.equal({ + left: 50, + top: 100, + right: 150, + bottom: 200, + }); + expect(getCustomTextRectangle({ path }, 200, 400)).to.deep.equal({ left: 0, top: 0, right: 200, bottom: 400 }); + }); }); describe("createCustomGeometry", () => { it("should write the path, connection sites and text box in schema order", () => { - const tree = new Formatter().format(createCustomGeometry(createCustomGeometryPath("M 0 0 L 10 0 L 5 10 Z", 1000, 1000))); + const tree = new Formatter().format(createCustomGeometry(createCustomGeometryData({ path: "M 0 0 L 10 0 L 5 10 Z" }, 1000, 1000))); expect(tree).to.deep.equal({ "a:custGeom": [ { "a:avLst": {} }, - { "a:gdLst": {} }, + { + // Each site keeps its share of the shape's width and height, as PowerPoint writes freeforms + "a:gdLst": [ + { "a:gd": { _attr: { name: "connsiteX0", fmla: "*/ 0 w 1000" } } }, + { "a:gd": { _attr: { name: "connsiteY0", fmla: "*/ 0 h 1000" } } }, + { "a:gd": { _attr: { name: "connsiteX1", fmla: "*/ 1000 w 1000" } } }, + { "a:gd": { _attr: { name: "connsiteY1", fmla: "*/ 0 h 1000" } } }, + { "a:gd": { _attr: { name: "connsiteX2", fmla: "*/ 500 w 1000" } } }, + { "a:gd": { _attr: { name: "connsiteY2", fmla: "*/ 1000 h 1000" } } }, + ], + }, { "a:ahLst": {} }, { "a:cxnLst": [ - { "a:cxn": [{ _attr: { ang: 16200000 } }, { "a:pos": { _attr: { x: 0, y: 0 } } }] }, - { "a:cxn": [{ _attr: { ang: 16200000 } }, { "a:pos": { _attr: { x: 1000, y: 0 } } }] }, - { "a:cxn": [{ _attr: { ang: 5400000 } }, { "a:pos": { _attr: { x: 500, y: 1000 } } }] }, + { "a:cxn": [{ _attr: { ang: 16200000 } }, { "a:pos": { _attr: { x: "connsiteX0", y: "connsiteY0" } } }] }, + { "a:cxn": [{ _attr: { ang: 16200000 } }, { "a:pos": { _attr: { x: "connsiteX1", y: "connsiteY1" } } }] }, + { "a:cxn": [{ _attr: { ang: 5400000 } }, { "a:pos": { _attr: { x: "connsiteX2", y: "connsiteY2" } } }] }, ], }, { "a:rect": { _attr: { l: "l", t: "t", r: "r", b: "b" } } }, @@ -230,7 +409,7 @@ describe("createCustomGeometry", () => { it("should write curves and arcs", () => { // The box around the path is 100 by 75, the same size as the shape const tree = new Formatter().format( - createCustomGeometry(createCustomGeometryPath("M 0 50 A 50 50 0 0 1 100 50 Q 50 100 0 50 C 0 0 0 0 0 50", 100, 75)), + createCustomGeometry(createCustomGeometryData({ path: "M 0 50 A 50 50 0 0 1 100 50 Q 50 100 0 50 C 0 0 0 0 0 50" }, 100, 75)), ); const path = tree["a:custGeom"][5]["a:pathLst"][0]["a:path"]; expect(path.slice(2)).to.deep.equal([ @@ -245,4 +424,59 @@ describe("createCustomGeometry", () => { }, ]); }); + + it("should write each path with its fill and line, when they aren't the shape's", () => { + const tree = new Formatter().format( + createCustomGeometry( + createCustomGeometryData( + { + paths: [ + { path: "M 0 0 L 10 0 L 10 10 Z" }, + { path: "M 0 0 L 10 10", fill: false }, + { path: "M 0 10 L 10 10 L 0 0 Z", fill: "darker", line: false }, + ], + }, + 100, + 100, + ), + ), + ); + const paths = tree["a:custGeom"][5]["a:pathLst"]; + expect(paths.map((path: { readonly "a:path": readonly { readonly _attr?: unknown }[] }) => path["a:path"][0]._attr)).to.deep.equal([ + { w: 100, h: 100 }, + { w: 100, h: 100, fill: "none" }, + { w: 100, h: 100, fill: "darken", stroke: false }, + ]); + }); + + it("should write the text area as guides that keep their share of the shape", () => { + const tree = new Formatter().format( + createCustomGeometry( + createCustomGeometryData( + { path: "M 0 0 H 100 V 100 H 0 Z", textArea: { left: 10, top: 20, right: 90, bottom: 70 }, connectionPoints: [] }, + 1000, + 2000, + ), + ), + ); + expect(tree["a:custGeom"][1]).to.deep.equal({ + "a:gdLst": [ + { "a:gd": { _attr: { name: "textAreaLeft", fmla: "*/ 100 w 1000" } } }, + { "a:gd": { _attr: { name: "textAreaTop", fmla: "*/ 400 h 2000" } } }, + { "a:gd": { _attr: { name: "textAreaRight", fmla: "*/ 900 w 1000" } } }, + { "a:gd": { _attr: { name: "textAreaBottom", fmla: "*/ 1400 h 2000" } } }, + ], + }); + expect(tree["a:custGeom"][4]).to.deep.equal({ + "a:rect": { _attr: { l: "textAreaLeft", t: "textAreaTop", r: "textAreaRight", b: "textAreaBottom" } }, + }); + }); + + it("should write a guide as a value in a shape with no width or height", () => { + const tree = new Formatter().format(createCustomGeometry(createCustomGeometryData({ path: "M 0 5 L 10 5" }, 100, 0))); + expect(tree["a:custGeom"][1]["a:gdLst"].slice(0, 2)).to.deep.equal([ + { "a:gd": { _attr: { name: "connsiteX0", fmla: "*/ 0 w 100" } } }, + { "a:gd": { _attr: { name: "connsiteY0", fmla: "val 0" } } }, + ]); + }); }); diff --git a/src/shapes/custom-geometry/custom-geometry.ts b/src/shapes/custom-geometry/custom-geometry.ts index 621c5fc2d9..4842a7c9cb 100644 --- a/src/shapes/custom-geometry/custom-geometry.ts +++ b/src/shapes/custom-geometry/custom-geometry.ts @@ -1,8 +1,9 @@ /** * Custom shapes (`a:custGeom`): polygons and freeform paths drawn from SVG path data. * - * The path is scaled so the box around it fills the shape, then written as DrawingML path commands. - * Every corner and end of the path is a connection site, so connectors can attach to custom shapes. + * A shape has one path or several, each filled and outlined on its own. The box around all the paths is scaled to fill + * the shape, and they are written as DrawingML path commands. Every corner and end of the paths is a connection site, + * unless the shape gives its own connection points, so connectors can attach to custom shapes. * * Reference: ECMA-376 Part 1, 20.1.9.8 custGeom (Custom Geometry) * @@ -11,8 +12,105 @@ // cspell:ignore custGeom import { BuilderElement, type XmlComponent } from "docx"; -import { type EllipticalArc, type PathPoint, type PathSegment, getPathBounds, parseSvgPath, pointOnArc } from "./svg-path"; +import { orientParts } from "./path-holes"; +import { type EllipticalArc, type PathBounds, type PathPoint, type PathSegment, getPathBounds, parseSvgPath, pointOnArc } from "./svg-path"; import type { ConnectionSite } from "../connector/connection-sites"; +import type { ConnectorSide } from "../shape-connector"; + +/** + * How a path of a custom shape is filled: with the shape's `fill` (`true`), not at all (`false`), or with the shape's + * fill made lighter or darker, as Word's preset shapes shade the top of a cube or the inside of a can. + * + * @publicApi + */ +export type CustomShapePathFill = boolean | "lighter" | "slightlyLighter" | "darker" | "slightlyDarker"; + +/** + * One of the paths of a custom shape. Each path is filled with the shape's `fill` and outlined with its `line`, on its + * own, so paths can overlap without cutting holes in each other. + * + * @publicApi + */ +export type CustomShapePath = { + /** SVG path data, such as `"M 0 0 L 100 0 L 50 80 Z"`, in the same units as the shape's other paths */ + readonly path: string; + /** How the path is filled. Default is `true`, the shape's `fill` */ + readonly fill?: CustomShapePathFill; + /** Whether the shape's `line` is drawn along the path. Default is `true` */ + readonly line?: boolean; +}; + +/** + * A box in a custom shape, in the units of its paths. + * + * @publicApi + */ +export type CustomShapeTextArea = { + readonly left: number; + readonly top: number; + readonly right: number; + readonly bottom: number; +}; + +/** + * A point of a custom shape that connectors attach to, in the units of its paths. + * + * @publicApi + */ +export type CustomShapeConnectionPoint = { + readonly x: number; + readonly y: number; + /** + * The side of the shape the point faces. Connectors leave the point towards it, and a connector's end with this + * `side` attaches here. Default is the side the point is nearest, as a share of the shape's width and height + */ + readonly side?: ConnectorSide; +}; + +/** + * The outline of a custom shape, and where its text and connection points go. + * + * @publicApi + */ +export type CustomShapeGeometry = { + /** + * Where the text goes, in the units of the paths, such as the body of a speech bubble without its tail. Default is + * the whole shape + */ + readonly textArea?: CustomShapeTextArea; + /** + * The points connectors attach to, in the units of the paths. Default is every corner and end of the paths + */ + readonly connectionPoints?: readonly CustomShapeConnectionPoint[]; +} & ( + | { + /** + * The outline of the shape as SVG path data, such as `"M 0 0 L 100 0 L 50 80 Z"` for a triangle. + * It can use the commands M, L, H, V, C, S, Q, T, A and Z, in any units: the path is scaled so the + * box around it fills the shape. A closed part of the path inside another part is a hole in it + */ + readonly path: string; + readonly paths?: undefined; + } + | { + /** + * Several paths, in the same units, each with its own fill and line. The box around all of them is scaled to + * fill the shape. Later paths are drawn over earlier ones + */ + readonly paths: readonly CustomShapePath[]; + readonly path?: undefined; + } +); + +/** + * A custom shape's geometry options, as the shape's options give them. + */ +export type CustomGeometryOptions = { + readonly path?: string; + readonly paths?: readonly CustomShapePath[]; + readonly textArea?: CustomShapeTextArea; + readonly connectionPoints?: readonly CustomShapeConnectionPoint[]; +}; /** * A segment of a custom shape's path, in whole EMUs from the top-left corner of the shape. @@ -33,16 +131,43 @@ export type CustomPathSegment = | { readonly type: "close" }; /** - * A custom shape's path, scaled to the shape, and its connection sites. + * How a path is filled, as DrawingML names it (`ST_PathFillMode`). The shape's fill is `"norm"`, the default. + */ +type PathFillMode = "none" | "norm" | "lighten" | "lightenLess" | "darken" | "darkenLess"; + +/** + * One of a custom shape's paths, scaled to the shape. + */ +export type CustomGeometryPath = { + readonly segments: readonly CustomPathSegment[]; + readonly fill: PathFillMode; + /** Whether the shape's line is drawn along the path */ + readonly stroke: boolean; +}; + +/** + * A box in a shape, in EMUs from its top-left corner. + */ +export type CustomGeometryBox = { + readonly left: number; + readonly top: number; + readonly right: number; + readonly bottom: number; +}; + +/** + * A custom shape's paths, scaled to the shape, its connection sites and where its text goes. */ export type CustomGeometry = { - /** The shape's width in EMUs, which the path is drawn in */ + /** The shape's width in EMUs, which the paths are drawn in */ readonly width: number; - /** The shape's height in EMUs, which the path is drawn in */ + /** The shape's height in EMUs, which the paths are drawn in */ readonly height: number; - readonly segments: readonly CustomPathSegment[]; - /** The corners and ends of the path, in the order they are drawn */ + readonly paths: readonly CustomGeometryPath[]; + /** The shape's connection points, or the corners and ends of its paths in the order they are drawn */ readonly sites: readonly ConnectionSite[]; + /** Where the text goes. Without it, the text uses the whole shape */ + readonly textArea?: CustomGeometryBox; }; const ANGLE_UNITS_PER_DEGREE = 60000; @@ -177,7 +302,7 @@ export const outwardAngle = (x: number, y: number, width: number, height: number }; /** - * The corners and ends of a path: where each of its segments ends. A connector leaves each one in the direction, + * The corners and ends of the paths: where each of their segments ends. A connector leaves each one in the direction, * right, down, left or up, that it is furthest from the middle of the shape in. */ const findSites = (segments: readonly PathSegment[], scale: Scale, width: number, height: number): readonly ConnectionSite[] => { @@ -186,17 +311,107 @@ const findSites = (segments: readonly PathSegment[], scale: Scale, width: number return unique.map(({ x, y }) => ({ x, y, angle: outwardAngle(x, y, width, height) })); }; +const SIDE_ANGLES: Readonly> = { right: 0, bottom: 90, left: 180, top: 270 }; + /** - * Reads SVG path data and scales it to a shape: the box around the path is stretched to fill the shape's box. + * The shape's own connection points, scaled to the shape. + * + * @throws If a point isn't a pair of numbers, or its side isn't one of the four + */ +const connectionSites = ( + points: readonly CustomShapeConnectionPoint[], + scale: Scale, + width: number, + height: number, +): readonly ConnectionSite[] => + points.map((point) => { + const { x, y, side } = point; + if (!Number.isFinite(x) || !Number.isFinite(y) || (side !== undefined && SIDE_ANGLES[side] === undefined)) { + throw new Error( + `Invalid connection point ${JSON.stringify(point)}. Expected numbers x and y, and a side of top, right, bottom or left`, + ); + } + const site = round(toShape(scale, { x, y })); + return { ...site, angle: side === undefined ? outwardAngle(site.x, site.y, width, height) : SIDE_ANGLES[side] }; + }); + +/* cspell:disable */ +const PATH_FILLS: ReadonlyMap = new Map([ + [true, "norm"], + [false, "none"], + ["lighter", "lighten"], + ["slightlyLighter", "lightenLess"], + ["darker", "darken"], + ["slightlyDarker", "darkenLess"], +]); +/* cspell:enable */ + +type ReadPath = { + readonly segments: readonly PathSegment[]; + readonly fill: PathFillMode; + readonly stroke: boolean; +}; + +/** + * Reads a custom shape's paths. Parts of a path inside other parts are turned round to go the other way, so they are + * holes whichever way applications fill paths. + * + * @throws If there is no path, both `path` and `paths`, a path isn't valid SVG path data, or a fill isn't one of the choices + */ +const readPaths = ({ path, paths }: CustomGeometryOptions): readonly ReadPath[] => { + if (path !== undefined && paths !== undefined) { + throw new Error("Invalid custom shape. Expected path or paths, not both"); + } + const options = paths ?? (path === undefined ? [] : [{ path }]); + if (options.length === 0) { + throw new Error("Invalid custom shape. Expected a path, or at least one of paths"); + } + return options.map(({ path: data, fill = true, line }) => { + const mode = PATH_FILLS.get(fill); + if (mode === undefined) { + throw new Error( + `Invalid custom shape path fill "${fill}". Expected true, false, "lighter", "slightlyLighter", "darker" or "slightlyDarker"`, + ); + } + return { segments: orientParts(parseSvgPath(data)), fill: mode, stroke: line !== false }; + }); +}; + +const unionOf = (bounds: readonly PathBounds[]): PathBounds => ({ + left: Math.min(...bounds.map(({ left }) => left)), + top: Math.min(...bounds.map(({ top }) => top)), + right: Math.max(...bounds.map(({ right }) => right)), + bottom: Math.max(...bounds.map(({ bottom }) => bottom)), +}); + +/** + * Where the text goes, scaled to the shape. + * + * @throws If the box's sides aren't numbers, or it is turned inside out + */ +const scaleTextArea = (textArea: CustomShapeTextArea, scale: Scale): CustomGeometryBox => { + const { left, top, right, bottom } = textArea; + if (![left, top, right, bottom].every(Number.isFinite) || right < left || bottom < top) { + throw new Error( + `Invalid text area ${JSON.stringify(textArea)}. Expected numbers left, top, right and bottom, with right at least left and bottom at least top`, + ); + } + const topLeft = round(toShape(scale, { x: left, y: top })); + const bottomRight = round(toShape(scale, { x: right, y: bottom })); + return { left: topLeft.x, top: topLeft.y, right: bottomRight.x, bottom: bottomRight.y }; +}; + +/** + * Reads a custom shape's paths and scales them to the shape: the box around them is stretched to fill the shape's box. + * The text area and connection points are scaled with them. * - * @param path - SVG path data, such as `"M 0 0 L 100 0 L 50 80 Z"`, in any units * @param width - The shape's width in EMUs * @param height - The shape's height in EMUs - * @throws If the path is not valid SVG path data + * @throws If the paths, text area or connection points aren't valid */ -export const createCustomGeometryPath = (path: string, width: number, height: number): CustomGeometry => { - const segments = parseSvgPath(path); - const bounds = getPathBounds(segments); +export const createCustomGeometryData = (options: CustomGeometryOptions, width: number, height: number): CustomGeometry => { + const paths = readPaths(options); + const bounds = unionOf(paths.map(({ segments }) => getPathBounds(segments))); const pathWidth = bounds.right - bounds.left; const pathHeight = bounds.bottom - bounds.top; const x = pathWidth > 0 ? width / pathWidth : 0; @@ -206,11 +421,33 @@ export const createCustomGeometryPath = (path: string, width: number, height: nu return { width, height, - segments: segments.flatMap((segment) => convertSegment(segment, scale)), - sites: findSites(segments, scale, width, height), + paths: paths.map(({ segments, fill, stroke }) => ({ + segments: segments.flatMap((segment) => convertSegment(segment, scale)), + fill, + stroke, + })), + sites: + options.connectionPoints === undefined + ? findSites( + paths.flatMap(({ segments }) => segments), + scale, + width, + height, + ) + : connectionSites(options.connectionPoints, scale, width, height), + textArea: options.textArea && scaleTextArea(options.textArea, scale), }; }; +/** + * The box a custom shape of the given size writes its text in: its text area, or the whole shape. + * + * @param width - The shape's width in EMUs + * @param height - The shape's height in EMUs + */ +export const getCustomTextRectangle = (options: CustomGeometryOptions, width: number, height: number): CustomGeometryBox => + (options.textArea && createCustomGeometryData(options, width, height).textArea) ?? { left: 0, top: 0, right: width, bottom: height }; + const createPoint = ({ x, y }: PathPoint): XmlComponent => new BuilderElement({ name: "a:pt", @@ -245,28 +482,78 @@ const createPathSegment = (segment: CustomPathSegment): XmlComponent => { } }; +/** + * A shape geometry guide (`a:gd`): a named value worked out from a formula. + */ +type Guide = { readonly name: string; readonly formula: string }; + +/** + * A guide for a length across or down the shape that keeps its share of the shape's width or height when the shape is + * resized, as PowerPoint writes the points of freeforms: the length times `w` (or `h`), divided by the width (or height) + * it was worked out for. + */ +const shareGuide = (name: string, value: number, size: "w" | "h", length: number): Guide => ({ + name, + formula: length === 0 ? `val ${value}` : `*/ ${value} ${size} ${length}`, +}); + +const createGuide = ({ name, formula }: Guide): XmlComponent => + new BuilderElement<{ readonly name: string; readonly formula: string }>({ + name: "a:gd", + attributes: { name: { key: "name", value: name }, formula: { key: "fmla", value: formula } }, + }); + +/* cspell:disable */ +const siteGuides = (sites: readonly ConnectionSite[], width: number, height: number): readonly Guide[] => + sites.flatMap(({ x, y }, index) => [shareGuide(`connsiteX${index}`, x, "w", width), shareGuide(`connsiteY${index}`, y, "h", height)]); + // // // // // // -const createConnectionSite = ({ x, y, angle }: ConnectionSite): XmlComponent => +const createConnectionSite = ({ angle }: ConnectionSite, index: number): XmlComponent => new BuilderElement<{ readonly angle: number }>({ name: "a:cxn", attributes: { angle: { key: "ang", value: Math.round(angle * ANGLE_UNITS_PER_DEGREE) } }, children: [ - new BuilderElement({ + new BuilderElement<{ readonly x: string; readonly y: string }>({ name: "a:pos", - attributes: { x: { key: "x", value: x }, y: { key: "y", value: y } }, + attributes: { x: { key: "x", value: `connsiteX${index}` }, y: { key: "y", value: `connsiteY${index}` } }, }), ], }); +/* cspell:enable */ + +const textAreaGuides = (textArea: CustomGeometryBox | undefined, width: number, height: number): readonly Guide[] => + textArea === undefined + ? [] + : [ + shareGuide("textAreaLeft", textArea.left, "w", width), + shareGuide("textAreaTop", textArea.top, "h", height), + shareGuide("textAreaRight", textArea.right, "w", width), + shareGuide("textAreaBottom", textArea.bottom, "h", height), + ]; + +const createPath = (path: CustomGeometryPath, width: number, height: number): XmlComponent => + new BuilderElement<{ readonly width: number; readonly height: number; readonly fill?: PathFillMode; readonly stroke?: boolean }>({ + name: "a:path", + attributes: { + width: { key: "w", value: width }, + height: { key: "h", value: height }, + // Only what differs from the defaults is written + fill: { key: "fill", value: path.fill === "norm" ? undefined : path.fill }, + stroke: { key: "stroke", value: path.stroke ? undefined : false }, + }, + children: path.segments.map(createPathSegment), + }); /** * Creates an `a:custGeom` element for a custom shape. * - * The text in the shape uses the whole of its box (`a:rect`). + * The connection sites and text area are guides that keep their share of the shape's width and height, so they stay + * in place when the shape is resized. Without a text area, the text uses the whole of the shape's box. * * ## XSD Schema * ```xml @@ -282,35 +569,33 @@ const createConnectionSite = ({ x, y, angle }: ConnectionSite): XmlComponent => * * ``` */ -export const createCustomGeometry = ({ width, height, segments, sites }: CustomGeometry): XmlComponent => +export const createCustomGeometry = ({ width, height, paths, sites, textArea }: CustomGeometry): XmlComponent => new BuilderElement({ name: "a:custGeom", children: [ new BuilderElement({ name: "a:avLst" }), - new BuilderElement({ name: "a:gdLst" }), + new BuilderElement({ + name: "a:gdLst", + children: [...siteGuides(sites, width, height), ...textAreaGuides(textArea, width, height)].map(createGuide), + }), new BuilderElement({ name: "a:ahLst" }), new BuilderElement({ name: "a:cxnLst", children: sites.map(createConnectionSite) }), new BuilderElement<{ readonly left: string; readonly top: string; readonly right: string; readonly bottom: string }>({ name: "a:rect", - attributes: { - left: { key: "l", value: "l" }, - top: { key: "t", value: "t" }, - right: { key: "r", value: "r" }, - bottom: { key: "b", value: "b" }, - }, - }), - new BuilderElement({ - name: "a:pathLst", - children: [ - new BuilderElement<{ readonly width: number; readonly height: number }>({ - name: "a:path", - attributes: { - width: { key: "w", value: width }, - height: { key: "h", value: height }, - }, - children: segments.map(createPathSegment), - }), - ], + attributes: textArea + ? { + left: { key: "l", value: "textAreaLeft" }, + top: { key: "t", value: "textAreaTop" }, + right: { key: "r", value: "textAreaRight" }, + bottom: { key: "b", value: "textAreaBottom" }, + } + : { + left: { key: "l", value: "l" }, + top: { key: "t", value: "t" }, + right: { key: "r", value: "r" }, + bottom: { key: "b", value: "b" }, + }, }), + new BuilderElement({ name: "a:pathLst", children: paths.map((path) => createPath(path, width, height)) }), ], }); diff --git a/src/shapes/custom-geometry/path-holes.spec.ts b/src/shapes/custom-geometry/path-holes.spec.ts new file mode 100644 index 0000000000..18f8db9e23 --- /dev/null +++ b/src/shapes/custom-geometry/path-holes.spec.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; + +import { orientParts } from "./path-holes"; +import { type PathSegment, parseSvgPath, pointOnArc } from "./svg-path"; + +const oriented = (path: string): readonly PathSegment[] => orientParts(parseSvgPath(path)); + +// Squares 100, 50 and 20 wide around the same middle, clockwise on the page, and the same squares anticlockwise +const OUTER = "M 0 0 H 100 V 100 H 0 Z"; +const MIDDLE = "M 25 25 H 75 V 75 H 25 Z"; +const INNER = "M 40 40 H 60 V 60 H 40 Z"; +const MIDDLE_ANTICLOCKWISE = "M 25 25 V 75 H 75 V 25 Z"; + +describe("orientParts", () => { + it("should turn round a part inside another that goes the same way, starting where it did", () => { + expect(oriented(`${OUTER} ${MIDDLE}`)).to.deep.equal([ + ...parseSvgPath(OUTER), + { type: "move", to: { x: 25, y: 25 } }, + { type: "line", to: { x: 25, y: 75 } }, + { type: "line", to: { x: 75, y: 75 } }, + { type: "line", to: { x: 75, y: 25 } }, + { type: "close" }, + ]); + }); + + it("should leave parts that already go the other way, and parts that aren't inside another", () => { + expect(oriented(`${OUTER} ${MIDDLE_ANTICLOCKWISE}`)).to.deep.equal(parseSvgPath(`${OUTER} ${MIDDLE_ANTICLOCKWISE}`)); + // Two squares side by side + const apart = "M 0 0 H 10 V 10 H 0 Z M 20 0 H 30 V 10 H 20 Z"; + expect(oriented(apart)).to.deep.equal(parseSvgPath(apart)); + }); + + it("should fill a part inside a hole again, going the same way as the outline", () => { + const segments = oriented(`${OUTER} ${MIDDLE} ${INNER}`); + // The middle square is turned round, and the inner square goes the other way to it, as it was drawn + expect(segments.slice(5, 10)).to.deep.equal(oriented(`${OUTER} ${MIDDLE}`).slice(5)); + expect(segments.slice(10)).to.deep.equal(parseSvgPath(INNER)); + }); + + it("should find the part a part is directly inside, whatever order the parts are in", () => { + const segments = oriented(`${MIDDLE} ${OUTER} ${INNER}`); + expect(segments.slice(0, 5)).to.deep.equal(oriented(`${OUTER} ${MIDDLE}`).slice(5)); + expect(segments.slice(5)).to.deep.equal(parseSvgPath(`${OUTER} ${INNER}`)); + }); + + it("should close a part that doesn't end where it starts with a line from its end", () => { + // The triangle's last side is drawn by the close + expect(oriented(`${OUTER} M 25 25 L 75 25 L 50 75 Z`).slice(5)).to.deep.equal([ + { type: "move", to: { x: 25, y: 25 } }, + { type: "line", to: { x: 50, y: 75 } }, + { type: "line", to: { x: 75, y: 25 } }, + { type: "close" }, + ]); + // The triangle's last side is drawn, and the close has nothing left to draw + expect(oriented(`${OUTER} M 25 25 L 75 25 L 50 75 L 25 25 Z`).slice(5)).to.deep.equal([ + { type: "move", to: { x: 25, y: 25 } }, + { type: "line", to: { x: 50, y: 75 } }, + { type: "line", to: { x: 75, y: 25 } }, + { type: "close" }, + ]); + }); + + it("should draw curves backwards", () => { + expect(oriented(`${OUTER} M 30 30 C 50 20 70 20 70 30 Q 80 50 70 70 L 30 70 Z`).slice(5)).to.deep.equal([ + { type: "move", to: { x: 30, y: 30 } }, + { type: "line", to: { x: 30, y: 70 } }, + { type: "line", to: { x: 70, y: 70 } }, + { type: "quadratic", control: { x: 80, y: 50 }, to: { x: 70, y: 30 } }, + { type: "cubic", control1: { x: 70, y: 20 }, control2: { x: 50, y: 20 }, to: { x: 30, y: 30 } }, + { type: "close" }, + ]); + }); + + it("should draw arcs backwards, along the same ellipse", () => { + // A circle, clockwise, in two halves + const segments = oriented(`${OUTER} M 30 50 A 20 20 0 0 1 70 50 A 20 20 0 0 1 30 50 Z`).slice(5); + expect(segments.map(({ type }) => type)).to.deep.equal(["move", "arc", "arc", "close"]); + const arcs = segments.flatMap((segment) => (segment.type === "arc" ? [segment] : [])); + expect(arcs.map(({ from, to }) => [from, to])).to.deep.equal([ + [ + { x: 30, y: 50 }, + { x: 70, y: 50 }, + ], + [ + { x: 70, y: 50 }, + { x: 30, y: 50 }, + ], + ]); + for (const { from, to, arc } of arcs) { + expect(arc.sweepAngle).to.be.closeTo(-Math.PI, 1e-9); + expect(pointOnArc(arc, arc.startAngle).x).to.be.closeTo(from.x, 1e-9); + expect(pointOnArc(arc, arc.startAngle + arc.sweepAngle).x).to.be.closeTo(to.x, 1e-9); + } + }); + + it("should leave a part that isn't closed, and turn a closed part inside it the other way to it", () => { + const open = `${OUTER} M 25 25 H 75 V 75 H 25`; + expect(oriented(open)).to.deep.equal(parseSvgPath(open)); + // A part that goes on after it is closed can't be turned round either + const continued = `${OUTER} ${MIDDLE} L 50 50`; + expect(oriented(continued)).to.deep.equal(parseSvgPath(continued)); + + expect(oriented(`M 0 0 H 100 V 100 H 0 ${MIDDLE}`).slice(4)).to.deep.equal(oriented(`${OUTER} ${MIDDLE}`).slice(5)); + }); + + it("should leave parts that enclose nothing, and not count them as holding other parts", () => { + const path = `${OUTER} M 25 50 H 75 M 20 0 L 20 100`; + expect(oriented(path)).to.deep.equal(parseSvgPath(path)); + }); +}); diff --git a/src/shapes/custom-geometry/path-holes.ts b/src/shapes/custom-geometry/path-holes.ts new file mode 100644 index 0000000000..fce9ae53b5 --- /dev/null +++ b/src/shapes/custom-geometry/path-holes.ts @@ -0,0 +1,177 @@ +/** + * Holes in custom shapes: a closed part of a path inside another part is a hole in it, and a part inside a hole is + * filled again. + * + * Applications fill a path by one of two rules. By the even-odd rule, as LibreOffice fills, a part inside another is + * always a hole. By the non-zero rule, it is a hole only if it goes round the other way. So each closed part is turned + * round, where it needs to be, to go the other way to the part it is in, and the rules agree. + * + * @module + */ +import { type PathPoint, type PathSegment, cubicAt, pointOnArc, quadraticAt } from "./svg-path"; + +// How many straight steps a curve is measured with +const CURVE_STEPS = 8; + +type DrawnSegment = Exclude; + +/** + * A part of a path: where its move goes to, and the segments after it, up to the next move. + */ +type Part = { + readonly start: PathPoint; + readonly segments: readonly PathSegment[]; +}; + +type MeasuredPart = Part & { + /** The part's outline, with curves as straight steps */ + readonly outline: readonly PathPoint[]; + /** Positive if the part goes clockwise on the page, negative if anticlockwise, and 0 if it encloses nothing */ + readonly turn: number; + /** Whether the part can be turned round: it is closed once, at its end */ + readonly closed: boolean; +}; + +const steps = (point: (t: number) => PathPoint): readonly PathPoint[] => + Array.from({ length: CURVE_STEPS }, (_, index) => point((index + 1) / CURVE_STEPS)); + +/** + * The points a segment passes through, after where it starts. A close goes back to the start of the part. + */ +const outlineOf = (segment: PathSegment, from: PathPoint, start: PathPoint): readonly PathPoint[] => { + switch (segment.type) { + case "cubic": { + const { control1: c1, control2: c2, to } = segment; + return steps((t) => ({ x: cubicAt(from.x, c1.x, c2.x, to.x, t), y: cubicAt(from.y, c1.y, c2.y, to.y, t) })); + } + case "quadratic": { + const { control, to } = segment; + return steps((t) => ({ x: quadraticAt(from.x, control.x, to.x, t), y: quadraticAt(from.y, control.y, to.y, t) })); + } + case "arc": { + const { arc } = segment; + return steps((t) => pointOnArc(arc, arc.startAngle + arc.sweepAngle * t)); + } + case "close": + return [start]; + default: + return [segment.to]; + } +}; + +// Twice the area a closed outline encloses, positive when it goes clockwise on the page (y down) +const signedArea = (outline: readonly PathPoint[]): number => + outline.reduce((total, point, index) => { + const next = outline[(index + 1) % outline.length]; + return total + point.x * next.y - next.x * point.y; + }, 0); + +const measurePart = (part: Part): MeasuredPart => { + const { start, segments } = part; + const outline = segments.reduce( + (points, segment) => [...points, ...outlineOf(segment, points[points.length - 1], start)], + [start], + ); + const area = signedArea(outline); + return { + ...part, + outline, + turn: Math.abs(area) < 1e-9 ? 0 : Math.sign(area), + closed: segments.filter(({ type }) => type === "close").length === 1 && segments[segments.length - 1].type === "close", + }; +}; + +/** + * Splits a path into its parts. A path starts with a move, and each move starts a part. + */ +const splitParts = (segments: readonly PathSegment[]): readonly Part[] => + segments.reduce((parts, segment) => { + if (segment.type === "move") { + return [...parts, { start: segment.to, segments: [] }]; + } + const last = parts[parts.length - 1]; + return [...parts.slice(0, -1), { ...last, segments: [...last.segments, segment] }]; + }, []); + +// Whether a point is inside an outline: a line from the point to the right crosses its sides an odd number of times +const isPointInside = ({ x, y }: PathPoint, outline: readonly PathPoint[]): boolean => + outline.reduce((inside, point, index) => { + const previous = outline[(index + outline.length - 1) % outline.length]; + const crosses = point.y > y !== previous.y > y && x < ((previous.x - point.x) * (y - point.y)) / (previous.y - point.y) + point.x; + return crosses ? !inside : inside; + }, false); + +// A part is inside another when most of its outline is. Points on the other part's outline can count either way +const isInside = (part: MeasuredPart, other: MeasuredPart): boolean => + part.outline.filter((point) => isPointInside(point, other.outline)).length > part.outline.length / 2; + +const hasEnd = (segment: PathSegment): segment is DrawnSegment => segment.type !== "close"; + +const reverseSegment = (segment: DrawnSegment, from: PathPoint): PathSegment => { + switch (segment.type) { + case "cubic": + return { type: "cubic", control1: segment.control2, control2: segment.control1, to: from }; + case "quadratic": + return { type: "quadratic", control: segment.control, to: from }; + case "arc": { + const { arc } = segment; + return { + type: "arc", + from: segment.to, + to: from, + arc: { ...arc, startAngle: arc.startAngle + arc.sweepAngle, sweepAngle: -arc.sweepAngle }, + }; + } + default: + return { type: "line", to: from }; + } +}; + +/** + * A closed part drawn the other way round. It starts where it did, and each segment is drawn backwards. + */ +const reversePart = ({ start, segments }: Part): readonly PathSegment[] => { + const drawn = segments.filter(hasEnd); + // Where each segment starts, and last, where the part ends before it is closed + const starts = [start, ...drawn.map(({ to }) => to)]; + const end = starts[starts.length - 1]; + // The line that closed the part, from its end back to its start, is drawn first + const closing: readonly PathSegment[] = end.x === start.x && end.y === start.y ? [] : [{ type: "line", to: end }]; + const backwards = drawn.reduceRight( + (result, segment, index) => [...result, reverseSegment(segment, starts[index])], + [], + ); + // The first segment, drawn backwards, ends the part. When it is a line, the close draws it + const ending = drawn[0].type === "line" ? backwards.slice(0, -1) : backwards; + return [{ type: "move", to: start }, ...closing, ...ending, { type: "close" }]; +}; + +/** + * Turns round the closed parts of a path that go the same way as the part they are directly inside, so that a part + * inside another is a hole in it whichever rule an application fills paths by. Parts that aren't inside another, and + * parts that aren't closed, are left as they are. + * + * @param segments - A path, starting with a move + */ +export const orientParts = (segments: readonly PathSegment[]): readonly PathSegment[] => { + const parts = splitParts(segments).map(measurePart); + const containers = parts.map((part, index) => + parts.flatMap((other, otherIndex) => (otherIndex !== index && other.turn !== 0 && isInside(part, other) ? [otherIndex] : [])), + ); + const depths = containers.map(({ length }) => length); + + // The way a part goes once turned round: the other way to the part it is directly inside, the deepest one it is in + const turnOf = (index: number): number => { + const parent = containers[index] + .filter((container) => depths[container] < depths[index]) + .reduce( + (deepest, container) => (deepest === undefined || depths[container] > depths[deepest] ? container : deepest), + undefined, + ); + return parent === undefined || !parts[index].closed ? parts[index].turn : -turnOf(parent); + }; + + return parts.flatMap((part, index) => + part.turn !== 0 && turnOf(index) !== part.turn ? reversePart(part) : [{ type: "move", to: part.start } as const, ...part.segments], + ); +}; diff --git a/src/shapes/custom-geometry/svg-path.ts b/src/shapes/custom-geometry/svg-path.ts index 8b3caa43ea..cb267a2fa4 100644 --- a/src/shapes/custom-geometry/svg-path.ts +++ b/src/shapes/custom-geometry/svg-path.ts @@ -301,10 +301,16 @@ const bezierTurningPoints = (coefficients: readonly [number, number, number]): r return [(-b + root) / (2 * a), (-b - root) / (2 * a)]; }; -const cubicAt = (p0: number, p1: number, p2: number, p3: number, t: number): number => +/** + * A cubic Bézier curve's position along one axis at `t`, from 0 to 1. + */ +export const cubicAt = (p0: number, p1: number, p2: number, p3: number, t: number): number => (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * p1 + 3 * (1 - t) * t * t * p2 + t ** 3 * p3; -const quadraticAt = (p0: number, p1: number, p2: number, t: number): number => (1 - t) ** 2 * p0 + 2 * (1 - t) * t * p1 + t * t * p2; +/** + * A quadratic Bézier curve's position along one axis at `t`, from 0 to 1. + */ +export const quadraticAt = (p0: number, p1: number, p2: number, t: number): number => (1 - t) ** 2 * p0 + 2 * (1 - t) * t * p1 + t * t * p2; const isWithin = (t: number): boolean => t > 0 && t < 1; diff --git a/src/shapes/preset-shape/preset-shape-properties.ts b/src/shapes/preset-shape/preset-shape-properties.ts index ab80919f22..70e99e157b 100644 --- a/src/shapes/preset-shape/preset-shape-properties.ts +++ b/src/shapes/preset-shape/preset-shape-properties.ts @@ -10,7 +10,7 @@ import { createShapeGuides } from "./shape-adjustments"; import { type ShapeEffects, createShapeEffects } from "./shape-effects"; import { type ShapeFill, createShapeFill } from "./shape-fill"; import { type ShapeLine, createShapeLine } from "./shape-line"; -import { createCustomGeometry, createCustomGeometryPath } from "../custom-geometry/custom-geometry"; +import { type CustomGeometryOptions, createCustomGeometry, createCustomGeometryData } from "../custom-geometry/custom-geometry"; import { createPresetGeometry, createTransform } from "../drawing/drawing-parts"; /** @@ -22,11 +22,10 @@ export type PresetShapeGeometry = /** The shape's adjustments, such as `{ cornerRadius: 25 }` for a `"roundedRectangle"` */ readonly adjustments?: Readonly>; } - | { + | (CustomGeometryOptions & { + /** A custom shape, drawn from SVG path data scaled to fill the shape */ readonly type: "custom"; - /** SVG path data, such as `"M 0 0 L 100 0 L 50 80 Z"`, scaled to fill the shape */ - readonly path: string; - }; + }); export type PresetShapePropertiesOptions = { readonly transformation: IMediaDataTransformation; @@ -65,7 +64,7 @@ export const createPresetShapeProperties = ({ children: [ createTransform(transformation), geometry.type === "custom" - ? createCustomGeometry(createCustomGeometryPath(geometry.path, transformation.emus.x, transformation.emus.y)) + ? createCustomGeometry(createCustomGeometryData(geometry, transformation.emus.x, transformation.emus.y)) : createPresetGeometry(getOoxmlShapeName(geometry.type), createShapeGuides(geometry.type, geometry.adjustments)), createShapeFill(fill), createShapeLine(line), diff --git a/src/shapes/shape-drawing.spec.ts b/src/shapes/shape-drawing.spec.ts index e3af88933f..220e59d5bb 100644 --- a/src/shapes/shape-drawing.spec.ts +++ b/src/shapes/shape-drawing.spec.ts @@ -557,6 +557,52 @@ describe("layoutShapeDrawing", () => { expect(sitesOf(children[2])[0]).to.equal(1); }); + it("should connect to a custom shape's own connection points, by side or by the point nearest", () => { + // A cylinder, with points at the middle of its top, bottom and sides + const cylinder = { + id: "c", + type: "custom", + paths: [ + { path: "M 0 10 A 50 10 0 0 1 100 10 V 90 A 50 10 0 0 1 0 90 Z" }, + { path: "M 0 10 A 50 10 0 0 0 100 10", fill: false }, + ], + connectionPoints: [ + { x: 50, y: 0 }, + { x: 100, y: 50 }, + { x: 50, y: 100 }, + { x: 0, y: 50, side: "left" }, + ], + transformation: { offset: { left: 0, top: 0 }, width: 100, height: 100 }, + } as IShapeGroupChildOptions; + const { children } = layoutShapeDrawing([ + cylinder, + box("below", 0, 300), + box("left", -300, 25), + connect("c", "below"), + connect({ id: "c", side: "left" }, "left"), + connect({ id: "c", point: { x: 90, y: 60 } }, "below"), + ]); + expect(sitesOf(children[3])[0]).to.equal(2); + expect(sitesOf(children[4])[0]).to.equal(3); + expect(sitesOf(children[5])[0]).to.equal(1); + }); + + it("should end connectors at the middle of a side of a custom shape without connection points", () => { + const { children } = layoutShapeDrawing([ + { + id: "t", + type: "custom", + path: "M 50 0 L 100 100 L 0 100 Z", + connectionPoints: [], + transformation: { width: 100, height: 100 }, + }, + box("a", 0, 300), + connect("t", "a"), + ] as readonly IShapeGroupChildOptions[]); + expect(sitesOf(children[2])).to.deep.equal([undefined, 0]); + expect(endsOf(children[2])[0]).to.deep.equal([50, 100]); + }); + describe("text", () => { it("should size a shape to fit its text, and write the text as centred paragraphs", () => { const { children } = layoutShapeDrawing([ @@ -1152,7 +1198,7 @@ describe("connectors that need more bends than the presets have", () => { 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.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+$/); diff --git a/src/shapes/shape-drawing.ts b/src/shapes/shape-drawing.ts index 03da036c48..6ebc01d715 100644 --- a/src/shapes/shape-drawing.ts +++ b/src/shapes/shape-drawing.ts @@ -29,7 +29,7 @@ import { routeConnector, separateChannels, } from "./connector"; -import { createCustomGeometryPath, outwardAngle } from "./custom-geometry"; +import { createCustomGeometryData, outwardAngle } from "./custom-geometry"; import type { ShapeDrawingChildMediaData } from "./drawing/shape-drawing-child"; import type { ImageSource } from "./picture/image-data"; import type { ShapePictureCoreOptions } from "./picture/shape-picture"; @@ -444,7 +444,7 @@ const straightSidesOf = (options: ShapeChildOptions, width: number, height: numb const shapeSites = (options: ShapeChildOptions, width: number, height: number): readonly LocalSite[] => { const sites = options.type === "custom" - ? createCustomGeometryPath(options.path, width, height).sites + ? createCustomGeometryData(options, width, height).sites : getConnectionSites(options.type, width, height, createShapeGuides(options.type, options.adjustments)); return sites.map((site, index) => ({ ...site, index })); }; diff --git a/src/shapes/shape-run-data.ts b/src/shapes/shape-run-data.ts index 03388b837e..89dfb148b9 100644 --- a/src/shapes/shape-run-data.ts +++ b/src/shapes/shape-run-data.ts @@ -13,6 +13,7 @@ import { docPropertiesUniqueNumericId, } from "docx"; +import type { CustomShapeGeometry } from "./custom-geometry"; import { type PresetShapeCoreOptions, type PresetShapeType, @@ -57,7 +58,7 @@ export type ShapeBaseOptions = DrawingLinkOptions & { * * There is one member per preset shape, so `adjustments` only accepts the names of that shape's handles. * Another member takes any shape type without adjustments, for when the type is only known at runtime, - * and the last one is a custom shape drawn from a `path`. + * and the last one is a custom shape drawn from a `path` or `paths`. */ export type WithPresetShape = | { @@ -69,17 +70,12 @@ export type WithPresetShape = }; }[PresetShapeType] | (Options & { readonly type: PresetShapeType; readonly adjustments?: undefined }) - | (Options & { - /** A shape of your own, drawn from `path` */ - readonly type: "custom"; - /** - * The outline of the shape as SVG path data, such as `"M 0 0 L 100 0 L 50 80 Z"` for a triangle. - * It can use the commands M, L, H, V, C, S, Q, T, A and Z, in any units: the path is scaled so the - * box around it fills the shape - */ - readonly path: string; - readonly adjustments?: undefined; - }); + | (Options & + CustomShapeGeometry & { + /** A shape of your own, drawn from `path` or `paths` */ + readonly type: "custom"; + readonly adjustments?: undefined; + }); /** * Maps shape options to the data used to write a `wps:wsp` element. @@ -87,7 +83,16 @@ export type WithPresetShape = * @param styles - The document's styles, which `text` is written to suit */ export const createPresetShapeData = (options: WithPresetShape, styles?: TextStyles): PresetShapeCoreOptions => ({ - geometry: options.type === "custom" ? { type: "custom", path: options.path } : { type: options.type, adjustments: options.adjustments }, + geometry: + options.type === "custom" + ? { + type: "custom", + path: options.path, + paths: options.paths, + textArea: options.textArea, + connectionPoints: options.connectionPoints, + } + : { type: options.type, adjustments: options.adjustments }, fill: options.fill, line: options.line, effects: options.effects, diff --git a/src/shapes/shape-run.spec.ts b/src/shapes/shape-run.spec.ts index 50c17b8788..86aea4070c 100644 --- a/src/shapes/shape-run.spec.ts +++ b/src/shapes/shape-run.spec.ts @@ -202,6 +202,27 @@ describe("ShapeRun", () => { expect(Object.keys(shape[1]["wps:spPr"][1])).to.deep.equal(["a:custGeom"]); }); + it("should draw a custom shape from several paths, with its text area and connection points", () => { + const tree = new Formatter().format( + new ShapeRun({ + type: "custom", + paths: [{ path: "M 0 0 H 100 V 100 H 0 Z" }, { path: "M 0 0 L 100 100", fill: false, line: true }], + textArea: { left: 0, top: 0, right: 100, bottom: 50 }, + connectionPoints: [{ x: 50, y: 0, side: "top" }], + transformation: { width: 100, height: 100 }, + }), + ); + + const shape = tree["w:r"][0]["w:drawing"][0]["wp:inline"][5]["a:graphic"][1]["a:graphicData"][1]["wps:wsp"]; + const geometry = shape[1]["wps:spPr"][1]["a:custGeom"]; + expect(geometry[1]["a:gdLst"]).to.have.length(6); + expect(geometry[3]).to.deep.equal({ + "a:cxnLst": [{ "a:cxn": [{ _attr: { ang: 16200000 } }, { "a:pos": { _attr: { x: "connsiteX0", y: "connsiteY0" } } }] }], + }); + expect(geometry[4]["a:rect"]._attr.b).to.equal("textAreaBottom"); + expect(geometry[5]["a:pathLst"]).to.have.length(2); + }); + describe("in the document's styles", () => { const contextOf = (document: object): IContext => ({ file: new File({ styles: { default: { document } }, sections: [] }), stack: [] }) as unknown as IContext; diff --git a/src/shapes/shape-run.ts b/src/shapes/shape-run.ts index eb829c77a1..3ed1b81cb4 100644 --- a/src/shapes/shape-run.ts +++ b/src/shapes/shape-run.ts @@ -62,6 +62,13 @@ export type { ShapeThemeColorName, SolidShapeFill, } from "./preset-shape"; +export type { + CustomShapeConnectionPoint, + CustomShapeGeometry, + CustomShapePath, + CustomShapePathFill, + CustomShapeTextArea, +} from "./custom-geometry"; export type { ShapeSize, ShapeTransformation } from "./shape-text-size"; export type { ShapeFloating, diff --git a/src/shapes/shape-text-size.spec.ts b/src/shapes/shape-text-size.spec.ts index 7825628377..d5c4a94de4 100644 --- a/src/shapes/shape-text-size.spec.ts +++ b/src/shapes/shape-text-size.spec.ts @@ -103,6 +103,20 @@ describe("resolveShapeSize", () => { ); }); + it("should fit the text of a custom shape in its text area", () => { + const rectangle = resolveShapeSize({ type: "rectangle", text: "Hello", transformation: { width: "fitText", height: "fitText" } }); + // The text area is the middle half of the shape across, and its top half down + const { width, height } = resolveShapeSize({ + type: "custom", + path: "M 0 0 H 100 V 100 H 0 Z", + textArea: { left: 25, top: 0, right: 75, bottom: 50 }, + text: "Hello", + transformation: { width: "fitText", height: "fitText" }, + }); + expect(width).to.be.closeTo(rectangle.width * 2, 2); + expect(height).to.be.closeTo(rectangle.height * 2, 2); + }); + it("should measure text that runs up or down the shape across its height", () => { const { width, height } = resolveShapeSize({ type: "rectangle", diff --git a/src/shapes/shape-text-size.ts b/src/shapes/shape-text-size.ts index 73286d1876..6d8de37319 100644 --- a/src/shapes/shape-text-size.ts +++ b/src/shapes/shape-text-size.ts @@ -6,6 +6,7 @@ */ import { AlignmentType, type IMediaTransformation, Paragraph, TextRun } from "docx"; +import { type CustomGeometryOptions, getCustomTextRectangle } from "./custom-geometry"; import { type PresetShapeType, type ShapeTextOptions, createShapeGuides } from "./preset-shape"; import { type ShapePercentage, percentageOf } from "./shape-floating"; import { type TextStyles, WORD_DEFAULT_STYLES, hasDefaultParagraphSpacing, readTextParagraphs } from "./shape-text-styles"; @@ -53,7 +54,7 @@ export const createTextParagraphs = (text: string, styles: TextStyles = WORD_DEF /** * What a shape needs to be sized to fit its text. */ -export type TextSizingOptions = { +export type TextSizingOptions = CustomGeometryOptions & { readonly type: PresetShapeType | "custom"; /** The shape's adjustments, by their readable names */ readonly adjustments?: Readonly>; @@ -132,7 +133,10 @@ export const resolveShapeSize = ( // The text box's length across and along the text, in pixels, for a shape of the given size const textBox = (acrossSize: number, alongSize: number): { readonly across: number; readonly along: number } => { const [width, height] = turned ? [alongSize, acrossSize] : [acrossSize, alongSize]; - const box = getTextRectangle(options.type, width * EMUS_PER_PIXEL, height * EMUS_PER_PIXEL, guides); + const box = + options.type === "custom" + ? getCustomTextRectangle(options, width * EMUS_PER_PIXEL, height * EMUS_PER_PIXEL) + : getTextRectangle(options.type, width * EMUS_PER_PIXEL, height * EMUS_PER_PIXEL, guides); const size = { width: (box.right - box.left) / EMUS_PER_PIXEL, height: (box.bottom - box.top) / EMUS_PER_PIXEL }; return turned ? { across: size.height, along: size.width } : { across: size.width, along: size.height }; };