Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
cce62ac
extract diagram editor toolbar:
mabaasit Jun 17, 2025
a43ed7e
add export modal
mabaasit Jun 17, 2025
39793bd
json export
mabaasit Jun 20, 2025
e47687e
tests
mabaasit Jun 20, 2025
dbc1ca0
close modal
mabaasit Jun 20, 2025
6d8de76
Merge branch 'main' into COMPASS-9448-diagram-json-export
mabaasit Jun 20, 2025
087936c
tests
mabaasit Jun 20, 2025
6c21b63
ensure test run
mabaasit Jun 20, 2025
b7d8dcf
fix toast
mabaasit Jun 20, 2025
7c4c14e
fix electron test
mabaasit Jun 20, 2025
f9bcc51
fix link
mabaasit Jun 20, 2025
b65f4c8
ensure its thrown
mabaasit Jun 23, 2025
adc19a1
asset number of selected collections
mabaasit Jun 23, 2025
6c41226
fix modal styles
mabaasit Jun 23, 2025
86e8a92
Merge branch 'main' into COMPASS-9448-diagram-json-export
mabaasit Jun 23, 2025
7fa0480
return null for tests
mabaasit Jun 24, 2025
8c5c14d
Merge branch 'main' into COMPASS-9448-diagram-json-export
mabaasit Jun 24, 2025
ffef0b7
remove comment
mabaasit Jun 24, 2025
88a227b
export image to png
mabaasit Jun 26, 2025
487a2b9
Merge branch 'main' of https://github.com/mongodb-js/compass into COM…
mabaasit Jun 26, 2025
56aadf0
move container to the export png
mabaasit Jun 26, 2025
42b9c8e
add ocr e2e test
mabaasit Jun 26, 2025
68d00cf
abortable export
mabaasit Jun 27, 2025
7b220ca
Merge branch 'main' of https://github.com/mongodb-js/compass into COM…
mabaasit Jun 27, 2025
8a08691
use package methods
mabaasit Jun 30, 2025
3b16d26
clean up
mabaasit Jun 30, 2025
c035d7a
Merge branch 'main' into COMPASS-9449-export-to-png
mabaasit Jun 30, 2025
cda452d
update diagramming
mabaasit Jul 1, 2025
a47faf8
Merge remote-tracking branch 'origin' into COMPASS-9449-export-to-png
mabaasit Jul 1, 2025
15bf100
npm install
mabaasit Jul 1, 2025
ae8e3c6
npm check
mabaasit Jul 1, 2025
840c078
fix test
mabaasit Jul 2, 2025
4bca5a2
Merge branch 'main' of https://github.com/mongodb-js/compass into COM…
mabaasit Jul 2, 2025
0a9a6e4
update npm
mabaasit Jul 2, 2025
aab9aca
Merge branch 'main' of https://github.com/mongodb-js/compass into COM…
mabaasit Jul 2, 2025
c6bc709
fix spaces issue
mabaasit Jul 2, 2025
010b0c6
fix popup for firefox
mabaasit Jul 2, 2025
b34c1f5
skip on win and lowercase test assertions
mabaasit Jul 3, 2025
6136ff4
cr comments
mabaasit Jul 3, 2025
fd4ee26
Merge branch 'main' of https://github.com/mongodb-js/compass into COM…
mabaasit Jul 3, 2025
065851a
npm install
mabaasit Jul 3, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/compass-data-modeling/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@mongodb-js/compass-user-data": "^0.7.2",
"@mongodb-js/compass-workspaces": "^0.42.0",
"html-to-image": "1.11.11",
"@mongodb-js/diagramming": "^1.0.3",
"bson": "^6.10.3",
"compass-preferences-model": "^2.41.0",
"lodash": "^4.17.21",
Expand Down
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,
Expand All @@ -13,6 +13,7 @@ import {
RadioGroup,
spacing,
SpinLoader,
useToast,
} from '@mongodb-js/compass-components';
import {
closeExportModal,
Expand All @@ -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';

Expand Down Expand Up @@ -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();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use our openToast instead, not sure how are we even exporting this one, we really shouldn't

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);
setIsExporting(false);
abortControllerRef.current?.abort();
abortControllerRef.current = null;
onCloseClick();
}, [onCloseClick]);

const onExport = useCallback(async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The 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

Copy link
Collaborator Author

Choose a reason for hiding this comment

The 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.

Copy link
Collaborator

Choose a reason for hiding this comment

The 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) {
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
Expand Down Expand Up @@ -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>
Expand Down
105 changes: 45 additions & 60 deletions packages/compass-data-modeling/src/services/export-diagram.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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) => {
Copy link
Member

Choose a reason for hiding this comment

The 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 toPng.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The 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.

Copy link
Member

Choose a reason for hiding this comment

The 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);
Copy link
Collaborator

Choose a reason for hiding this comment

The 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

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, @Anemy also mentioned same and that time i completely misunderstood this. i added this in 6136ff4 along with other fixes. Regarding useToast hook, i'll do a follow up to remove it from compass-components as its not being used elsewhere.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good!

i'll do a follow up to remove it from compass-components

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)

Copy link
Collaborator

Choose a reason for hiding this comment

The 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 finally

_reject(error);
};

ReactDOM.render(
<DiagramProvider>
<Diagram
edges={edges.map(mapEdgeToDiagramEdge)}
nodes={nodes.map(mapNodeToDiagramNode)}
edges={diagramEdges}
nodes={diagramNodes}
onlyRenderVisibleElements={false}
/>
</DiagramProvider>,
Expand All @@ -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,
Expand All @@ -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(() => {
Expand Down Expand Up @@ -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);
}
Loading