V3
This commit is contained in:
133
src/components/ConfigStep.tsx
Normal file
133
src/components/ConfigStep.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import React from 'react';
|
||||
import { AppConfig } from '../types';
|
||||
import { Ruler, Box, Layers, Minimize2 } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
config: AppConfig;
|
||||
onChange: (newConfig: AppConfig) => void;
|
||||
}
|
||||
|
||||
const InputGroup: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
|
||||
<div className="flex flex-col gap-2 mb-4">
|
||||
<label className="text-sm font-medium text-gray-300">{label}</label>
|
||||
<div className="flex gap-4">{children}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const NumberInput = ({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
max
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (val: number) => void;
|
||||
max?: number
|
||||
}) => (
|
||||
<div className="flex-1 relative">
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max={max}
|
||||
value={value}
|
||||
onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
|
||||
className="w-full bg-slate-800 border border-slate-700 rounded p-2 pl-8 text-white focus:ring-2 focus:ring-primary outline-none"
|
||||
/>
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">мм</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
|
||||
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
|
||||
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in">
|
||||
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
|
||||
<Box size={24} /> 1. Размеры
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* Drawer Dimensions */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Ruler className="text-accent" size={18} /> Внутренние размеры ящика
|
||||
</h3>
|
||||
<InputGroup label="Ширина (X)">
|
||||
<NumberInput label="Ш" value={config.drawer.width} onChange={(v) => updateDrawer('width', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Глубина (Y)">
|
||||
<NumberInput label="Г" value={config.drawer.depth} onChange={(v) => updateDrawer('depth', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Высота (Z)">
|
||||
<NumberInput label="В" value={config.drawer.height} onChange={(v) => updateDrawer('height', v)} />
|
||||
</InputGroup>
|
||||
</div>
|
||||
|
||||
{/* Settings */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Layers className="text-accent" size={18} /> Параметры печати
|
||||
</h3>
|
||||
|
||||
<div className="mb-6">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium text-gray-300">Толщина стенок</label>
|
||||
<span className="text-primary font-bold bg-primary/10 px-2 py-1 rounded text-sm border border-primary/20">
|
||||
{config.wallThickness.toFixed(1)} мм
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.4</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.4"
|
||||
max="3.2"
|
||||
step="0.1"
|
||||
value={config.wallThickness}
|
||||
onChange={(e) => onChange({...config, wallThickness: parseFloat(e.target.value)})}
|
||||
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-primary hover:accent-blue-400 transition-all"
|
||||
/>
|
||||
<span className="text-xs text-gray-500 font-mono">3.2</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
||||
<Minimize2 size={14} className="text-gray-400"/> Зазор (Tolerance)
|
||||
</label>
|
||||
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
|
||||
{config.printerTolerance.toFixed(1)} мм
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.0</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.0"
|
||||
max="2.0"
|
||||
step="0.1"
|
||||
value={config.printerTolerance}
|
||||
onChange={(e) => onChange({...config, printerTolerance: parseFloat(e.target.value)})}
|
||||
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-accent hover:accent-amber-400 transition-all"
|
||||
/>
|
||||
<span className="text-xs text-gray-500 font-mono">2.0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-slate-900/50 p-3 rounded border border-slate-700/50">
|
||||
<p className="text-xs text-gray-400 leading-relaxed">
|
||||
<span className="text-accent font-semibold">Зазор</span> уменьшает размер каждой ячейки, чтобы они легко вставлялись в ящик и друг в друга. Рекомендуется 0.5 мм.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
372
src/components/LayoutStep.tsx
Normal file
372
src/components/LayoutStep.tsx
Normal file
@@ -0,0 +1,372 @@
|
||||
import React, { useRef, useState, useMemo } from 'react';
|
||||
import { AppConfig, LayoutSplits } from '../types';
|
||||
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
config: AppConfig;
|
||||
splits: LayoutSplits;
|
||||
onChange: (splits: LayoutSplits) => void;
|
||||
}
|
||||
|
||||
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
|
||||
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) => {
|
||||
if (!svgRef.current) return;
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
||||
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
|
||||
|
||||
setMousePos({ x: nx, y: ny });
|
||||
|
||||
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 };
|
||||
});
|
||||
|
||||
// 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 };
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
setPhantomAxis(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
if (hoveredSplit) {
|
||||
// Start Dragging
|
||||
if (e.button === 0) { // Left click
|
||||
setDragging(hoveredSplit);
|
||||
} else if (e.button === 2) { // Right click
|
||||
removeSplit(hoveredSplit.axis, hoveredSplit.index);
|
||||
}
|
||||
} else if (phantomAxis) {
|
||||
// Create New Split
|
||||
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 });
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setDragging(null);
|
||||
};
|
||||
|
||||
const removeSplit = (axis: Axis, index: number) => {
|
||||
const newSplits = { ...splits };
|
||||
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
|
||||
onChange(newSplits);
|
||||
setHoveredSplit(null);
|
||||
setDragging(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Grid size={24} /> 2. Редактор макета
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => onChange({ x: [], y: [] })}
|
||||
className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
|
||||
>
|
||||
<RotateCcw size={14} /> Сбросить сетку
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<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"/> Инструкция
|
||||
</div>
|
||||
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight">
|
||||
<li><b className="text-blue-400">Клик у края:</b> Новая линия</li>
|
||||
<li><b className="text-orange-400">Перетаскивание:</b> Изменить размер</li>
|
||||
<li><b className="text-red-400">Двойной клик/ПКМ:</b> Удалить</li>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center justify-center w-full h-full">
|
||||
<div className="h-full max-h-[90%] flex flex-col justify-between py-2 mr-2">
|
||||
<span className="text-xs text-slate-500 font-mono">0</span>
|
||||
<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={{
|
||||
width: '100%',
|
||||
maxWidth: '900px',
|
||||
aspectRatio: `${1/aspectRatio}`,
|
||||
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
|
||||
maxHeight: '75vh'
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`0 0 ${viewBoxW} ${viewBoxH}`}
|
||||
className="w-full h-full touch-none"
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<defs>
|
||||
<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 --- */}
|
||||
{sortedX.slice(0, -1).map((x1, i) => {
|
||||
const x2 = sortedX[i + 1];
|
||||
return sortedY.slice(0, -1).map((y1, j) => {
|
||||
const y2 = sortedY[j + 1];
|
||||
const width = (x2 - x1) * config.drawer.width;
|
||||
const depth = (y2 - y1) * config.drawer.depth;
|
||||
const centerX = ((x1 + x2) / 2) * viewBoxW;
|
||||
const centerY = ((y1 + y2) / 2) * viewBoxH;
|
||||
|
||||
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 (
|
||||
<text
|
||||
key={`label-${i}-${j}`}
|
||||
x={centerX}
|
||||
y={centerY}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="middle"
|
||||
className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200"
|
||||
style={{
|
||||
fontSize: `${fontSize}px`,
|
||||
textShadow: '1px 1px 3px rgba(0,0,0,0.8)'
|
||||
}}
|
||||
>
|
||||
{width.toFixed(0)} × {depth.toFixed(0)}
|
||||
</text>
|
||||
);
|
||||
});
|
||||
})}
|
||||
|
||||
{/* --- Existing X Lines (Vertical) --- */}
|
||||
{splits.x.map((x, i) => {
|
||||
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
|
||||
const isDragging = dragging?.axis === 'x' && dragging.index === i;
|
||||
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
|
||||
const width = isHovered || isDragging ? 8 : 4;
|
||||
|
||||
return (
|
||||
<g key={`x-${i}`} onDoubleClick={() => removeSplit('x', i)}>
|
||||
{/* Invisible wide hit area */}
|
||||
<line
|
||||
x1={x * viewBoxW} y1={0}
|
||||
x2={x * viewBoxW} y2={viewBoxH}
|
||||
stroke="transparent" strokeWidth="60"
|
||||
className="cursor-col-resize hover:stroke-white/5"
|
||||
/>
|
||||
{/* Visible Line */}
|
||||
<line
|
||||
x1={x * viewBoxW} y1={0}
|
||||
x2={x * viewBoxW} y2={viewBoxH}
|
||||
stroke={color} strokeWidth={width}
|
||||
className="transition-all duration-150"
|
||||
/>
|
||||
{/* 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"/>
|
||||
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* --- Existing Y Lines (Horizontal) --- */}
|
||||
{splits.y.map((y, i) => {
|
||||
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
|
||||
const isDragging = dragging?.axis === 'y' && dragging.index === i;
|
||||
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
|
||||
const width = isHovered || isDragging ? 8 : 4;
|
||||
|
||||
return (
|
||||
<g key={`y-${i}`} onDoubleClick={() => removeSplit('y', i)}>
|
||||
{/* Invisible wide hit area */}
|
||||
<line
|
||||
x1={0} y1={y * viewBoxH}
|
||||
x2={viewBoxW} y2={y * viewBoxH}
|
||||
stroke="transparent" strokeWidth="60"
|
||||
className="cursor-row-resize hover:stroke-white/5"
|
||||
/>
|
||||
<line
|
||||
x1={0} y1={y * viewBoxH}
|
||||
x2={viewBoxW} y2={y * viewBoxH}
|
||||
stroke={color} strokeWidth={width}
|
||||
className="transition-all duration-150"
|
||||
/>
|
||||
{(isHovered || isDragging) && (
|
||||
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}>
|
||||
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
|
||||
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* --- Phantom Line (Preview) --- */}
|
||||
{!hoveredSplit && !dragging && phantomAxis === 'x' && (
|
||||
<g>
|
||||
<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"
|
||||
/>
|
||||
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
</g>
|
||||
)}
|
||||
{!hoveredSplit && !dragging && phantomAxis === 'y' && (
|
||||
<g>
|
||||
<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"
|
||||
/>
|
||||
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
259
src/components/PreviewStep.tsx
Normal file
259
src/components/PreviewStep.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import React, { useMemo, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { Canvas } from '@react-three/fiber';
|
||||
import { OrbitControls, Center, Environment } from '@react-three/drei';
|
||||
import * as THREE from 'three';
|
||||
import JSZip from 'jszip';
|
||||
import { AppConfig, GeneratedPart } from '../types';
|
||||
import { createBinGeometry, exportSTL, generateSTL } from '../services/geometryGenerator';
|
||||
import { Download, Package, Info, Loader2 } from 'lucide-react';
|
||||
|
||||
// --- 3D Helper Components ---
|
||||
|
||||
// Каркас ящика (только ребра, без диагоналей)
|
||||
const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
||||
const { width, depth, height } = config.drawer;
|
||||
const offset = 0.5; // Небольшой отступ наружу
|
||||
|
||||
return (
|
||||
<group position={[width / 2, height / 2, depth / 2]}>
|
||||
<lineSegments>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(width + offset, height + offset, depth + offset)]} />
|
||||
<lineBasicMaterial color="#475569" />
|
||||
</lineSegments>
|
||||
</group>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Bin Component ---
|
||||
|
||||
interface BinMeshProps {
|
||||
part: GeneratedPart;
|
||||
thickness: number;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, isSelected, onClick }) => {
|
||||
// REMOVED ARTIFICIAL GAP: The part dimensions now include the printer tolerance physically.
|
||||
// The gap will be visible naturally because part.width is smaller than grid size.
|
||||
|
||||
// Генерируем реальную геометрию, как для STL
|
||||
const geometry = useMemo(() => {
|
||||
return createBinGeometry(part.width, part.depth, part.height, thickness);
|
||||
}, [part, thickness]);
|
||||
|
||||
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}
|
||||
/>
|
||||
</mesh>
|
||||
|
||||
{/* Подсветка выделения (Bounding Box) */}
|
||||
{isSelected && (
|
||||
<lineSegments position={[0, part.height/2, 0]}>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(part.width, part.height, part.depth)]} />
|
||||
<lineBasicMaterial color="white" linewidth={2} />
|
||||
</lineSegments>
|
||||
)}
|
||||
</group>
|
||||
);
|
||||
};
|
||||
|
||||
interface Props {
|
||||
parts: GeneratedPart[];
|
||||
config: AppConfig;
|
||||
}
|
||||
|
||||
export const PreviewStep: React.FC<Props> = ({ parts, config }) => {
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isZipping, setIsZipping] = useState(false);
|
||||
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
||||
|
||||
// Автопрокрутка к выбранному элементу
|
||||
useEffect(() => {
|
||||
if (selectedId && itemRefs.current[selectedId]) {
|
||||
itemRefs.current[selectedId]?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'center'
|
||||
});
|
||||
}
|
||||
}, [selectedId]);
|
||||
|
||||
const handleDownload = (part: GeneratedPart) => {
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
||||
};
|
||||
|
||||
const handleDownloadAll = async () => {
|
||||
if (isZipping) return;
|
||||
setIsZipping(true);
|
||||
|
||||
try {
|
||||
console.log("Starting ZIP generation...");
|
||||
// Ensure JSZip is available
|
||||
if (typeof JSZip === 'undefined' && !JSZip) {
|
||||
throw new Error("Библиотека JSZip не загружена.");
|
||||
}
|
||||
|
||||
const zip = new JSZip();
|
||||
|
||||
// Генерация STL для каждой части и добавление в архив
|
||||
parts.forEach(part => {
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
const stlData = generateSTL(mesh);
|
||||
// stlData is Uint8Array or string here, which is supported
|
||||
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
||||
});
|
||||
|
||||
console.log("Files added to ZIP. Generating blob...");
|
||||
|
||||
// Генерация самого ZIP файла
|
||||
const content = await zip.generateAsync({ type: "blob" });
|
||||
|
||||
console.log("ZIP blob generated. Size:", content.size);
|
||||
|
||||
// Скачивание
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(content);
|
||||
link.download = "PrintFit_Project.zip";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
} catch (e: any) {
|
||||
console.error("Failed to create zip archive", e);
|
||||
alert(`Ошибка при создании архива: ${e.message || 'Неизвестная ошибка'}`);
|
||||
} finally {
|
||||
setIsZipping(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col lg:flex-row h-full gap-6">
|
||||
{/* 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">
|
||||
<Info size={14} /> Управление
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
<li>• ЛКМ: Вращение</li>
|
||||
<li>• ПКМ: Перемещение</li>
|
||||
<li>• Скролл: Масштаб</li>
|
||||
<li className="text-accent mt-2 font-semibold">• Клик по детали для выбора</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<Canvas
|
||||
shadows
|
||||
dpr={[1, 2]}
|
||||
camera={{
|
||||
position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
|
||||
fov: 45,
|
||||
near: 1,
|
||||
far: 20000
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<color attach="background" args={['#0f172a']} />
|
||||
|
||||
<ambientLight intensity={0.7} />
|
||||
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
||||
<directionalLight position={[-100, 100, -50]} intensity={0.5} />
|
||||
<Environment preset="city" />
|
||||
|
||||
<Center>
|
||||
<group>
|
||||
<DrawerFrame config={config} />
|
||||
{parts.map(part => (
|
||||
<BinMesh
|
||||
key={part.id}
|
||||
part={part}
|
||||
thickness={config.wallThickness}
|
||||
isSelected={selectedId === part.id}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
/>
|
||||
))}
|
||||
</group>
|
||||
</Center>
|
||||
|
||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
</div>
|
||||
|
||||
{/* Sidebar List */}
|
||||
<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">
|
||||
<Package size={24} /> Детали ({parts.length})
|
||||
</h2>
|
||||
<button
|
||||
onClick={handleDownloadAll}
|
||||
disabled={isZipping || parts.length === 0}
|
||||
className={`bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all active:scale-95 disabled:opacity-50 disabled:scale-100 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{isZipping ? (
|
||||
<>
|
||||
<Loader2 size={16} className="animate-spin" /> ZIP...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download size={16} /> Скачать все
|
||||
</>
|
||||
)}
|
||||
</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-start mb-2">
|
||||
<span className="font-semibold text-gray-200 group-hover:text-white transition-colors">{part.name}</span>
|
||||
<div
|
||||
className="w-3 h-3 rounded-full border border-white/10"
|
||||
style={{ backgroundColor: part.color }}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-xs text-gray-400 mb-3">
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Ширина</span>
|
||||
{part.width.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Глубина</span>
|
||||
{part.depth.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Высота</span>
|
||||
{part.height.toFixed(1)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
||||
className="w-full py-2 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-2 transition-colors font-medium"
|
||||
>
|
||||
<Download size={14} /> Скачать STL
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user