simplify distance helper and factor out common bounds helper (#581)

* simplify distance helper

* factor out common bounds helper
This commit is contained in:
David Luzar
2020-01-26 20:15:08 +01:00
committed by Christopher Chedeau
parent 5853fba821
commit 7b842fc330
7 changed files with 42 additions and 77 deletions

View File

@ -7,6 +7,7 @@ import { ExportType } from "./types";
import { getExportCanvasPreview } from "./getExportCanvasPreview";
import nanoid from "nanoid";
import { fileOpen, fileSave } from "browser-nativefs";
import { getCommonBounds } from "../element";
import i18n from "../i18n";
@ -43,35 +44,14 @@ export function serializeAsJSON(
);
}
function calculateScroll(
function calculateScrollCenter(
elements: readonly ExcalidrawElement[],
): { scrollX: number; scrollY: number } {
// Bounding box of all elements
let top = Number.MAX_SAFE_INTEGER;
let left = Number.MAX_SAFE_INTEGER;
let bottom = -Number.MAX_SAFE_INTEGER;
let right = -Number.MAX_SAFE_INTEGER;
let [x1, y1, x2, y2] = getCommonBounds(elements);
const centerX = (x1 + x2) / 2;
const centerY = (y1 + y2) / 2;
for (const element of elements) {
left = Math.min(
left,
element.width > 0 ? element.x : element.x + element.width,
);
top = Math.min(
top,
element.height > 0 ? element.y : element.y + element.height,
);
right = Math.max(
right,
element.width > 0 ? element.x + element.width : element.x,
);
bottom = Math.max(
bottom,
element.height > 0 ? element.y + element.height : element.y,
);
}
const centerX = left + (right - left) / 2;
const centerY = top + (bottom - top) / 2;
return {
scrollX: window.innerWidth / 2 - centerX,
scrollY: window.innerHeight / 2 - centerY,
@ -136,7 +116,9 @@ export async function loadFromJSON() {
}
const { elements, appState } = updateAppState(contents);
return new Promise<DataState>(resolve => {
resolve(restore(elements, { ...appState, ...calculateScroll(elements) }));
resolve(
restore(elements, { ...appState, ...calculateScrollCenter(elements) }),
);
});
}
@ -187,7 +169,7 @@ export async function importFromBackend(id: string | null) {
console.error(error);
}
}
return restore(elements, { ...appState, ...calculateScroll(elements) });
return restore(elements, { ...appState, ...calculateScrollCenter(elements) });
}
export async function exportCanvas(