All files / src/components/world/entities/scenes SceneResizeHandles.tsx

98.73% Statements 78/79
67.39% Branches 31/46
100% Functions 17/17
98.71% Lines 77/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 2792x 2x 2x 2x 2x                                       2x 2x 2x 2x   2x     16x       16x                                   16x       2x               2x           2x 2x                         2x         2x           10x 10x 10x 10x 10x 10x 10x 10x   10x 6x       6x             6x 3x 3x 3x     4x       4x             4x 2x 2x 2x       10x                                     2x               4x 4x 4x   4x 1x 1x     1x           1x                         4x   1x 1x 1x 1x           4x 1x 1x   1x 1x 1x 1x     4x 1x 1x 1x         4x 16x 1x 1x 1x                       1x 1x 1x         4x                                 16x                     2x  
import React, { useCallback, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import { MAX_SCENE_TILE_COUNT, TILE_SIZE } from "consts";
import { useAppDispatch } from "store/hooks";
import entitiesActions from "store/features/entities/entitiesActions";
 
export type ResizeEdge = "top" | "right" | "bottom" | "left";
 
export interface ResizeGeometry {
  x: number;
  y: number;
  width: number;
  height: number;
  shiftX: number;
  shiftY: number;
}
 
export interface ResizeStart extends ResizeGeometry {
  edge: ResizeEdge;
  pageX: number;
  pageY: number;
  preview: ResizeGeometry;
}
 
const HANDLE_SIZE = 5;
const MIN_WIDTH = 20;
const MIN_HEIGHT = 18;
const MAX_SIZE = 255;
 
const Handle = styled.div<{ $edge: ResizeEdge }>`
  position: absolute;
  z-index: 300;
  background: ${(props) => props.theme.colors.highlight};
  opacity: 0;
 
  ${(props) =>
    props.$edge === "left" || props.$edge === "right"
      ? `
        top: 0;
        bottom: 0;
        width: ${HANDLE_SIZE}px;
        ${props.$edge}: -${HANDLE_SIZE}px;
        cursor: ew-resize;
      `
      : `
        left: 0;
        right: 0;
        height: ${HANDLE_SIZE}px;
        ${props.$edge}: -${HANDLE_SIZE}px;
        cursor: ns-resize;
      `}
 
  &:hover {
    opacity: 0.5;
    outline: 2px solid ${(props) => props.theme.colors.highlight};
  }
`;
 
const Preview = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  z-index: 250;
  pointer-events: none;
  box-sizing: border-box;
  border: 2px solid ${(props) => props.theme.colors.highlight};
 
  span {
    position: relative;
    border-radius: 40px;
    padding: 5px 10px;
    background: ${(props) => props.theme.colors.highlight};
    color: ${(props) => props.theme.colors.highlightText};
  }
 
  &:before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    background: ${(props) => props.theme.colors.highlight};
    opacity: 0.3;
  }
`;
 
export const resizeGeometry = (
  start: ResizeStart,
  pageX: number,
  pageY: number,
  zoomRatio: number,
): ResizeGeometry => {
  const deltaX = Math.round((pageX - start.pageX) / zoomRatio / TILE_SIZE);
  const deltaY = Math.round((pageY - start.pageY) / zoomRatio / TILE_SIZE);
  let nextX = start.x;
  let nextY = start.y;
  let nextWidth = start.width;
  let nextHeight = start.height;
  let shiftX = 0;
  let shiftY = 0;
 
  if (start.edge === "left" || start.edge === "right") {
    const maxWidth = Math.min(
      MAX_SIZE,
      Math.floor(MAX_SCENE_TILE_COUNT / start.height),
    );
    nextWidth = Math.max(
      MIN_WIDTH,
      Math.min(
        maxWidth,
        start.width + (start.edge === "left" ? -deltaX : deltaX),
      ),
    );
    if (start.edge === "left") {
      const delta = start.width - nextWidth;
      nextX = start.x + delta * TILE_SIZE;
      shiftX = -delta;
    }
  } else {
    const maxHeight = Math.min(
      MAX_SIZE,
      Math.floor(MAX_SCENE_TILE_COUNT / start.width),
    );
    nextHeight = Math.max(
      MIN_HEIGHT,
      Math.min(
        maxHeight,
        start.height + (start.edge === "top" ? -deltaY : deltaY),
      ),
    );
    if (start.edge === "top") {
      const delta = start.height - nextHeight;
      nextY = start.y + delta * TILE_SIZE;
      shiftY = -delta;
    }
  }
 
  return {
    x: nextX,
    y: nextY,
    width: nextWidth,
    height: nextHeight,
    shiftX,
    shiftY,
  };
};
 
interface SceneResizeHandlesProps {
  sceneId: string;
  x: number;
  y: number;
  width: number;
  height: number;
  zoomRatio: number;
}
 
const SceneResizeHandles = ({
  sceneId,
  x,
  y,
  width,
  height,
  zoomRatio,
}: SceneResizeHandlesProps) => {
  const dispatch = useAppDispatch();
  const drag = useRef<ResizeStart | undefined>(undefined);
  const [preview, setPreview] = useState<ResizeGeometry>();
 
  const commitResize = useCallback(() => {
    const next = drag.current?.preview;
    Iif (!next) {
      return;
    }
    Eif (
      next.x !== x ||
      next.y !== y ||
      next.width !== width ||
      next.height !== height
    ) {
      dispatch(
        entitiesActions.resizeTilemapLayers({
          sceneId,
          ...next,
          resizeAxis:
            drag.current?.edge === "left" || drag.current?.edge === "right"
              ? "width"
              : "height",
        }),
      );
    }
  }, [dispatch, height, sceneId, width, x, y]);
 
  const onMouseMove = useCallback(
    (e: MouseEvent) => {
      Eif (drag.current) {
        const next = resizeGeometry(drag.current, e.pageX, e.pageY, zoomRatio);
        drag.current.preview = next;
        setPreview(next);
      }
    },
    [zoomRatio],
  );
 
  const onMouseUp = useCallback(() => {
    Eif (drag.current) {
      commitResize();
    }
    drag.current = undefined;
    setPreview(undefined);
    window.removeEventListener("mousemove", onMouseMove);
    window.removeEventListener("mouseup", onMouseUp);
  }, [commitResize, onMouseMove]);
 
  useEffect(
    () => () => {
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", onMouseUp);
    },
    [onMouseMove, onMouseUp],
  );
 
  const onMouseDown = useCallback(
    (edge: ResizeEdge) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
      e.preventDefault();
      e.stopPropagation();
      drag.current = {
        edge,
        pageX: e.pageX,
        pageY: e.pageY,
        x,
        y,
        width,
        height,
        shiftX: 0,
        shiftY: 0,
        preview: { x, y, width, height, shiftX: 0, shiftY: 0 },
      };
      setPreview(drag.current.preview);
      window.addEventListener("mousemove", onMouseMove);
      window.addEventListener("mouseup", onMouseUp);
    },
    [height, onMouseMove, onMouseUp, width, x, y],
  );
 
  return (
    <>
      {preview && (
        <Preview
          style={{
            left: preview.x - x,
            top: preview.y - y,
            width: preview.width * TILE_SIZE,
            height: preview.height * TILE_SIZE,
          }}
        >
          <span>
            {preview.width} x {preview.height}
          </span>
        </Preview>
      )}
      {(["top", "right", "bottom", "left"] as ResizeEdge[]).map((edge) => (
        <Handle
          key={edge}
          data-testid={`scene-resize-${edge}`}
          $edge={edge}
          onMouseDown={onMouseDown(edge)}
        />
      ))}
    </>
  );
};
 
export default SceneResizeHandles;