algospaced-dsa / algospaced-ui /src /components /map /PencilMapCanvas.tsx
iamfebin's picture
feat: FSRS card manager, fantasy cartography art polish, and map progression effects
f0175ec
Raw History Blame Contribute Delete
8.38 kB
import React, { useRef, useEffect, useCallback, useState } from 'react';
import type { MapNode, MapTheme } from '../../types/mapTypes';
import { MAP_WIDTH, MAP_HEIGHT } from '../../data/mapData';
import { TerrainDrawings } from './TerrainDrawings';
import { MapBorderAndFilters } from './MapBorderAndFilters';
import { CurvyPathAndNodes } from './CurvyPathAndNodes';
interface PencilMapCanvasProps {
nodes: MapNode[];
activeNodeIndex: number;
completions: Set<number>;
theme: MapTheme;
showLabels: boolean;
showGrid: boolean;
showNodeNumbers: boolean;
autoCenterOnActive: boolean;
onNodeClick: (index: number) => void;
hoveredNodeIndex: number | null;
setHoveredNodeIndex: (index: number | null) => void;
transform: { x: number; y: number; scale: number };
setTransform: React.Dispatch<React.SetStateAction<{ x: number; y: number; scale: number }>>;
}
export const PencilMapCanvas: React.FC<PencilMapCanvasProps> = ({
nodes,
activeNodeIndex,
completions,
theme,
showLabels,
showGrid,
showNodeNumbers,
autoCenterOnActive,
onNodeClick,
hoveredNodeIndex,
setHoveredNodeIndex,
transform,
setTransform,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const isDraggingRef = useRef(false);
const dragStartRef = useRef({ x: 0, y: 0 });
const touchDistRef = useRef<number | null>(null);
const wheelTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [isDirectInteracting, setIsDirectInteracting] = useState(false);
const transformRef = useRef(transform);
transformRef.current = transform;
// Center on active node smoothly
const centerOnNode = useCallback(
(nodeIdx: number) => {
if (!containerRef.current || nodeIdx < 0 || nodeIdx >= nodes.length) return;
const node = nodes[nodeIdx];
const { clientWidth, clientHeight } = containerRef.current;
const currentScale = transformRef.current.scale;
const targetScale = Math.max(currentScale, 0.9);
const targetX = clientWidth / 2 - node.x * targetScale;
const targetY = clientHeight / 2 - node.y * targetScale;
setTransform({
x: targetX,
y: targetY,
scale: targetScale,
});
},
[nodes, setTransform]
);
useEffect(() => {
if (autoCenterOnActive && activeNodeIndex >= 0) {
centerOnNode(activeNodeIndex);
}
}, [activeNodeIndex, autoCenterOnActive, centerOnNode]);
// Initial fit to screen when autoCenterOnActive is disabled or node is not yet ready
useEffect(() => {
if (containerRef.current && (!autoCenterOnActive || activeNodeIndex < 0)) {
const { clientWidth, clientHeight } = containerRef.current;
const scaleX = clientWidth / MAP_WIDTH;
const scaleY = clientHeight / MAP_HEIGHT;
const fitScale = Math.min(scaleX, scaleY) * 0.9;
const initialX = (clientWidth - MAP_WIDTH * fitScale) / 2;
const initialY = (clientHeight - MAP_HEIGHT * fitScale) / 2;
setTransform({
x: initialX,
y: initialY,
scale: Math.max(fitScale, 0.08),
});
}
}, [setTransform, autoCenterOnActive, activeNodeIndex]);
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault();
if (!containerRef.current) return;
setIsDirectInteracting(true);
if (wheelTimerRef.current) clearTimeout(wheelTimerRef.current);
wheelTimerRef.current = setTimeout(() => setIsDirectInteracting(false), 140);
const rect = containerRef.current.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const zoomFactor = e.deltaY < 0 ? 1.15 : 0.85;
const newScale = Math.min(Math.max(transform.scale * zoomFactor, 0.08), 3.5);
const newX = mouseX - ((mouseX - transform.x) / transform.scale) * newScale;
const newY = mouseY - ((mouseY - transform.y) / transform.scale) * newScale;
setTransform({
x: newX,
y: newY,
scale: newScale,
});
};
const handleMouseDown = (e: React.MouseEvent) => {
if (e.button !== 0) return;
isDraggingRef.current = true;
setIsDirectInteracting(true);
dragStartRef.current = {
x: e.clientX - transform.x,
y: e.clientY - transform.y,
};
};
const handleMouseMove = (e: React.MouseEvent) => {
if (!isDraggingRef.current) return;
setTransform((prev) => ({
...prev,
x: e.clientX - dragStartRef.current.x,
y: e.clientY - dragStartRef.current.y,
}));
};
const handleMouseUp = () => {
isDraggingRef.current = false;
setIsDirectInteracting(false);
};
const handleTouchStart = (e: React.TouchEvent) => {
setIsDirectInteracting(true);
if (e.touches.length === 1) {
isDraggingRef.current = true;
dragStartRef.current = {
x: e.touches[0].clientX - transform.x,
y: e.touches[0].clientY - transform.y,
};
} else if (e.touches.length === 2) {
isDraggingRef.current = false;
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
touchDistRef.current = Math.hypot(dx, dy);
}
};
const handleTouchMove = (e: React.TouchEvent) => {
if (e.touches.length === 1 && isDraggingRef.current) {
setTransform((prev) => ({
...prev,
x: e.touches[0].clientX - dragStartRef.current.x,
y: e.touches[0].clientY - dragStartRef.current.y,
}));
} else if (e.touches.length === 2 && touchDistRef.current && containerRef.current) {
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
const dist = Math.hypot(dx, dy);
const factor = dist / touchDistRef.current;
touchDistRef.current = dist;
const rect = containerRef.current.getBoundingClientRect();
const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2 - rect.left;
const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2 - rect.top;
setTransform((prev) => {
const newScale = Math.min(Math.max(prev.scale * factor, 0.08), 3.5);
return {
scale: newScale,
x: midX - ((midX - prev.x) / prev.scale) * newScale,
y: midY - ((midY - prev.y) / prev.scale) * newScale,
};
});
}
};
const handleTouchEnd = () => {
isDraggingRef.current = false;
touchDistRef.current = null;
setIsDirectInteracting(false);
};
const isParchmentDark = theme.id !== 'parchment';
return (
<div
id="pencil-map-container"
ref={containerRef}
className={`relative w-full h-full overflow-hidden canvas-interactive select-none ${isParchmentDark ? 'parchment-dark-bg' : 'parchment-bg'
}`}
onWheel={handleWheel}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
{/* Vintage Vignette Overlay */}
<div
className={`absolute inset-0 pointer-events-none z-10 ${isParchmentDark ? 'map-dark-vignette' : 'map-vignette'
}`}
/>
{/* SVG Canvas with Transform Matrix */}
<svg
id="pencil-map-svg"
viewBox={`0 0 ${MAP_WIDTH} ${MAP_HEIGHT}`}
width={MAP_WIDTH}
height={MAP_HEIGHT}
style={{
transform: `translate(${transform.x}px, ${transform.y}px) scale(${transform.scale})`,
transformOrigin: '0 0',
transition: isDirectInteracting
? 'none'
: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
}}
className="absolute top-0 left-0"
>
<MapBorderAndFilters theme={theme} showGrid={showGrid} />
<TerrainDrawings
theme={theme}
showLabels={showLabels}
finalNode={nodes[nodes.length - 1]}
completedCount={completions.size}
totalNodes={nodes.length}
/>
<CurvyPathAndNodes
nodes={nodes}
activeNodeIndex={activeNodeIndex}
completions={completions}
theme={theme}
showNodeNumbers={showNodeNumbers}
onNodeClick={onNodeClick}
hoveredNodeIndex={hoveredNodeIndex}
setHoveredNodeIndex={setHoveredNodeIndex}
/>
</svg>
</div>
);
};