Files
grungnet/src/components/map/Map.js

333 lines
8.7 KiB
JavaScript
Raw Normal View History

2020-03-20 21:46:52 +11:00
import React, { useRef, useEffect, useState } from "react";
import { Box, Image } from "theme-ui";
2020-03-20 21:46:52 +11:00
import interact from "interactjs";
import ProxyToken from "../token/ProxyToken";
import TokenMenu from "../token/TokenMenu";
2020-04-18 18:11:21 +10:00
import MapToken from "./MapToken";
import MapDrawing from "./MapDrawing";
import MapControls from "./MapControls";
2020-03-20 13:33:12 +11:00
import { omit } from "../../helpers/shared";
const mapTokenProxyClassName = "map-token__proxy";
const mapTokenMenuClassName = "map-token__menu";
2020-03-20 21:46:52 +11:00
const zoomSpeed = -0.005;
const minZoom = 0.1;
const maxZoom = 5;
2020-03-20 13:33:12 +11:00
function Map({
map,
2020-04-23 17:23:34 +10:00
mapState,
onMapTokenChange,
onMapTokenRemove,
onMapChange,
2020-04-19 15:15:48 +10:00
onMapDraw,
onMapDrawUndo,
onMapDrawRedo,
}) {
2020-03-20 13:33:12 +11:00
function handleProxyDragEnd(isOnMap, token) {
if (isOnMap && onMapTokenChange) {
onMapTokenChange(token);
2020-03-20 13:33:12 +11:00
}
if (!isOnMap && onMapTokenRemove) {
onMapTokenRemove(token);
}
}
/**
* Map drawing
*/
2020-03-20 21:46:52 +11:00
2020-04-19 00:24:06 +10:00
const [selectedTool, setSelectedTool] = useState("pan");
const [brushColor, setBrushColor] = useState("black");
2020-04-20 15:17:56 +10:00
const [useBrushGridSnapping, setUseBrushGridSnapping] = useState(false);
const [useBrushBlending, setUseBrushBlending] = useState(false);
const [useBrushGesture, setUseBrushGesture] = useState(false);
2020-04-19 00:24:06 +10:00
const [drawnShapes, setDrawnShapes] = useState([]);
function handleShapeAdd(shape) {
onMapDraw({ type: "add", shapes: [shape] });
}
function handleShapeRemove(shapeId) {
onMapDraw({ type: "remove", shapeIds: [shapeId] });
}
function handleShapeRemoveAll() {
onMapDraw({ type: "remove", shapeIds: drawnShapes.map((s) => s.id) });
}
2020-04-19 15:15:48 +10:00
// Replay the draw actions and convert them to shapes for the map drawing
useEffect(() => {
2020-04-23 17:23:34 +10:00
if (!mapState) {
return;
}
let shapesById = {};
2020-04-23 17:23:34 +10:00
for (let i = 0; i <= mapState.drawActionIndex; i++) {
const action = mapState.drawActions[i];
if (action.type === "add") {
for (let shape of action.shapes) {
shapesById[shape.id] = shape;
}
}
if (action.type === "remove") {
shapesById = omit(shapesById, action.shapeIds);
}
}
setDrawnShapes(Object.values(shapesById));
2020-04-23 17:23:34 +10:00
}, [mapState]);
const disabledTools = [];
if (!map) {
disabledTools.push("pan");
disabledTools.push("brush");
}
if (drawnShapes.length === 0) {
disabledTools.push("erase");
}
/**
* Map movement
*/
const mapTranslateRef = useRef({ x: 0, y: 0 });
const mapScaleRef = useRef(1);
const mapMoveContainerRef = useRef();
function setTranslateAndScale(newTranslate, newScale) {
const moveContainer = mapMoveContainerRef.current;
moveContainer.style.transform = `translate(${newTranslate.x}px, ${newTranslate.y}px) scale(${newScale})`;
mapScaleRef.current = newScale;
mapTranslateRef.current = newTranslate;
}
2020-03-20 21:46:52 +11:00
useEffect(() => {
function handleMove(event, isGesture) {
const scale = mapScaleRef.current;
const translate = mapTranslateRef.current;
let newScale = scale;
let newTranslate = translate;
if (isGesture) {
newScale = Math.max(Math.min(scale + event.ds, maxZoom), minZoom);
}
if (selectedTool === "pan" || isGesture) {
newTranslate = {
x: translate.x + event.dx,
y: translate.y + event.dy,
};
}
setTranslateAndScale(newTranslate, newScale);
}
const mapInteract = interact(".map")
.gesturable({
listeners: {
move: (e) => handleMove(e, true),
2020-04-07 11:47:06 +10:00
},
})
.draggable({
inertia: true,
listeners: {
move: (e) => handleMove(e, false),
},
cursorChecker: () => {
return selectedTool === "pan" && map ? "move" : "default";
2020-04-07 11:47:06 +10:00
},
})
.on("doubletap", (event) => {
event.preventDefault();
if (selectedTool === "pan") {
setTranslateAndScale({ x: 0, y: 0 }, 1);
}
});
return () => {
mapInteract.unset();
};
}, [selectedTool, map]);
2020-03-20 21:46:52 +11:00
// Reset map transform when map changes
useEffect(() => {
setTranslateAndScale({ x: 0, y: 0 }, 1);
}, [map]);
// Bind the wheel event of the map via a ref
// in order to support non-passive event listening
// to allow the track pad zoom to be interrupted
// see https://github.com/facebook/react/issues/14856
useEffect(() => {
const mapContainer = mapContainerRef.current;
function handleZoom(event) {
// Stop overscroll on chrome and safari
// also stop pinch to zoom on chrome
event.preventDefault();
const scale = mapScaleRef.current;
const translate = mapTranslateRef.current;
const deltaY = event.deltaY * zoomSpeed;
const newScale = Math.max(Math.min(scale + deltaY, maxZoom), minZoom);
setTranslateAndScale(translate, newScale);
}
if (mapContainer) {
mapContainer.addEventListener("wheel", handleZoom, {
passive: false,
});
}
return () => {
if (mapContainer) {
mapContainer.removeEventListener("wheel", handleZoom);
}
};
}, []);
/**
* Member setup
*/
const mapRef = useRef(null);
const mapContainerRef = useRef();
const gridX = map && map.gridX;
const gridY = map && map.gridY;
2020-04-20 15:17:56 +10:00
const gridSizeNormalized = { x: 1 / gridX || 0, y: 1 / gridY || 0 };
const tokenSizePercent = gridSizeNormalized.x * 100;
const aspectRatio = (map && map.width / map.height) || 1;
const mapImage = (
<Box
sx={{
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
}}
>
<Image
ref={mapRef}
className="mapImage"
sx={{
width: "100%",
userSelect: "none",
touchAction: "none",
}}
src={map && map.source}
/>
</Box>
);
const mapTokens = (
<Box
sx={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: "none",
}}
>
2020-04-23 17:23:34 +10:00
{mapState &&
Object.values(mapState.tokens).map((token) => (
<MapToken
key={token.id}
token={token}
tokenSizePercent={tokenSizePercent}
className={`${mapTokenProxyClassName} ${mapTokenMenuClassName}`}
/>
))}
</Box>
);
return (
2020-03-20 13:33:12 +11:00
<>
<Box
2020-03-20 13:33:12 +11:00
className="map"
sx={{
flexGrow: 1,
position: "relative",
overflow: "hidden",
backgroundColor: "rgba(0, 0, 0, 0.1)",
userSelect: "none",
2020-04-07 11:47:06 +10:00
touchAction: "none",
}}
2020-03-20 13:33:12 +11:00
bg="background"
ref={mapContainerRef}
>
2020-03-20 13:33:12 +11:00
<Box
sx={{
position: "relative",
top: "50%",
left: "50%",
2020-04-07 11:47:06 +10:00
transform: "translate(-50%, -50%)",
2020-03-20 13:33:12 +11:00
}}
>
<Box ref={mapMoveContainerRef}>
2020-03-20 21:46:52 +11:00
<Box
sx={{
width: "100%",
height: 0,
2020-04-07 11:47:06 +10:00
paddingBottom: `${(1 / aspectRatio) * 100}%`,
2020-03-20 21:46:52 +11:00
}}
/>
{mapImage}
2020-04-18 18:11:21 +10:00
<MapDrawing
width={map ? map.width : 0}
height={map ? map.height : 0}
2020-04-19 00:24:06 +10:00
selectedTool={selectedTool}
shapes={drawnShapes}
onShapeAdd={handleShapeAdd}
onShapeRemove={handleShapeRemove}
brushColor={brushColor}
2020-04-20 15:17:56 +10:00
useGridSnapping={useBrushGridSnapping}
gridSize={gridSizeNormalized}
useBrushBlending={useBrushBlending}
useBrushGesture={useBrushGesture}
2020-04-18 18:11:21 +10:00
/>
{mapTokens}
</Box>
2020-03-20 13:33:12 +11:00
</Box>
2020-04-19 00:24:06 +10:00
<MapControls
onMapChange={onMapChange}
onToolChange={setSelectedTool}
selectedTool={selectedTool}
disabledTools={disabledTools}
2020-04-19 15:15:48 +10:00
onUndo={onMapDrawUndo}
onRedo={onMapDrawRedo}
2020-04-23 17:23:34 +10:00
undoDisabled={!mapState || mapState.drawActionIndex < 0}
redoDisabled={
!mapState ||
mapState.drawActionIndex === mapState.drawActions.length - 1
}
brushColor={brushColor}
onBrushColorChange={setBrushColor}
onEraseAll={handleShapeRemoveAll}
2020-04-20 15:17:56 +10:00
useBrushGridSnapping={useBrushGridSnapping}
onBrushGridSnappingChange={setUseBrushGridSnapping}
useBrushBlending={useBrushBlending}
onBrushBlendingChange={setUseBrushBlending}
useBrushGesture={useBrushGesture}
onBrushGestureChange={setUseBrushGesture}
2020-04-19 00:24:06 +10:00
/>
</Box>
2020-03-20 13:33:12 +11:00
<ProxyToken
tokenClassName={mapTokenProxyClassName}
2020-03-20 13:33:12 +11:00
onProxyDragEnd={handleProxyDragEnd}
/>
<TokenMenu
tokenClassName={mapTokenMenuClassName}
onTokenChange={onMapTokenChange}
/>
2020-03-20 13:33:12 +11:00
</>
);
}
export default Map;