From cbf8eb9cbf2f4082cb1a83955d435ebcb73be3ab Mon Sep 17 00:00:00 2001 From: Georgios Andreadis Date: Mon, 11 Sep 2017 14:49:17 +0200 Subject: Center datacenter on site load --- src/store/middlewares/viewport-adjustment.js | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/store/middlewares/viewport-adjustment.js (limited to 'src/store/middlewares') diff --git a/src/store/middlewares/viewport-adjustment.js b/src/store/middlewares/viewport-adjustment.js new file mode 100644 index 00000000..75ad6a2f --- /dev/null +++ b/src/store/middlewares/viewport-adjustment.js @@ -0,0 +1,51 @@ +import {SET_MAP_DIMENSIONS, setMapPosition, setMapScale} from "../../actions/map"; +import { + MAP_MAX_SCALE, + MAP_MIN_SCALE, + SIDEBAR_WIDTH, + TILE_SIZE_IN_PIXELS, + VIEWPORT_PADDING +} from "../../components/map/MapConstants"; +import {calculateRoomListBounds} from "../../util/tile-calculations"; + +export const viewportAdjustmentMiddleware = store => next => action => { + const state = store.getState(); + if (action.type === SET_MAP_DIMENSIONS && state.currentDatacenterId !== -1) { + const roomIds = state.objects.datacenter[state.currentDatacenterId].roomIds; + const rooms = roomIds.map(id => Object.assign({}, state.objects.room[id])); + rooms.forEach(room => room.tiles = room.tileIds.map(tileId => state.objects.tile[tileId])); + + const viewportParams = calculateParametersToZoomInOnRooms(rooms, action.width, action.height); + store.dispatch(setMapPosition(viewportParams.newX, viewportParams.newY)); + store.dispatch(setMapScale(viewportParams.newScale)); + } + + next(action); +}; + +function calculateParametersToZoomInOnRooms(rooms, mapWidth, mapHeight) { + const bounds = calculateRoomListBounds(rooms); + const newScale = calculateNewScale(bounds, mapWidth, mapHeight); + + // Coordinates of the center of the room, relative to the global origin of the map + const roomCenterCoordinates = { + x: bounds.center.x * TILE_SIZE_IN_PIXELS * newScale, + y: bounds.center.y * TILE_SIZE_IN_PIXELS * newScale + }; + + const newX = -roomCenterCoordinates.x + mapWidth / 2; + const newY = -roomCenterCoordinates.y + mapHeight / 2; + + return {newScale, newX, newY}; +} + +function calculateNewScale(bounds, mapWidth, mapHeight) { + const width = bounds.max.x - bounds.min.x; + const height = bounds.max.y - bounds.min.y; + + const scaleX = (mapWidth - 2 * SIDEBAR_WIDTH) / (width * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); + const scaleY = mapHeight / (height * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); + const newScale = Math.min(scaleX, scaleY); + + return Math.min(Math.max(MAP_MIN_SCALE, newScale), MAP_MAX_SCALE); +} -- cgit v1.2.3