Skip to content
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

feat(frontend): Center initial canvas #8644

Merged
merged 7 commits into from
Nov 14, 2024
46 changes: 38 additions & 8 deletions autogpt_platform/frontend/src/components/Flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,35 @@ const FlowEditor: React.FC<{

const { x, y, zoom } = useViewport();

// Set the initial view port to center the canvas.
useEffect(() => {
if (nodes.length <= 0 || x !== 0 || y !== 0) {
return;
}

const topLeft = { x: Infinity, y: Infinity };
const bottomRight = { x: -Infinity, y: -Infinity };

nodes.forEach((node) => {
const { x, y } = node.position;
topLeft.x = Math.min(topLeft.x, x);
topLeft.y = Math.min(topLeft.y, y);
// Rough estimate of the width and height of the node: 500x400.
bottomRight.x = Math.max(bottomRight.x, x + 500);
bottomRight.y = Math.max(bottomRight.y, y + 400);
});

const centerX = (topLeft.x + bottomRight.x) / 2;
const centerY = (topLeft.y + bottomRight.y) / 2;
const zoom = 0.8;

setViewport({
x: window.innerWidth / 2 - centerX * zoom,
y: window.innerHeight / 2 - centerY * zoom,
zoom: zoom,
});
}, [nodes, setViewport, x, y]);

const addNode = useCallback(
(blockId: string, nodeType: string, hardcodedValues: any = {}) => {
const nodeSchema = availableNodes.find((node) => node.id === blockId);
Expand All @@ -434,14 +463,14 @@ const FlowEditor: React.FC<{
? // we will get all the dimension of nodes, then store
findNewlyAddedBlockCoordinates(
nodeDimensions,
(nodeSchema.uiType == BlockUIType.NOTE ? 300 : 500) / zoom,
60 / zoom,
zoom,
nodeSchema.uiType == BlockUIType.NOTE ? 300 : 500,
60,
1.0,
)
: // we will get all the dimension of nodes, then store
{
x: (window.innerWidth / 2 - x) / zoom,
y: (window.innerHeight / 2 - y) / zoom,
x: window.innerWidth / 2 - x,
y: window.innerHeight / 2 - y,
};

const newNode: CustomNode = {
Expand Down Expand Up @@ -471,8 +500,10 @@ const FlowEditor: React.FC<{

setViewport(
{
x: -viewportCoordinates.x * zoom + window.innerWidth / 2,
y: -viewportCoordinates.y * zoom + window.innerHeight / 2 - 100,
// Rough estimate of the dimension of the node is: 500x400px.
// Though we skip shifting the X, considering the block menu side-bar.
x: -viewportCoordinates.x * 0.8 + (window.innerWidth - 0.0) / 2,
y: -viewportCoordinates.y * 0.8 + (window.innerHeight - 400) / 2,
zoom: 0.8,
},
{ duration: 500 },
Expand All @@ -495,7 +526,6 @@ const FlowEditor: React.FC<{
clearNodesStatusAndOutput,
x,
y,
zoom,
],
);

Expand Down
Loading