-
Notifications
You must be signed in to change notification settings - Fork 247
feat(data-modeling): export diagram to png COMPASS-9449 #7055
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
Changes from 4 commits
cce62ac
a43ed7e
39793bd
e47687e
dbc1ca0
6d8de76
087936c
6c21b63
b7d8dcf
7c4c14e
f9bcc51
b65f4c8
adc19a1
6c41226
86e8a92
7fa0480
8c5c14d
ffef0b7
88a227b
487a2b9
56aadf0
42b9c8e
68d00cf
7b220ca
8a08691
3b16d26
c035d7a
cda452d
a47faf8
15bf100
ae8e3c6
840c078
4bca5a2
0a9a6e4
aab9aca
c6bc709
010b0c6
b34c1f5
6136ff4
fd4ee26
065851a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| import React, { useCallback, useState } from 'react'; | ||
| import React, { useCallback, useEffect, useRef, useState } from 'react'; | ||
| import { | ||
| Button, | ||
| css, | ||
|
|
@@ -13,6 +13,7 @@ import { | |
| RadioGroup, | ||
| spacing, | ||
| SpinLoader, | ||
| useToast, | ||
| } from '@mongodb-js/compass-components'; | ||
| import { | ||
| closeExportModal, | ||
|
|
@@ -24,6 +25,7 @@ import type { DataModelingState } from '../store/reducer'; | |
| import type { StaticModel } from '../services/data-model-storage'; | ||
| import { exportToJson, exportToPng } from '../services/export-diagram'; | ||
| import { useDiagram } from '@mongodb-js/diagramming'; | ||
| import { isCancelError } from '@mongodb-js/compass-utils'; | ||
|
|
||
| const nbsp = '\u00a0'; | ||
|
|
||
|
|
@@ -64,25 +66,68 @@ const ExportDiagramModal = ({ | |
| const [exportFormat, setExportFormat] = useState<'png' | 'json' | null>(null); | ||
| const diagram = useDiagram(); | ||
| const [isExporting, setIsExporting] = useState(false); | ||
| const abortControllerRef = useRef<AbortController | null>(null); | ||
| const toast = useToast(); | ||
|
||
| useEffect(() => { | ||
| const cleanup = () => { | ||
| if (abortControllerRef.current) { | ||
| abortControllerRef.current.abort(); | ||
| abortControllerRef.current = null; | ||
| } | ||
| }; | ||
| const abortController = new AbortController(); | ||
| if (isModalOpen) { | ||
| abortControllerRef.current = abortController; | ||
| } else { | ||
| cleanup(); | ||
| } | ||
| return cleanup; | ||
| }, [isModalOpen]); | ||
|
|
||
| const onClose = useCallback(() => { | ||
| setExportFormat(null); | ||
Anemy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| setIsExporting(false); | ||
| abortControllerRef.current?.abort(); | ||
| abortControllerRef.current = null; | ||
| onCloseClick(); | ||
| }, [onCloseClick]); | ||
|
|
||
| const onExport = useCallback(async () => { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is way too much logic in the UI here (like if you see that you're keeping abort controllers in render, you probably should start thinking about that), this should really be an action in the store instead
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, i'll add another slice for export. Or, I can do it as a follow up if that sounds okay to you.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow-up sounds good, let's not hold this code in the branch for too long 👍 |
||
| if (!exportFormat || !model) { | ||
| return; | ||
| try { | ||
| if (!exportFormat || !model) { | ||
Anemy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return; | ||
| } | ||
| setIsExporting(true); | ||
| if (exportFormat === 'json') { | ||
| exportToJson(diagramLabel, model); | ||
| } else if (exportFormat === 'png') { | ||
| await exportToPng( | ||
| diagramLabel, | ||
| diagram, | ||
| abortControllerRef.current?.signal | ||
| ); | ||
| } | ||
| } catch (error) { | ||
| if (isCancelError(error)) { | ||
| return; | ||
| } | ||
| toast.pushToast({ | ||
| id: 'export-diagram-error', | ||
| variant: 'warning', | ||
| title: 'Export failed', | ||
| description: `An error occurred while exporting the diagram: ${ | ||
| (error as Error).message | ||
| }`, | ||
| }); | ||
| } finally { | ||
| onClose(); | ||
| } | ||
| setIsExporting(true); | ||
| if (exportFormat === 'json') { | ||
| exportToJson(diagramLabel, model); | ||
| } else if (exportFormat === 'png') { | ||
| await exportToPng(diagramLabel, diagram); | ||
| } | ||
| onCloseClick(); | ||
| setIsExporting(false); | ||
| }, [exportFormat, onCloseClick, model, diagram, diagramLabel]); | ||
| }, [exportFormat, onClose, model, diagram, diagramLabel, toast]); | ||
|
|
||
| return ( | ||
| <Modal | ||
| open={isModalOpen} | ||
| setOpen={onCloseClick} | ||
| setOpen={onClose} | ||
| data-testid="export-diagram-modal" | ||
| > | ||
| <ModalHeader | ||
|
|
@@ -140,11 +185,7 @@ const ExportDiagramModal = ({ | |
| > | ||
| Export | ||
| </Button> | ||
| <Button | ||
| variant="default" | ||
| onClick={onCloseClick} | ||
| data-testid="cancel-button" | ||
| > | ||
| <Button variant="default" onClick={onClose} data-testid="cancel-button"> | ||
| Cancel | ||
| </Button> | ||
| </ModalFooter> | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,47 +4,15 @@ import { | |
| getViewportForBounds, | ||
| DiagramProvider, | ||
| Diagram, | ||
| mapEdgeToDiagramEdge, | ||
| mapNodeToDiagramNode, | ||
| } from '@mongodb-js/diagramming'; | ||
| import type { | ||
| useDiagram, | ||
| NodeProps, | ||
| NodeType, | ||
| EdgeProps, | ||
| Marker, | ||
| } from '@mongodb-js/diagramming'; | ||
| import type { DiagramInstance } from '@mongodb-js/diagramming'; | ||
| import type { StaticModel } from './data-model-storage'; | ||
| import ReactDOM from 'react-dom'; | ||
| import { toPng } from 'html-to-image'; | ||
| import { rafraf, spacing } from '@mongodb-js/compass-components'; | ||
|
|
||
| // TODO: Export these methods (and type) from the diagramming package | ||
| type DiagramInstance = ReturnType<typeof useDiagram>; | ||
| function mapNodeToDiagramNode( | ||
| node: ReturnType<DiagramInstance['getNodes']>[number] | ||
| ): NodeProps { | ||
| const { data, type, ...restOfNode } = node; | ||
| return { | ||
| ...restOfNode, | ||
| ...(data as any), // TODO: Type data (or expose these methods from the diagramming package) | ||
| type: type as NodeType, | ||
| }; | ||
| } | ||
| function mapEdgeToDiagramEdge( | ||
| edge: ReturnType<DiagramInstance['getEdges']>[number] | ||
| ): EdgeProps { | ||
| const { markerStart, markerEnd, ...restOfEdge } = edge; | ||
|
|
||
| // The diagramming package only allows string based markers | ||
| if (typeof markerStart !== 'string' || typeof markerEnd !== 'string') { | ||
| throw new Error('Unexpected edge with non-string markers'); | ||
| } | ||
|
|
||
| return { | ||
| ...restOfEdge, | ||
| markerEnd: markerEnd.replace('end-', '') as Marker, | ||
| markerStart: markerStart.replace('start-', '') as Marker, | ||
| }; | ||
| } | ||
| import { raceWithAbort } from '@mongodb-js/compass-utils'; | ||
|
|
||
| function moveSvgDefsToViewportElement( | ||
| container: Element, | ||
|
|
@@ -67,33 +35,50 @@ function moveSvgDefsToViewportElement( | |
| markerDef.remove(); | ||
| } | ||
|
|
||
| export async function exportToPng(fileName: string, diagram: DiagramInstance) { | ||
| const container = document.createElement('div'); | ||
| container.setAttribute('data-testid', 'export-diagram-container'); | ||
| // Push it out of the viewport | ||
| container.style.position = 'fixed'; | ||
| container.style.top = '100vh'; | ||
| container.style.left = '100vw'; | ||
| document.body.appendChild(container); | ||
|
|
||
| const dataUri = await getExportPngDataUri(container, diagram); | ||
| downloadFile(dataUri, fileName, () => { | ||
| container.remove(); | ||
| }); | ||
| export async function exportToPng( | ||
| fileName: string, | ||
| diagram: DiagramInstance, | ||
| signal?: AbortSignal | ||
| ) { | ||
| const dataUri = await raceWithAbort( | ||
| getExportPngDataUri(diagram), | ||
| signal ?? new AbortController().signal | ||
| ); | ||
| downloadFile(dataUri, fileName); | ||
| } | ||
|
|
||
| export function getExportPngDataUri( | ||
| container: HTMLDivElement, | ||
| diagram: DiagramInstance | ||
| ): Promise<string> { | ||
| return new Promise<string>((resolve, reject) => { | ||
| export function getExportPngDataUri(diagram: DiagramInstance): Promise<string> { | ||
| return new Promise<string>((resolve, _reject) => { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there a reason why we're going to the Promise resolve/reject here? I'm thinking it could lead to an uncaught exception. Could we instead have the cleanup in a finally or catch block? We could do await something like the rafraf as well and await the
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What would you recommend in this case? I only want to resolve once dom has been converted to a data uri (and as such show loading state to the user). For clean up, its already in place where we export.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would recommend async/await here with try/catch. I find it makes the code easier to read through and the error handling less prone to be uncaught. |
||
| const nodes = diagram.getNodes(); | ||
| const edges = diagram.getEdges(); | ||
| const bounds = getNodesBounds(nodes); | ||
|
|
||
| const container = document.createElement('div'); | ||
| container.setAttribute('data-testid', 'export-diagram-container'); | ||
| // Push it out of the viewport | ||
| container.style.position = 'fixed'; | ||
| container.style.top = '100vh'; | ||
| container.style.left = '100vw'; | ||
| container.style.width = `${bounds.width}px`; | ||
| container.style.height = `${bounds.height}px`; | ||
| document.body.appendChild(container); | ||
|
|
||
| const diagramEdges = edges.map(mapEdgeToDiagramEdge); | ||
| const diagramNodes = nodes.map(mapNodeToDiagramNode).map((node) => ({ | ||
| ...node, | ||
| selected: false, // Dont show selected state (blue border) | ||
| })); | ||
|
|
||
| const reject = (error: Error) => { | ||
| document.body.removeChild(container); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems like we're missing clean-up on resolve, this should probably be in a finally block
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sounds good!
Just FYI, I already did in eslint update PR, so no need to worry about this (was in the way of some new issues that update started to show there)
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: you don't need it here now that you have it in |
||
| _reject(error); | ||
| }; | ||
|
|
||
| ReactDOM.render( | ||
| <DiagramProvider> | ||
| <Diagram | ||
| edges={edges.map(mapEdgeToDiagramEdge)} | ||
| nodes={nodes.map(mapNodeToDiagramNode)} | ||
| edges={diagramEdges} | ||
| nodes={diagramNodes} | ||
| onlyRenderVisibleElements={false} | ||
| /> | ||
| </DiagramProvider>, | ||
|
|
@@ -110,10 +95,9 @@ export function getExportPngDataUri( | |
| '.react-flow__viewport' | ||
| ); | ||
| if (!viewportElement) { | ||
| throw new Error('Diagram element not found'); | ||
| return reject(new Error('Diagram element not found')); | ||
| } | ||
|
|
||
| const bounds = getNodesBounds(nodes); | ||
| const transform = getViewportForBounds( | ||
| bounds, | ||
| bounds.width, | ||
|
|
@@ -122,6 +106,7 @@ export function getExportPngDataUri( | |
| 2, // Maximum zoom | ||
| `${spacing[400]}px` // 16px padding | ||
| ); | ||
|
|
||
| // Moving svg defs to the viewport element | ||
| moveSvgDefsToViewportElement(container, viewportElement); | ||
| rafraf(() => { | ||
|
|
@@ -172,13 +157,13 @@ export function getExportJsonFromModel({ | |
| }; | ||
| } | ||
|
|
||
| function downloadFile(uri: string, fileName: string, cleanup: () => void) { | ||
| function downloadFile(uri: string, fileName: string, cleanup?: () => void) { | ||
| const link = document.createElement('a'); | ||
| link.download = fileName; | ||
| link.href = uri; | ||
| link.click(); | ||
| setTimeout(() => { | ||
| link.remove(); | ||
| cleanup(); | ||
| cleanup?.(); | ||
| }, 0); | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.