-
Notifications
You must be signed in to change notification settings - Fork 11
feat: Add ability to export workflow diagram as png #373
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cheryl7114
wants to merge
11
commits into
open-workflow-specification:main
Choose a base branch
from
cheryl7114:png-export-341
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e009bb6
feat: add png export utility
cheryl7114 0bd736e
feat: add png export button to side panel
cheryl7114 c21c2e3
fix: render all elements and re-query edges during export
cheryl7114 aaf317d
test: add unit tests for png export
cheryl7114 3990e97
fix: scope png export viewport query to diagram container
cheryl7114 aab8ad3
pull upstream changes
cheryl7114 88303a2
fix: fix copilot complaints
cheryl7114 44930c2
fix based on suggestions
cheryl7114 a3d172a
rerun tests
cheryl7114 aa56001
fix export test
cheryl7114 d232095
fix according to suggestions
cheryl7114 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@openworkflowspec/diagram-editor": minor | ||
| --- | ||
|
|
||
| add png export button for react flow diagram |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
91 changes: 91 additions & 0 deletions
91
packages/open-workflow-diagram-editor/src/lib/exportPng.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| /* | ||
| * Copyright 2021-Present The Open Workflow Specification Authors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import { toPng } from "html-to-image"; | ||
| import type { ReactFlowInstance } from "@xyflow/react"; | ||
|
|
||
| const PADDING = 40; | ||
| const SCALE = 3; | ||
|
|
||
| export async function exportDiagramAsPng( | ||
| reactFlowInstance: ReactFlowInstance, | ||
| filename: string, | ||
| container?: HTMLElement | null, | ||
| ): Promise<void> { | ||
| if (typeof document === "undefined") { | ||
| throw new Error("Document API is not available in this environment"); | ||
| } | ||
|
|
||
| const root = container ?? document; | ||
| const viewport = root.querySelector<HTMLElement>(".react-flow__viewport"); | ||
| if (!viewport) { | ||
| throw new Error("React Flow viewport element not found"); | ||
| } | ||
|
|
||
| const nodes = reactFlowInstance.getNodes(); | ||
| if (nodes.length === 0) { | ||
| throw new Error("No nodes to export"); | ||
| } | ||
|
|
||
| const { x: minX, y: minY, width, height } = reactFlowInstance.getNodesBounds(nodes); | ||
| const contentWidth = width + PADDING * 2; | ||
| const contentHeight = height + PADDING * 2; | ||
|
|
||
| // Edge colours are defined via CSS custom properties and Tailwind classes on | ||
| // ancestor elements. When html-to-image serialises the SVG, those rules are | ||
| // no longer in scope and stroke colours are lost. Fix: read the browser's | ||
| // fully-resolved computed stroke from each live element and set it as an | ||
| // inline style so the value is self-contained in the serialised output. | ||
| viewport.querySelectorAll<SVGElement>(".edge-line").forEach((el) => { | ||
| el.style.stroke = getComputedStyle(el).stroke; | ||
| }); | ||
|
|
||
| const backgroundColor = | ||
| getComputedStyle(viewport).getPropertyValue("--dec-canvas-bg").trim() || "#ffffff"; | ||
|
|
||
| let dataUrl: string; | ||
| try { | ||
| dataUrl = await toPng(viewport, { | ||
| backgroundColor, | ||
| width: contentWidth, | ||
| height: contentHeight, | ||
| pixelRatio: SCALE, | ||
| style: { | ||
| transform: `translate(${-minX + PADDING}px, ${-minY + PADDING}px)`, | ||
| width: `${contentWidth}px`, | ||
| height: `${contentHeight}px`, | ||
| }, | ||
| filter: (node) => { | ||
| if (node instanceof HTMLLinkElement && node.rel === "stylesheet") { | ||
| return new URL(node.href, document.baseURI).origin === globalThis.location?.origin; | ||
| } | ||
| return true; | ||
| }, | ||
| }); | ||
| } finally { | ||
| // Clear inline strokes by re-querying the live DOM. Refs captured before | ||
| // toPng are stale — React Flow may have replaced SVG elements during the | ||
| // await when isExporting triggered a re-render. | ||
| viewport.querySelectorAll<SVGElement>(".edge-line").forEach((el) => { | ||
| el.style.stroke = ""; | ||
| }); | ||
| } | ||
|
|
||
| const link = document.createElement("a"); | ||
| link.download = filename; | ||
| link.href = dataUrl; | ||
| link.click(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
91 changes: 91 additions & 0 deletions
91
packages/open-workflow-diagram-editor/tests/lib/exportPng.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| /* | ||
| * Copyright 2021-Present The Open Workflow Specification Authors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import { exportDiagramAsPng } from "../../src/lib/exportPng"; | ||
| import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; | ||
| import { toPng } from "html-to-image"; | ||
| import type { ReactFlowInstance } from "@xyflow/react"; | ||
|
|
||
| vi.mock("html-to-image", () => ({ | ||
| toPng: vi.fn().mockResolvedValue("data:image/png;base64,mock"), | ||
| })); | ||
|
|
||
| function makeViewport(): void { | ||
| const viewport = document.createElement("div"); | ||
| viewport.className = "react-flow__viewport"; | ||
| document.body.appendChild(viewport); | ||
| } | ||
|
|
||
| function makeInstance(nodes: object[]): ReactFlowInstance { | ||
| return { | ||
| getNodes: vi.fn().mockReturnValue(nodes), | ||
| getNodesBounds: vi.fn().mockReturnValue({ x: 0, y: 0, width: 100, height: 100 }), | ||
| } as unknown as ReactFlowInstance; | ||
| } | ||
|
|
||
| describe("exportDiagramAsPng", () => { | ||
| let mockClick: ReturnType<typeof vi.fn>; | ||
| let mockLink: HTMLAnchorElement; | ||
|
|
||
| beforeEach(() => { | ||
| makeViewport(); | ||
|
|
||
| mockClick = vi.fn(); | ||
| mockLink = { click: mockClick, href: "", download: "" } as unknown as HTMLAnchorElement; | ||
| const originalCreateElement = document.createElement.bind(document); | ||
| vi.spyOn(document, "createElement").mockImplementation((tag: string) => { | ||
| if (tag === "a") return mockLink; | ||
| return originalCreateElement(tag); | ||
| }); | ||
|
cheryl7114 marked this conversation as resolved.
|
||
| }); | ||
|
|
||
| afterEach(() => { | ||
| document.body.innerHTML = ""; | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it("triggers a download with the given filename", async () => { | ||
| const instance = makeInstance([{ id: "1" }]); | ||
| await exportDiagramAsPng(instance, "diagram.png"); | ||
|
|
||
| expect(mockLink.download).toBe("diagram.png"); | ||
| expect(mockLink.href).toBe("data:image/png;base64,mock"); | ||
| expect(mockClick).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it("falls back to #ffffff when --dec-canvas-bg is not set", async () => { | ||
| const instance = makeInstance([{ id: "1" }]); | ||
| await exportDiagramAsPng(instance, "diagram.png"); | ||
|
|
||
| expect(toPng).toHaveBeenCalledWith( | ||
| expect.any(HTMLElement), | ||
| expect.objectContaining({ backgroundColor: "#ffffff" }), | ||
| ); | ||
| }); | ||
|
|
||
| it("throws when there are no nodes", async () => { | ||
| const instance = makeInstance([]); | ||
| await expect(exportDiagramAsPng(instance, "diagram.png")).rejects.toThrow("No nodes to export"); | ||
| }); | ||
|
|
||
| it("throws when the viewport element is not found", async () => { | ||
| document.body.innerHTML = ""; | ||
| const instance = makeInstance([{ id: "1" }]); | ||
| await expect(exportDiagramAsPng(instance, "diagram.png")).rejects.toThrow( | ||
| "React Flow viewport element not found", | ||
| ); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.