All files / src/widgets/viewport/ui EditorViewport.tsx

59.18% Statements 29/49
29.41% Branches 5/17
38.46% Functions 5/13
61.36% Lines 27/44

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                                                                                  1x           6x 6x     6x     6x 12x 6x 6x       6x   6x                                 6x       6x       6x 6x   1x                       6x             6x   6x 6x 6x 6x         6x 6x                 6x                     6x                         6x                           6x                                                                                                                                                                  
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
 
import { layersSelectors, makeSelectByProject } from '@/entities/layer/model/selectors';
import { updateLayer, useLayerCanvases } from '@/entities/layer/model';
import { selectActiveTool } from '@/entities/editor/model/selectors';
 
import { BrushTool, useBrushDraw } from '@/entities/brush/model';
import { LineTool, useLineDraw } from '@/entities/line/model';
import { ShapeTool, useShapeDraw } from '@/entities/shape/model';
import { EraserTool, useEraserDraw } from '@/entities/eraser/model';
 
import { ToolBar, UndoRedoButtons } from '@/widgets/toolbar/ui';
import { useViewportControls } from '@/widgets/viewport/hooks';
 
import { DrawCanvas, GridCanvas, LayerStack } from '@/widgets/canvas/model';
import type { EditorTool } from '@/shared/types';
 
interface ToolHandlers {
	onPointerDown?: (e: React.PointerEvent<HTMLCanvasElement>) => void;
	onPointerMove?: (e: React.PointerEvent<HTMLCanvasElement>) => void;
	onPointerUp?: (e: React.PointerEvent<HTMLCanvasElement>) => void;
}
 
interface EditorViewportProps {
	projectId: string;
	width: number;
	height: number;
	onViewportUpdate?: (data: {
		scale: number;
		offsetX: number;
		offsetY: number;
		showGrid: boolean;
		handleFit: () => void;
		handleReset: () => void;
		toggleGrid: () => void;
	}) => void;
}
 
type ActiveEditorTool = Exclude<EditorTool, null>;
 
export const EditorViewport = React.memo(function EditorViewport({
	projectId,
	width,
	height,
	onViewportUpdate,
}: EditorViewportProps) {
	const dispatch = useAppDispatch();
	const didDrawRef = useRef(false);
 
	// Current active tool from Redux (brush / line / shape / eraser / null)
	const activeTool = useAppSelector(selectActiveTool);
 
	// Layers for this project
	const selectByProject = useMemo(makeSelectByProject, []);
	const layersAll = useAppSelector((s) => selectByProject(s, projectId));
	const layers = useMemo(
		() => [...layersAll].sort((a, b) => a.zIndex - b.zIndex),
		[layersAll],
	);
 
	const activeLayer = useAppSelector(layersSelectors.selectActiveLayer);
 
	const [viewportBase, setViewportBase] = useState({
		scale: 1,
		offsetX: 0,
		offsetY: 0,
	});
 
	const {
		containerRef,
		isPanning,
		showGrid,
		setShowGrid,
		onMouseDown,
		onMouseMove,
		onMouseUp,
		onWheel,
		handleFit,
		handleReset,
	} = useViewportControls(width, height, (data) => {
		setViewportBase(data);
	});
 
	const toggleGrid = useCallback(() => {
		setShowGrid((prev) => !prev);
	}, [setShowGrid]);
 
	useEffect(() => {
		if (!onViewportUpdate) return;
 
		onViewportUpdate({
			scale: viewportBase.scale,
			offsetX: viewportBase.offsetX,
			offsetY: viewportBase.offsetY,
			showGrid,
			handleFit,
			handleReset,
			toggleGrid,
		});
	}, [onViewportUpdate, viewportBase, showGrid, handleFit, handleReset, toggleGrid]);
 
	// Canvas refs and drawing logic
	const { bindCanvasRef, getCanvas } = useLayerCanvases(
		layers,
		projectId,
		width,
		height,
	);
 
	const drawRef = useRef<HTMLCanvasElement | null>(null);
 
	const brushHandlers = useBrushDraw(drawRef);
	const lineHandlers = useLineDraw(drawRef);
	const shapeHandlers = useShapeDraw(drawRef);
	const eraserHandlers = useEraserDraw(() =>
		activeLayer ? getCanvas(activeLayer.id) : null,
	);
 
	// Stable map of handlers per tool type.
	const toolHandlers: Partial<Record<ActiveEditorTool, ToolHandlers>> = useMemo(
		() => ({
			brush: brushHandlers,
			line: lineHandlers,
			shape: shapeHandlers,
			eraser: eraserHandlers,
		}),
		[brushHandlers, lineHandlers, shapeHandlers, eraserHandlers],
	);
 
	const activeHandlers = activeTool
		? toolHandlers[activeTool as ActiveEditorTool]
		: undefined;
 
	// ───────────── Tool event handlers (pointer) ─────────────
 
	/**
	 * Pointer down:
	 * - reset "didDraw" flag,
	 * - delegate to active tool handlers.
	 */
	const handlePointerDown = useCallback(
		(e: React.PointerEvent<HTMLCanvasElement>) => {
			didDrawRef.current = false;
			activeHandlers?.onPointerDown?.(e);
		},
		[activeHandlers],
	);
 
	/**
	 * Pointer move:
	 * - delegate to active tool,
	 * - mark that this stroke has drawn something.
	 */
	const handlePointerMove = useCallback(
		(e: React.PointerEvent<HTMLCanvasElement>) => {
			activeHandlers?.onPointerMove?.(e);
			didDrawRef.current = true;
		},
		[activeHandlers],
	);
 
	/**
	 * Pointer up:
	 * - finish tool handling,
	 * - if we actually drew something, merge draw canvas into active layer
	 *   and save snapshot via Redux.
	 */
	const handlePointerUp = useCallback(
		async (e: React.PointerEvent<HTMLCanvasElement>) => {
			activeHandlers?.onPointerUp?.(e);
 
			if (!didDrawRef.current || !activeLayer || !activeTool) return;
 
			const target = getCanvas(activeLayer.id);
			const drawCanvas = drawRef.current;
 
			if (target && drawCanvas) {
				const ctx = target.getContext('2d');
				ctx?.drawImage(drawCanvas, 0, 0);
 
				// Clear draw canvas after applying stroke
				drawCanvas
					.getContext('2d', { willReadFrequently: true, alpha: true })
					?.clearRect(0, 0, width, height);
 
				const snapshot = target.toDataURL('image/png');
 
				await dispatch(
					updateLayer({
						id: activeLayer.id,
						changes: { snapshot },
					}),
				).unwrap();
			}
		},
		[activeHandlers, activeLayer, activeTool, dispatch, getCanvas, width, height],
	);
 
	return (
		<div
			data-testid="viewport-container"
			className="relative w-full h-full bg-gray-100 dark:bg-gray-900 flex items-center justify-center select-none overflow-hidden"
			onMouseDown={onMouseDown}
			onMouseMove={onMouseMove}
			onMouseUp={onMouseUp}
			onWheel={onWheel}
		>
			<div
				ref={containerRef}
				style={{
					width,
					height,
					position: 'relative',
					border: '1px solid rgba(0, 0, 0, 0.2)',
					background: '#ffffff',
				}}
			>
				<GridCanvas width={width} height={height} showGrid={showGrid} />
 
				<LayerStack
					layers={layers}
					width={width}
					height={height}
					bindCanvasRef={bindCanvasRef}
					activeLayerId={activeLayer?.id ?? null}
				/>
 
				<DrawCanvas
					ref={drawRef}
					width={width}
					height={height}
					onPointerDown={handlePointerDown}
					onPointerMove={handlePointerMove}
					onPointerUp={handlePointerUp}
					isPanning={isPanning}
				/>
			</div>
 
			<ToolBar position="left">
				<BrushTool />
				<LineTool />
				<ShapeTool />
				<EraserTool />
				<UndoRedoButtons />
			</ToolBar>
		</div>
	);
});