refactor: simplify zoom by removing zoom.translation (#4477)

This commit is contained in:
David Luzar 2022-01-29 21:12:44 +01:00 committed by GitHub
parent e4edda4555
commit 79d323fab1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 152 additions and 408 deletions

View file

@ -18,4 +18,4 @@ export {
hasText,
getElementsAtPosition,
} from "./comparisons";
export { getNormalizedZoom, getNewZoom } from "./zoom";
export { getNormalizedZoom } from "./zoom";

View file

@ -41,14 +41,8 @@ export const centerScrollOn = ({
zoom: Zoom;
}) => {
return {
scrollX:
(viewportDimensions.width / 2) * (1 / zoom.value) -
scenePoint.x -
zoom.translation.x * (1 / zoom.value),
scrollY:
(viewportDimensions.height / 2) * (1 / zoom.value) -
scenePoint.y -
zoom.translation.y * (1 / zoom.value),
scrollX: (viewportDimensions.width / 2) * (1 / zoom.value) - scenePoint.x,
scrollY: (viewportDimensions.height / 2) * (1 / zoom.value) - scenePoint.y,
};
};

View file

@ -1,30 +1,41 @@
import { NormalizedZoomValue, PointerCoords, Zoom } from "../types";
export const getNewZoom = (
newZoomValue: NormalizedZoomValue,
prevZoom: Zoom,
canvasOffset: { left: number; top: number },
zoomOnViewportPoint: PointerCoords = { x: 0, y: 0 },
): Zoom => {
return {
value: newZoomValue,
translation: {
x:
zoomOnViewportPoint.x -
canvasOffset.left -
(zoomOnViewportPoint.x - canvasOffset.left - prevZoom.translation.x) *
(newZoomValue / prevZoom.value),
y:
zoomOnViewportPoint.y -
canvasOffset.top -
(zoomOnViewportPoint.y - canvasOffset.top - prevZoom.translation.y) *
(newZoomValue / prevZoom.value),
},
};
};
import { AppState, NormalizedZoomValue } from "../types";
export const getNormalizedZoom = (zoom: number): NormalizedZoomValue => {
const normalizedZoom = parseFloat(zoom.toFixed(2));
const clampedZoom = Math.max(0.1, Math.min(normalizedZoom, 30));
return clampedZoom as NormalizedZoomValue;
};
export const getStateForZoom = (
{
viewportX,
viewportY,
nextZoom,
}: {
viewportX: number;
viewportY: number;
nextZoom: NormalizedZoomValue;
},
appState: AppState,
) => {
const appLayerX = viewportX - appState.offsetLeft;
const appLayerY = viewportY - appState.offsetTop;
const currentZoom = appState.zoom.value;
// get original scroll position without zoom
const baseScrollX = appState.scrollX + (appLayerX - appLayerX / currentZoom);
const baseScrollY = appState.scrollY + (appLayerY - appLayerY / currentZoom);
// get scroll offsets for target zoom level
const zoomOffsetScrollX = -(appLayerX - appLayerX / nextZoom);
const zoomOffsetScrollY = -(appLayerY - appLayerY / nextZoom);
return {
scrollX: baseScrollX + zoomOffsetScrollX,
scrollY: baseScrollY + zoomOffsetScrollY,
zoom: {
value: nextZoom,
},
};
};