Skip to content

Commit 77a1ac6

Browse files
committed
refactor centering calc
1 parent dd07568 commit 77a1ac6

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

packages/compass-data-modeling/src/components/diagram-editor.tsx

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -191,26 +191,30 @@ const DiagramContent: React.FunctionComponent<{
191191
// Center on a new collection when it is added
192192
const previouslyOpenedDrawer = useRef<boolean>(false);
193193
useEffect(() => {
194-
if (newCollection) {
195-
const node = nodes.find((n) => n.id === newCollection);
196-
if (node) {
197-
const zoom = diagram.current.getViewport().zoom;
198-
const drawerOffset = previouslyOpenedDrawer.current ? 0 : 240;
199-
const newNodeWidth = 244;
200-
const newNodeHeight = 64;
201-
return rafraf(() => {
202-
void diagram.current.setCenter(
203-
((node.position.x + newNodeWidth / 2) * zoom + drawerOffset) / zoom,
204-
node.position.y + newNodeHeight / 2,
205-
{
206-
duration: 500,
207-
zoom,
208-
}
209-
);
210-
});
211-
}
212-
}
194+
const wasDrawerPreviouslyOpened = previouslyOpenedDrawer.current;
213195
previouslyOpenedDrawer.current = !!isDrawerOpen;
196+
197+
if (!newCollection) return;
198+
const node = nodes.find((n) => n.id === newCollection);
199+
if (!node) return;
200+
201+
// For calculating the center, we're taking into account the drawer,
202+
// so that the new node is centered in the visible part.
203+
const drawerOffset = wasDrawerPreviouslyOpened ? 0 : 240;
204+
const zoom = diagram.current.getViewport().zoom;
205+
const drawerOffsetInDiagramCoords = drawerOffset / zoom;
206+
const newNodeWidth = 244;
207+
const newNodeHeight = 64;
208+
return rafraf(() => {
209+
void diagram.current.setCenter(
210+
node.position.x + newNodeWidth / 2 + drawerOffsetInDiagramCoords,
211+
node.position.y + newNodeHeight / 2,
212+
{
213+
duration: 500,
214+
zoom,
215+
}
216+
);
217+
});
214218
}, [newCollection, nodes, isDrawerOpen]);
215219

216220
const handleNodesConnect = useCallback(

0 commit comments

Comments
 (0)