Files
grungnet/src/components/Map.js

121 lines
2.8 KiB
JavaScript
Raw Normal View History

import React, { useRef } from "react";
import { Box, Image } from "theme-ui";
import Token from "../components/Token";
2020-03-20 13:33:12 +11:00
import ProxyToken from "../components/ProxyToken";
import AddMapButton from "../components/AddMapButton";
2020-03-20 13:33:12 +11:00
const mapTokenClassName = "map-token";
const defaultTokenSize = 48;
2020-03-20 13:33:12 +11:00
function Map({
mapSource,
mapData,
tokens,
onMapTokenMove,
onMapTokenRemove,
onMapChanged
}) {
2020-03-20 13:33:12 +11:00
function handleProxyDragEnd(isOnMap, token) {
if (isOnMap && onMapTokenMove) {
onMapTokenMove(token);
}
if (!isOnMap && onMapTokenRemove) {
onMapTokenRemove(token);
}
}
const mapRef = useRef(null);
const rows = mapData && mapData.rows;
const tokenSizePercent = (1 / rows) * 100;
const aspectRatio = (mapData && mapData.width / mapData.height) || 1;
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)"
}}
2020-03-20 13:33:12 +11:00
bg="background"
>
2020-03-20 13:33:12 +11:00
<Box
sx={{
position: "relative",
overflow: "hidden",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)"
2020-03-20 13:33:12 +11:00
}}
>
<Box
sx={{
width: "100%",
height: 0,
paddingBottom: `${(1 / aspectRatio) * 100}%`
}}
/>
<Box
sx={{ position: "absolute", top: 0, right: 0, bottom: 0, left: 0 }}
>
<Image ref={mapRef} id="map" src={mapSource} />
</Box>
<Box
sx={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0
}}
>
{Object.values(tokens).map(token => (
<Box
key={token.id}
style={{
left: `${token.x * 100}%`,
top: `${token.y * 100}%`,
width: `${tokenSizePercent}%`
}}
sx={{
position: "absolute",
display: "flex"
}}
>
<Token
tokenId={token.id}
image={token.image}
className={mapTokenClassName}
/>
</Box>
))}
</Box>
2020-03-20 13:33:12 +11:00
</Box>
<Box
p={2}
sx={{
position: "absolute",
top: "0",
left: "50%",
transform: "translateX(-50%)"
}}
>
<AddMapButton onMapChanged={onMapChanged} />
</Box>
</Box>
2020-03-20 13:33:12 +11:00
<ProxyToken
tokenClassName={mapTokenClassName}
onProxyDragEnd={handleProxyDragEnd}
size={defaultTokenSize}
2020-03-20 13:33:12 +11:00
/>
</>
);
}
export default Map;