All files / src/components/pages SpritesPage.tsx

0% Statements 0/150
0% Branches 0/124
0% Functions 0/41
0% Lines 0/149

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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styled, { ThemeContext } from "styled-components";
import debounce from "lodash/debounce";
import useResizable from "ui/hooks/use-resizable";
import useWindowSize from "ui/hooks/use-window-size";
import {
  SplitPaneHorizontalDivider,
  SplitPaneVerticalDivider,
} from "ui/splitpane/SplitPaneDivider";
import editorActions from "store/features/editor/editorActions";
import { SpriteEditor } from "components/sprites/SpriteEditor";
import { NavigatorSprites } from "components/sprites/NavigatorSprites";
import {
  spriteAnimationSelectors,
  spriteSheetSelectors,
  spriteStateSelectors,
} from "store/features/entities/entitiesState";
import MetaspriteEditor from "components/sprites/MetaspriteEditor";
import SpriteTilePalette from "components/sprites/SpriteTilePalette";
import SpriteAnimationTimeline from "components/sprites/SpriteAnimationTimeline";
import { SplitPaneHeader } from "ui/splitpane/SplitPaneHeader";
import l10n from "shared/lib/lang/l10n";
import MetaspriteEditorToolsPanel from "components/sprites/MetaspriteEditorToolsPanel";
import { ZoomButton } from "ui/buttons/ZoomButton";
import MetaspriteEditorPreviewSettings from "components/sprites/MetaspriteEditorPreviewSettings";
import spriteActions from "store/features/sprite/spriteActions";
import { clampSidebarWidth } from "renderer/lib/window/sidebar";
import { Button } from "ui/buttons/Button";
import { TargetIcon } from "ui/icons/Icons";
import { FixedSpacer } from "ui/spacing/Spacing";
import { getAnimationNameById } from "renderer/lib/sprites/spriteL10NHelpers";
import { useAppDispatch, useAppSelector } from "store/hooks";
 
const Wrapper = styled.div`
  display: flex;
  width: 100%;
`;
 
const PrecisionIcon = styled(TargetIcon)`
  && {
    height: 16px;
    width: 16px;
    max-width: 16px;
    max-height: 16px;
    margin: -2px 0 0 0;
  }
`;
 
const SpritesPage = () => {
  const dispatch = useAppDispatch();
  const themeContext = useContext(ThemeContext);
  const worldSidebarWidth = useAppSelector(
    (state) => state.editor.worldSidebarWidth
  );
  const navigatorSidebarWidth = useAppSelector(
    (state) => state.editor.navigatorSidebarWidth
  );
  const tilesZoom = useAppSelector((state) => state.editor.zoomSpriteTiles);
  const windowSize = useWindowSize();
  const prevWindowWidthRef = useRef<number>(0);
  const windowWidth = windowSize.width || 0;
  const windowHeight = windowSize.height || 0;
  const minCenterPaneWidth = 0;
 
  const allSprites = useAppSelector((state) =>
    spriteSheetSelectors.selectAll(state)
  );
  const spritesLookup = useAppSelector((state) =>
    spriteSheetSelectors.selectEntities(state)
  );
  const spriteStatesLookup = useAppSelector((state) =>
    spriteStateSelectors.selectEntities(state)
  );
  const spriteAnimationsLookup = useAppSelector((state) =>
    spriteAnimationSelectors.selectEntities(state)
  );
  const selectedId = useAppSelector(
    (state) => state.editor.selectedSpriteSheetId
  );
  const navigationStateId = useAppSelector(
    (state) => state.editor.selectedSpriteStateId
  );
  const animationId = useAppSelector(
    (state) => state.editor.selectedAnimationId
  );
  const metaspriteId = useAppSelector(
    (state) => state.editor.selectedMetaspriteId
  );
  const selectedAdditionalMetaspriteIds = useAppSelector(
    (state) => state.editor.selectedAdditionalMetaspriteIds
  );
  const precisionTileMode = useAppSelector(
    (state) => state.editor.precisionTileMode
  );
  const [tmpPrecisionMode, setTmpPrecisionMode] = useState(false);
 
  const sprite = useAppSelector((state) =>
    spriteSheetSelectors.selectById(state, selectedId)
  );
 
  const lastSpriteId = useRef("");
  useEffect(() => {
    Iif (sprite) {
      lastSpriteId.current = sprite.id;
    }
  }, [sprite]);
 
  const viewSpriteId = useMemo(
    () => sprite?.id || lastSpriteId.current || allSprites[0]?.id,
    [allSprites, sprite]
  );
 
  const selectedSprite = spritesLookup[viewSpriteId];
 
  const selectedState =
    spriteStatesLookup[navigationStateId] ||
    spriteStatesLookup[selectedSprite?.states[0] ?? ""];
 
  const selectedAnimation =
    spriteAnimationsLookup[animationId] ||
    (selectedState && spriteAnimationsLookup[selectedState.animations?.[0]]);
 
  const selectedStateId = selectedState?.id || "";
  const selectedAnimationId = selectedAnimation?.id || "";
  const selectedMetaspriteId =
    metaspriteId || selectedAnimation?.frames[0] || "";
  const frames = useMemo(
    () => selectedAnimation?.frames || [],
    [selectedAnimation?.frames]
  );
  const selectedFrame = frames.indexOf(selectedMetaspriteId);
 
  // If selected frame not found jump to last frame in animation
  useEffect(() => {
    Iif (selectedFrame === -1 && frames.length > 0) {
      dispatch(
        editorActions.setSelectedMetaspriteId(frames[frames.length - 1])
      );
    }
  }, [dispatch, frames, selectedFrame]);
 
  const [leftPaneWidth, setLeftPaneSize, startLeftPaneResize] = useResizable({
    initialSize: navigatorSidebarWidth,
    direction: "right",
    minSize: 50,
    maxSize: Math.max(101, windowWidth - minCenterPaneWidth - 200),
    onResize: (_v) => {
      recalculateRightColumn();
    },
    onResizeComplete: (v) => {
      Iif (v < 200) {
        setLeftPaneSize(200);
      }
      recalculateRightColumn();
    },
  });
  const [rightPaneWidth, setRightPaneSize, onResizeRight] = useResizable({
    initialSize: worldSidebarWidth,
    direction: "left",
    minSize: 280,
    maxSize: Math.max(281, windowWidth - minCenterPaneWidth - 100),
    onResize: (_v) => {
      recalculateLeftColumn();
    },
    onResizeComplete: (width) => {
      if (width > windowWidth - 200) {
        setLeftPaneSize(200);
        setRightPaneSize(windowWidth - 200);
      } else {
        recalculateLeftColumn();
      }
    },
  });
  const [centerPaneHeight, setCenterPaneSize, onResizeCenter] = useResizable({
    initialSize: 231,
    direction: "top",
    minSize: 30,
    maxSize: windowHeight - 100,
  });
  const [animationsOpen, setAnimationsOpen] = useState(true);
 
  useEffect(() => {
    prevWindowWidthRef.current = windowWidth;
  });
  const prevWidth = prevWindowWidthRef.current;
 
  useEffect(() => {
    dispatch(spriteActions.compileSprite({ spriteSheetId: viewSpriteId }));
  }, [dispatch, viewSpriteId]);
 
  useEffect(() => {
    Iif (windowWidth !== prevWidth) {
      const panelsTotalWidth =
        leftPaneWidth + rightPaneWidth + minCenterPaneWidth;
      const widthOverflow = panelsTotalWidth - windowWidth;
      Iif (widthOverflow > 0) {
        setLeftPaneSize(leftPaneWidth - 0.5 * widthOverflow);
        setRightPaneSize(rightPaneWidth - 0.5 * widthOverflow);
      }
    }
  }, [
    windowWidth,
    prevWidth,
    leftPaneWidth,
    setLeftPaneSize,
    rightPaneWidth,
    setRightPaneSize,
  ]);
 
  const debouncedStoreWidths = useRef(
    debounce((leftPaneWidth: number, rightPaneWidth: number) => {
      dispatch(
        editorActions.resizeWorldSidebar(clampSidebarWidth(rightPaneWidth))
      );
      dispatch(editorActions.resizeNavigatorSidebar(leftPaneWidth));
    }, 100)
  );
 
  useEffect(
    () => debouncedStoreWidths.current(leftPaneWidth, rightPaneWidth),
    [leftPaneWidth, rightPaneWidth]
  );
 
  const recalculateLeftColumn = () => {
    const newWidth = Math.min(
      leftPaneWidth,
      windowWidth - rightPaneWidth - minCenterPaneWidth
    );
    Iif (newWidth !== leftPaneWidth) {
      setLeftPaneSize(newWidth);
    }
  };
 
  const recalculateRightColumn = () => {
    const newWidth = Math.min(
      rightPaneWidth,
      windowWidth - leftPaneWidth - minCenterPaneWidth
    );
    Iif (newWidth !== rightPaneWidth) {
      setRightPaneSize(newWidth);
    }
  };
 
  const toggleTilesPane = useCallback(() => {
    if (centerPaneHeight === 30) {
      setCenterPaneSize(231);
    } else {
      setCenterPaneSize(30);
    }
  }, [centerPaneHeight, setCenterPaneSize]);
 
  const toggleAnimationsPane = useCallback(() => {
    setAnimationsOpen(!animationsOpen);
  }, [animationsOpen, setAnimationsOpen]);
 
  const onZoomIn = useCallback(() => {
    dispatch(editorActions.zoomIn({ section: "spriteTiles" }));
  }, [dispatch]);
 
  const onZoomOut = useCallback(() => {
    dispatch(editorActions.zoomOut({ section: "spriteTiles" }));
  }, [dispatch]);
 
  const onZoomReset = useCallback(() => {
    dispatch(editorActions.zoomReset({ section: "spriteTiles" }));
  }, [dispatch]);
 
  const onTogglePrecisionTiles = useCallback(
    (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
      e.stopPropagation();
      dispatch(editorActions.setPrecisionTileMode(!precisionTileMode));
    },
    [dispatch, precisionTileMode]
  );
 
  const handleKeys = useCallback((e: KeyboardEvent) => {
    Iif (e.altKey) {
      setTmpPrecisionMode(true);
    }
  }, []);
 
  const handleKeysUp = useCallback((e: KeyboardEvent) => {
    Iif (!e.altKey) {
      setTmpPrecisionMode(false);
    }
  }, []);
 
  useEffect(() => {
    window.addEventListener("keydown", handleKeys);
    window.addEventListener("keyup", handleKeysUp);
 
    return () => {
      window.removeEventListener("keydown", handleKeys);
      window.removeEventListener("keyup", handleKeysUp);
    };
  });
 
  return (
    <Wrapper>
      <div
        style={{
          transition: "opacity 0.3s ease-in-out",
          width: Math.max(200, leftPaneWidth),
          background: themeContext?.colors.sidebar.background,
          overflow: "hidden",
          position: "relative",
        }}
      >
        <div
          style={{
            minWidth: 200,
            position: "relative",
            width: "100%",
            height: "100%",
          }}
        >
          <NavigatorSprites
            height={windowHeight - 38}
            selectedId={selectedId}
            viewId={viewSpriteId}
            selectedAnimationId={selectedAnimationId}
            selectedStateId={selectedStateId}
            defaultFirst
          />
        </div>
      </div>
      <SplitPaneHorizontalDivider onMouseDown={startLeftPaneResize} />
      <div
        style={{
          flex: "1 1 0",
          minWidth: 0,
          overflow: "hidden",
          background: themeContext?.colors.background,
          color: themeContext?.colors.text,
          height: windowHeight - 38,
          position: "relative",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div style={{ flexGrow: 1, position: "relative" }}>
          <MetaspriteEditorToolsPanel
            selectedAnimationId={selectedAnimationId}
            metaspriteId={selectedMetaspriteId}
          />
          {frames.map((frameId) => (
            <MetaspriteEditor
              key={frameId}
              spriteSheetId={viewSpriteId}
              metaspriteId={frameId}
              animationId={selectedAnimation?.id || ""}
              spriteStateId={selectedStateId}
              hidden={frameId !== selectedMetaspriteId}
            />
          ))}
 
          <MetaspriteEditorPreviewSettings
            spriteSheetId={viewSpriteId}
            metaspriteId={selectedMetaspriteId}
          />
        </div>
        <SplitPaneVerticalDivider onMouseDown={onResizeCenter} />
        <div style={{ position: "relative", height: centerPaneHeight }}>
          <SplitPaneHeader
            onToggle={toggleTilesPane}
            collapsed={centerPaneHeight === 30}
            buttons={
              centerPaneHeight > 30 && (
                <>
                  <Button
                    size="small"
                    variant={
                      precisionTileMode || tmpPrecisionMode
                        ? "primary"
                        : "transparent"
                    }
                    onClick={onTogglePrecisionTiles}
                    title={`${l10n("FIELD_PRECISION_SELECTION")}${
                      precisionTileMode ? ` (${l10n("FIELD_ENABLED")})` : ""
                    }`}
                  >
                    <PrecisionIcon />
                  </Button>
                  <FixedSpacer width={5} />
                  <ZoomButton
                    zoom={tilesZoom}
                    size="small"
                    variant="transparent"
                    title={l10n("TOOLBAR_ZOOM_RESET")}
                    titleIn={l10n("TOOLBAR_ZOOM_IN")}
                    titleOut={l10n("TOOLBAR_ZOOM_OUT")}
                    onZoomIn={onZoomIn}
                    onZoomOut={onZoomOut}
                    onZoomReset={onZoomReset}
                  />
                </>
              )
            }
          >
            {l10n("FIELD_TILES")}
          </SplitPaneHeader>
          <SpriteTilePalette
            id={viewSpriteId}
            precisionMode={precisionTileMode || tmpPrecisionMode}
          />
        </div>
        <SplitPaneVerticalDivider />
        <SplitPaneHeader
          onToggle={toggleAnimationsPane}
          collapsed={!animationsOpen}
        >
          {l10n("FIELD_FRAMES")}
          {selectedState &&
            `: ${getAnimationNameById(
              selectedState.animationType,
              selectedState.flipLeft,
              selectedAnimationId,
              selectedState.animations
            )}`}
        </SplitPaneHeader>
        {animationsOpen && (
          <SpriteAnimationTimeline
            spriteSheetId={viewSpriteId}
            animationId={selectedAnimation?.id || ""}
            metaspriteId={selectedMetaspriteId}
            additionalMetaspriteIds={selectedAdditionalMetaspriteIds}
          />
        )}
      </div>
      <SplitPaneHorizontalDivider onMouseDown={onResizeRight} />
      <div
        style={{
          width: rightPaneWidth,
          background: themeContext?.colors.sidebar.background,
          height: "100%",
          overflow: "hidden",
          position: "relative",
        }}
      >
        <SpriteEditor
          id={viewSpriteId}
          metaspriteId={selectedMetaspriteId}
          spriteStateId={selectedStateId}
          animationId={selectedAnimation?.id || ""}
        />
      </div>
    </Wrapper>
  );
};
 
export default SpritesPage;