Fix 3D view and layout view #4

Merged
rust merged 4 commits from test into main 2025-12-27 22:25:53 +03:00
2 changed files with 136 additions and 138 deletions

View File

@@ -13,25 +13,21 @@ type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
// State for interaction
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); // Proposed new line axis
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); // Normalized 0-1
// State
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null);
const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);
// Constants
const SNAP_THRESHOLD = 0.02; // Reduced threshold slightly for better precision on large grid
const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width;
const viewBoxH = viewBoxW * aspectRatio;
// Helpers to calculate cell dimensions
// IMPORTANT: Dependencies must be correct. dragging updates splits, which updates sortedX/Y
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]);
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
// Handlers
const handleMouseMove = (e: React.MouseEvent) => {
// --- Глобальный обработчик (для пустого места и перетаскивания) ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
@@ -39,101 +35,85 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setMousePos({ x: nx, y: ny });
// 1. Если тащим - обновляем позицию
if (dragging) {
// Move logic
// IMPORTANT: Create NEW array references so useMemo in this component and parent components detect changes
const newSplits = {
x: [...splits.x],
y: [...splits.y]
};
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
return;
}
// Hover logic: Check if near existing lines
let foundSplit = null;
// Check X splits (Vertical lines)
splits.x.forEach((val, idx) => {
if (Math.abs(nx - val) < SNAP_THRESHOLD) foundSplit = { axis: 'x' as Axis, index: idx };
});
// 2. Если мы здесь, значит мышка НЕ на существующей линии
// (иначе событие было бы перехвачено в handleSplitHover)
setHoveredSplit(null);
// Check Y splits (Horizontal lines)
if (!foundSplit) {
splits.y.forEach((val, idx) => {
if (Math.abs(ny - val) < SNAP_THRESHOLD) foundSplit = { axis: 'y' as Axis, index: idx };
});
// 3. Логика Фантомной линии (создание новой)
const SNAP_THRESHOLD = 0.02;
// Проверяем, не слишком ли мы близко к краям или другим линиям (чтобы не спамить)
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
const distLeft = nx;
const distRight = 1 - nx;
const distTop = ny;
const distBottom = 1 - ny;
const minXDist = Math.min(distLeft, distRight);
const minYDist = Math.min(distTop, distBottom);
// Определяем ось по близости к краю
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
let valid = true;
if (potentialAxis === 'x') {
if (closeToX || closeToEdgeX) valid = false;
} else {
if (closeToY || closeToEdgeY) valid = false;
}
setHoveredSplit(foundSplit);
// Auto-detect axis for NEW lines if not hovering existing
// AND if not too close to other lines
if (!foundSplit) {
// Check proximity to ALL lines to prevent creating duplicates
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);
// Also check edges (0 and 1)
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
if (closeToX || closeToEdgeX) {
// Too close to X line or edge, don't allow vertical split here
// But might allow horizontal?
// Actually if we are close to an X line, we probably want to select it, which is handled by foundSplit.
// If foundSplit is null but closeToX is true, it means we are just outside threshold?
// Let's simplified: if too close to any parallel line, disable creation.
}
const distLeft = nx;
const distRight = 1 - nx;
const distTop = ny;
const distBottom = 1 - ny;
const minXDist = Math.min(distLeft, distRight);
const minYDist = Math.min(distTop, distBottom);
// Determine potential axis
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
// Validate proximity for that axis
let valid = true;
if (potentialAxis === 'x') {
if (closeToX || closeToEdgeX) valid = false;
} else {
if (closeToY || closeToEdgeY) valid = false;
}
if (valid) {
setPhantomAxis(potentialAxis);
} else {
setPhantomAxis(null);
}
if (valid) {
setPhantomAxis(potentialAxis);
} else {
setPhantomAxis(null);
}
};
// --- Обработчик наведения на КОНКРЕТНУЮ линию ---
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
// Если мы тащим линию, позволяем событию всплыть до глобального обработчика,
// чтобы он посчитал координаты.
if (dragging) return;
// Если просто водим мышкой - блокируем всплытие,
// чтобы глобальный обработчик не думал, что мы в пустоте.
e.stopPropagation();
setHoveredSplit({ axis, index });
setPhantomAxis(null); // Убираем фантом, раз мы на линии
};
const handleMouseDown = (e: React.MouseEvent) => {
// Клик по существующей линии (hoveredSplit уже установлен через onMouseMove линии)
if (hoveredSplit) {
// Start Dragging
if (e.button === 0) { // Left click
if (e.button === 0) {
setDragging(hoveredSplit);
} else if (e.button === 2) { // Right click
} else if (e.button === 2) {
removeSplit(hoveredSplit.axis, hoveredSplit.index);
}
} else if (phantomAxis) {
// Create New Split
}
// Клик по пустому месту (создание)
else if (phantomAxis) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits);
// Immediately start dragging the new line for fine-tuning
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
};
@@ -167,7 +147,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<div className="flex flex-col h-full select-none">
<div className="flex-1 bg-slate-800/30 rounded-lg p-6 flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50">
{/* Instruction Box */}
<div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[200px] pointer-events-none">
<div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
<MousePointer2 size={14} className="text-primary"/> Инструкция
@@ -179,7 +158,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</ul>
</div>
{/* Rulers */}
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]">
<span className="text-xs text-slate-500 font-mono">0</span>
<span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
@@ -191,7 +169,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
</div>
{/* Main Interactive SVG */}
<div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
style={{
@@ -206,7 +183,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
ref={svgRef}
viewBox={`0 0 ${viewBoxW} ${viewBoxH}`}
className="w-full h-full touch-none"
onMouseMove={handleMouseMove}
onMouseMove={handleGlobalMouseMove}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
@@ -216,14 +193,10 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
<path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/>
</pattern>
<filter id="solid-bg" x="-0.1" y="-0.1" width="1.2" height="1.2">
<feFlood floodColor="#1e293b" floodOpacity="0.8"/>
<feComposite in="SourceGraphic" operator="over"/>
</filter>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Cell Dimensions Labels --- */}
{/* --- Labels --- */}
{sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => {
@@ -236,14 +209,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const cellWidthSVG = (x2 - x1) * viewBoxW;
const cellHeightSVG = (y2 - y1) * viewBoxH;
// Dynamic Font Sizing Logic
// Max font size: 36px
// Must fit in height: 60% of height max
// Must fit in width: approx 25% of width max (assuming ~5 chars)
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
// Don't show text if calculated font size is too small to be readable
if (fontSize < 10) return null;
return (
@@ -265,7 +233,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
});
})}
{/* --- Existing X Lines (Vertical) --- */}
{/* --- X Lines (Vertical) --- */}
{splits.x.map((x, i) => {
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'x' && dragging.index === i;
@@ -273,22 +241,26 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const width = isHovered || isDragging ? 8 : 4;
return (
<g key={`x-${i}`} onDoubleClick={() => removeSplit('x', i)}>
{/* Invisible wide hit area */}
<g
key={`x-${i}`}
onDoubleClick={() => removeSplit('x', i)}
// ВАЖНО: Событие вешаем на группу
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
>
{/* Невидимая широкая зона захвата (80 единиц!) */}
<line
x1={x * viewBoxW} y1={0}
x2={x * viewBoxW} y2={viewBoxH}
stroke="transparent" strokeWidth="60"
className="cursor-col-resize hover:stroke-white/5"
stroke="transparent" strokeWidth="80"
className="cursor-col-resize"
/>
{/* Visible Line */}
{/* Видимая линия */}
<line
x1={x * viewBoxW} y1={0}
x2={x * viewBoxW} y2={viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150"
className="transition-all duration-150 pointer-events-none"
/>
{/* Delete Button if hovered */}
{(isHovered || isDragging) && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
@@ -299,7 +271,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
);
})}
{/* --- Existing Y Lines (Horizontal) --- */}
{/* --- Y Lines (Horizontal) --- */}
{splits.y.map((y, i) => {
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'y' && dragging.index === i;
@@ -307,19 +279,22 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const width = isHovered || isDragging ? 8 : 4;
return (
<g key={`y-${i}`} onDoubleClick={() => removeSplit('y', i)}>
{/* Invisible wide hit area */}
<g
key={`y-${i}`}
onDoubleClick={() => removeSplit('y', i)}
onMouseMove={(e) => handleSplitHover(e, 'y', i)}
>
<line
x1={0} y1={y * viewBoxH}
x2={viewBoxW} y2={y * viewBoxH}
stroke="transparent" strokeWidth="60"
className="cursor-row-resize hover:stroke-white/5"
stroke="transparent" strokeWidth="80"
className="cursor-row-resize"
/>
<line
x1={0} y1={y * viewBoxH}
x2={viewBoxW} y2={y * viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150"
className="transition-all duration-150 pointer-events-none"
/>
{(isHovered || isDragging) && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}>
@@ -331,16 +306,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
);
})}
{/* --- Phantom Line (Preview) --- */}
{/* --- Phantom Lines --- */}
{!hoveredSplit && !dragging && phantomAxis === 'x' && (
<g>
<g className="pointer-events-none">
<line
x1={mousePos.x * viewBoxW} y1="0"
x2={mousePos.x * viewBoxW} y2="100%"
stroke="#3b82f6"
strokeWidth="4"
strokeDasharray="12,8"
className="pointer-events-none opacity-60"
stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"
className="opacity-60"
/>
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}>
<circle r="3" fill="#3b82f6" />
@@ -348,14 +321,12 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</g>
)}
{!hoveredSplit && !dragging && phantomAxis === 'y' && (
<g>
<g className="pointer-events-none">
<line
x1="0" y1={mousePos.y * viewBoxH}
x2="100%" y2={mousePos.y * viewBoxH}
stroke="#3b82f6"
strokeWidth="4"
strokeDasharray="12,8"
className="pointer-events-none opacity-60"
stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"
className="opacity-60"
/>
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}>
<circle r="3" fill="#3b82f6" />

View File

@@ -42,17 +42,15 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
{/* Модель */}
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
<meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color}
roughness={0.5}
metalness={0.1}
side={THREE.DoubleSide} // <--- ИСПРАВЛЕНИЕ: Рисуем обе стороны стенки
side={THREE.DoubleSide}
/>
</mesh>
{/* Белая обводка */}
{isSelected && (
<lineSegments geometry={edgesGeometry}>
<lineBasicMaterial color="white" linewidth={2} />
@@ -145,6 +143,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
return (
<div className="flex flex-col h-full">
{/* Верхняя панель */}
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
@@ -183,6 +182,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
</div>
<div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
{/* 3D Viewer */}
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
@@ -230,6 +230,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
</Canvas>
</div>
{/* Sidebar List (Grid Layout) */}
<div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
<div className="flex justify-between items-center mb-6 shrink-0">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
@@ -245,27 +246,53 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
</button>
</div>
<div className="flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar">
{parts.map(part => (
<div
key={part.id}
ref={(el) => { itemRefs.current[part.id] = el }}
className={`p-4 rounded-lg border transition-all cursor-pointer group ${selectedId === part.id ? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent' : 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'}`}
onClick={() => setSelectedId(part.id)}
>
<div className="flex justify-between items-center mb-2">
<span className="font-semibold text-gray-200">{part.name}</span>
<div className="w-3 h-3 rounded-full border border-white/10" style={{ backgroundColor: part.color }} />
</div>
<button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-2.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-sm flex items-center justify-center gap-2 transition-colors font-medium mt-2"
<div className="flex-1 overflow-y-auto pr-1 custom-scrollbar">
<div className="grid grid-cols-2 gap-3 pb-4">
{parts.map(part => (
<div
key={part.id}
ref={(el) => { itemRefs.current[part.id] = el }}
className={`
p-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
${selectedId === part.id
? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent'
: 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'
}
`}
onClick={() => setSelectedId(part.id)}
>
<Download size={16} /> Скачать STL
</button>
</div>
))}
{/* Фон-индикатор */}
<div
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
style={{ backgroundColor: part.color, opacity: 0.1 }}
/>
{/* Заголовок */}
<div className="flex items-center justify-between z-10">
<span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
{part.name}
</span>
<div
className="w-2.5 h-2.5 rounded-full border border-white/20 shadow-sm"
style={{ backgroundColor: part.color }}
/>
</div>
{/* --- РАЗМЕРЫ (НОВОЕ) --- */}
<div className="text-[10px] text-gray-400 font-mono z-10">
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
</div>
{/* Кнопка */}
<button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
>
<Download size={12} /> STL
</button>
</div>
))}
</div>
</div>
</div>
</div>