Add split

This commit is contained in:
Халимов Рустам
2026-01-10 16:43:20 +03:00
parent 8789d82064
commit 4af73b00eb
5 changed files with 379 additions and 278 deletions

View File

@@ -9,9 +9,7 @@ import { ChevronRight, ChevronLeft, Box } from 'lucide-react';
const App = () => {
const [step, setStep] = useState(1);
const [isLoadedFromUrl, setIsLoadedFromUrl] = useState(false);
// State
const [config, setConfig] = useState<AppConfig>({
drawer: { width: 300, depth: 400, height: 80 },
wallThickness: 1.2,
@@ -19,36 +17,33 @@ const App = () => {
cornerRadius: 4,
});
// Чистый стейт без subdivisions
// ВАЖНО: Инициализируем partitions
const [splits, setSplits] = useState<LayoutSplits>({
x: [],
y: []
y: [],
partitions: {}
});
// --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ ---
useEffect(() => {
const sharedData = parseShareUrl();
if (sharedData) {
setConfig(sharedData.config);
// Принудительно чистим объект от старых полей, если они были в ссылке
setSplits({
x: sharedData.splits.x || [],
y: sharedData.splits.y || []
y: sharedData.splits.y || [],
partitions: sharedData.splits.partitions || {}
});
setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname);
}
}, []);
// Derived State: Parts
const parts: GeneratedPart[] = useMemo(() => {
return calculateParts(config, splits);
}, [config, splits]);
return (
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950">
{/* Header */}
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md sticky top-0 z-50">
<div className="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2">
@@ -60,80 +55,31 @@ const App = () => {
<p className="text-xs text-gray-400">Генератор органайзеров</p>
</div>
</div>
{/* Progress Stepper */}
<div className="flex items-center gap-4 text-sm font-medium">
{[1, 2, 3].map((num) => (
<React.Fragment key={num}>
<div className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>
{num}
</span>
<span className="hidden md:inline">
{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}
</span>
</div>
{num < 3 && <div className="w-8 h-[1px] bg-slate-700" />}
</React.Fragment>
<div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>{num}</span>
<span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span>
</div>
))}
</div>
</div>
</header>
{/* Main Content */}
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8">
{step === 1 && (
<div className="max-w-4xl mx-auto animate-fade-in">
<ConfigStep config={config} onChange={setConfig} />
</div>
)}
{step === 2 && (
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in">
<LayoutStep config={config} splits={splits} onChange={setSplits} />
</div>
)}
{step === 3 && (
<div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in">
<PreviewStep parts={parts} config={config} splits={splits} />
</div>
)}
{step === 1 && <div className="max-w-4xl mx-auto animate-fade-in"><ConfigStep config={config} onChange={setConfig} /></div>}
{step === 2 && <div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in"><LayoutStep config={config} splits={splits} onChange={setSplits} /></div>}
{step === 3 && <div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in"><PreviewStep parts={parts} config={config} splits={splits} /></div>}
</main>
{/* Footer Navigation */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50">
<div className="max-w-7xl mx-auto flex justify-between items-center">
<button
disabled={step === 1}
onClick={() => setStep(s => Math.max(1, s - 1))}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"
>
<ChevronLeft size={18} /> Назад
</button>
<div className="text-sm text-gray-500">
{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}
</div>
<button disabled={step === 1} onClick={() => setStep(s => Math.max(1, s - 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"><ChevronLeft size={18} /> Назад</button>
<div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div>
{step < 3 ? (
<button
onClick={() => setStep(s => Math.min(3, s + 1))}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95"
>
Далее <ChevronRight size={18} />
</button>
<button onClick={() => setStep(s => Math.min(3, s + 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95">Далее <ChevronRight size={18} /></button>
) : (
<button
onClick={() => {
setStep(1);
setSplits({x: [], y: []});
window.history.replaceState({}, '', window.location.pathname);
}}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700"
>
Новый проект
</button>
<button onClick={() => { setStep(1); setSplits({x: [], y: [], partitions: {}}); window.history.replaceState({}, '', window.location.pathname); }} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700">Новый проект</button>
)}
</div>
</footer>

View File

@@ -1,6 +1,6 @@
import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';
import { AppConfig, LayoutSplits, Partition } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Settings2, Sliders } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -8,31 +8,84 @@ interface Props {
onChange: (splits: LayoutSplits) => void;
}
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
// State
const [mode, setMode] = useState<EditMode>('lines');
// States for Lines
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);
// FIX: Кнопка удаления не пропадает под курсором
const [isButtonHovered, setIsButtonHovered] = useState(false);
// SAFE ACCESS: Защита от undefined
const safeX = splits.x || [];
const safeY = splits.y || [];
// State for Cell Editor
const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null);
// Safeties
const safeX = splits?.x || [];
const safeY = splits?.y || [];
const safePartitions = splits?.partitions || {};
const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width;
const aspectRatio = (config.drawer.depth || 1) / (config.drawer.width || 1);
const viewBoxH = viewBoxW * aspectRatio;
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- PARTITION LOGIC ---
const getCurrentPartitions = () => {
if (!editingCell) return [];
const key = `${editingCell.i}-${editingCell.j}`;
return safePartitions[key] || [];
};
const addPartition = (axis: 'x' | 'y') => {
if (!editingCell) return;
const key = `${editingCell.i}-${editingCell.j}`;
const current = safePartitions[key] || [];
const newPart: Partition = {
id: Date.now().toString(),
axis,
offset: 0.5,
height: config.drawer.height, // по умолчанию полная высота
rounded: false
};
onChange({
...splits,
partitions: { ...safePartitions, [key]: [...current, newPart] }
});
};
const updatePartition = (id: string, updates: Partial<Partition>) => {
if (!editingCell) return;
const key = `${editingCell.i}-${editingCell.j}`;
const current = safePartitions[key] || [];
const updated = current.map(p => p.id === id ? { ...p, ...updates } : p);
onChange({
...splits,
partitions: { ...safePartitions, [key]: updated }
});
};
const removePartition = (id: string) => {
if (!editingCell) return;
const key = `${editingCell.i}-${editingCell.j}`;
const current = safePartitions[key] || [];
onChange({
...splits,
partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) }
});
};
// --- MOUSE HANDLERS (Global) ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
@@ -41,56 +94,51 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setMousePos({ x: nx, y: ny });
if (dragging) {
const newSplits = { x: [...safeX], y: [...safeY] };
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
return;
if (mode === 'lines') {
if (dragging) {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
return;
}
if (isButtonHovered) return;
setHoveredSplit(null);
const SNAP = 0.02;
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
if (!closeToX && !closeToY && !closeToEdgeX && !closeToEdgeY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
setPhantomAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x');
} else {
setPhantomAxis(null);
}
}
if (isButtonHovered) return;
setHoveredSplit(null);
const SNAP = 0.02;
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
if (!closeToX && !closeToY && !closeToEdgeX && !closeToEdgeY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
const minXDist = Math.min(nx, distRight);
const minYDist = Math.min(ny, distBottom);
setPhantomAxis(minXDist < minYDist ? 'y' : 'x');
} 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) => {
if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { x: [...safeX], y: [...safeY] };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
if (mode === 'lines') {
if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeMainSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
} else {
if (e.target === svgRef.current) setEditingCell(null);
}
};
const removeSplit = (axis: Axis, index: number) => {
const newSplits = { x: [...safeX], y: [...safeY] };
const removeMainSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits);
setHoveredSplit(null);
@@ -99,62 +147,68 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
};
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">
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative">
<div className="flex justify-between items-center mb-4 z-20">
<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} /> Сбросить сетку
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
<button onClick={() => { setMode('lines'); setEditingCell(null); }} className={`flex items-center gap-2 px-4 py-2 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}>
<Grid size={14} /> Границы
</button>
<button onClick={() => setMode('cells')} className={`flex items-center gap-2 px-4 py-2 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}>
<LayoutGrid size={14} /> Внутри ячеек
</button>
</div>
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} 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 flex-col h-full select-none relative">
<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">
<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">
{/* Instructions */}
<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"/> Инструкция
<MousePointer2 size={14} className="text-primary"/> {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
</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>
{mode === 'lines' ? (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-blue-400">Клик:</b> Новая граница</li>
<li><b className="text-orange-400">Драг:</b> Двигать</li>
</ul>
) : (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-green-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">
<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>
<div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
<div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group"
style={{
width: '100%',
maxWidth: '900px',
width: '100%', maxWidth: '900px',
aspectRatio: `${1/aspectRatio}`,
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair') : 'default',
maxHeight: '75vh'
}}
>
<svg
ref={svgRef}
viewBox={`0 0 ${viewBoxW} ${viewBoxH}`}
className="w-full h-full touch-none"
onMouseMove={handleGlobalMouseMove}
onMouseDown={handleMouseDown}
onMouseUp={() => setDragging(null)}
onContextMenu={(e) => e.preventDefault()}
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none"
onMouseMove={handleGlobalMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
>
<defs>
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
@@ -163,113 +217,141 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Labels --- */}
{/* --- Cells & Partitions --- */}
{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;
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
if (fontSize < 10) return null;
const cellX = x1 * viewBoxW;
const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW;
const cellH = (y2 - y1) * viewBoxH;
const isSelected = editingCell?.i === i && editingCell?.j === j;
const parts = safePartitions[`${i}-${j}`] || [];
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>
<g key={`cell-${i}-${j}`}>
<rect x={cellX} y={cellY} width={cellW} height={cellH}
fill={isSelected ? "rgba(59, 130, 246, 0.2)" : "transparent"}
stroke={isSelected ? "#3b82f6" : "transparent"} strokeWidth="4"
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""}
onClick={(e) => { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }}
/>
{/* Render Partitions */}
{parts.map(p => {
if (p.axis === 'x') {
const px = cellX + (cellW * p.offset);
return <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="3" />;
} else {
const py = cellY + (cellH * p.offset);
return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="3" />;
}
})}
</g>
);
});
})}
{/* --- X Lines (Vertical) --- */}
{safeX.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)}
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="80" className="cursor-col-resize" />
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{(isHovered || isDragging) && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- Main Grid Lines --- */}
{safeX.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'x', index: i }); setPhantomAxis(null); } }}>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
{mode === 'lines' && hoveredSplit?.axis === 'x' && hoveredSplit.index === i && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}>
<circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
</g>
))}
{/* --- Y Lines (Horizontal) --- */}
{safeY.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;
{safeY.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'y', index: i }); setPhantomAxis(null); } }}>
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-row-resize" : ""} />
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
{mode === 'lines' && hoveredSplit?.axis === 'y' && hoveredSplit.index === i && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}>
<circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
</g>
))}
return (
<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="80" className="cursor-row-resize" />
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{(isHovered || isDragging) && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- Phantom Lines --- */}
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'x' && (
<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="opacity-60"/>
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}> <circle r="3" fill="#3b82f6" /> </g>
</g>
)}
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'y' && (
<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="opacity-60"/>
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}> <circle r="3" fill="#3b82f6" /> </g>
</g>
)}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
</svg>
</div>
</div>
{/* --- MODAL EDITOR FOR CELLS --- */}
{mode === 'cells' && editingCell && (
<div className="absolute top-0 right-0 bottom-0 w-80 bg-slate-900 border-l border-slate-700 p-4 shadow-2xl flex flex-col z-30 animate-in slide-in-from-right-10">
<div className="flex justify-between items-center mb-6">
<h3 className="text-lg font-bold text-white flex items-center gap-2">
<Settings2 size={18} className="text-primary"/> Редактор ячейки
</h3>
<button onClick={() => setEditingCell(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
</div>
<div className="flex gap-2 mb-6">
<button onClick={() => addPartition('x')} className="flex-1 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-white text-xs py-2 px-3 rounded flex items-center justify-center gap-2 transition-colors">
<Plus size={14} className="text-green-400"/> Верт.
</button>
<button onClick={() => addPartition('y')} className="flex-1 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-white text-xs py-2 px-3 rounded flex items-center justify-center gap-2 transition-colors">
<Plus size={14} className="text-green-400"/> Гориз.
</button>
</div>
<div className="flex-1 overflow-y-auto space-y-4 pr-1">
{getCurrentPartitions().map((p, idx) => (
<div key={p.id} className="bg-slate-800 p-3 rounded border border-slate-700 group">
<div className="flex justify-between items-center mb-2">
<span className="text-xs font-bold text-purple-300">
#{idx+1} {p.axis === 'x' ? 'Вертикальная' : 'Горизонтальная'}
</span>
<button onClick={() => removePartition(p.id)} className="text-red-400 opacity-50 hover:opacity-100"><Trash2 size={14}/></button>
</div>
<div className="space-y-3">
<div>
<div className="flex justify-between text-[10px] text-gray-400 mb-1">
<span>Позиция</span> <span>{(p.offset * 100).toFixed(0)}%</span>
</div>
<input type="range" min="0.1" max="0.9" step="0.05" value={p.offset}
onChange={(e) => updatePartition(p.id, { offset: parseFloat(e.target.value) })}
className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"
/>
</div>
<div>
<div className="flex justify-between text-[10px] text-gray-400 mb-1">
<span>Высота</span> <span>{p.height} мм</span>
</div>
<input type="range" min="5" max={config.drawer.height} step="1" value={p.height}
onChange={(e) => updatePartition(p.id, { height: parseFloat(e.target.value) })}
className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
</div>
<div className="flex items-center gap-2">
<input type="checkbox" id={`rounded-${p.id}`} checked={p.rounded}
onChange={(e) => updatePartition(p.id, { rounded: e.target.checked })}
className="rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0"
/>
<label htmlFor={`rounded-${p.id}`} className="text-xs text-gray-300 cursor-pointer select-none">Скругление краев</label>
</div>
</div>
</div>
))}
{getCurrentPartitions().length === 0 && (
<div className="text-center text-gray-500 text-xs py-4 border border-dashed border-slate-700 rounded">
Нет перегородок
</div>
)}
</div>
</div>
)}
</div>
</div>
</div>

View File

@@ -33,8 +33,15 @@ interface BinMeshProps {
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
const geometry = useMemo(() => {
return createBinGeometry(part.width, part.depth, part.height, thickness, cornerRadius);
}, [part, thickness, cornerRadius]);
return createBinGeometry(
part.width,
part.depth,
part.height,
thickness,
cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки
);
}, [part, thickness, cornerRadius]);
const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20);

View File

@@ -1,16 +1,12 @@
import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart } from '../types';
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
export const calculateParts = (
config: AppConfig,
splits: LayoutSplits
): GeneratedPart[] => {
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
const parts: GeneratedPart[] = [];
// Safe Access
const safeX = splits.x || [];
const safeY = splits.y || [];
const safeParts = splits.partitions || {};
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
@@ -19,20 +15,21 @@ export const calculateParts = (
for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) {
const segmentX = xPoints[i] * config.drawer.width;
const segmentY = yPoints[j] * config.drawer.depth;
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const rawX = xPoints[i] * config.drawer.width;
const rawY = yPoints[j] * config.drawer.depth;
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const realWidth = segmentW - config.printerTolerance;
const realDepth = segmentD - config.printerTolerance;
const realX = segmentX + (config.printerTolerance / 2);
const realY = segmentY + (config.printerTolerance / 2);
// Получаем перегородки для этой ячейки
const internalPartitions = safeParts[`${i}-${j}`] || [];
if (realWidth < 5 || realDepth < 5) {
continue;
}
// Рассчитываем реальные размеры с учетом допуска принтера
const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2);
const realY = rawY + (config.printerTolerance / 2);
if (realWidth < 5 || realDepth < 5) continue;
parts.push({
id: `part-${partCounter}`,
@@ -42,15 +39,18 @@ export const calculateParts = (
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
color: `hsl(${Math.random() * 360}, 70%, 50%)`,
internalPartitions: internalPartitions
});
partCounter++;
}
}
return parts;
};
// --- GEOMETRY GENERATION ---
// Создает форму скругленного прямоугольника (или обычного)
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape();
const x = -width / 2;
@@ -75,20 +75,25 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
shape.quadraticCurveTo(x, y, x, y + r);
}
return shape;
}
};
// Генерирует геометрию ячейки С ПЕРЕГОРОДКАМИ
export const createBinGeometry = (
width: number,
depth: number,
height: number,
thickness: number,
radius: number = 0
radius: number = 0,
partitions: Partition[] = []
): THREE.BufferGeometry => {
const geometries: THREE.BufferGeometry[] = [];
// 1. ОСНОВНАЯ КОРОБКА (Дно + Стенки)
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
depth: thickness, bevelEnabled: false, curveSegments: 16
});
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 });
floorGeo.rotateX(-Math.PI / 2);
geometries.push(floorGeo);
const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0, radius - thickness);
@@ -101,19 +106,67 @@ export const createBinGeometry = (
}
const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: wallHeight, bevelEnabled: false, curveSegments: 16
});
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 12 });
wallGeo.rotateX(-Math.PI / 2);
wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo);
const merged = mergeBufferGeometries([floorGeo, wallGeo]);
// 2. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
// Мы создаем их внутри внутреннего пространства (innerWidth/innerDepth)
partitions.forEach(p => {
// Размеры перегородки
let pWidth = 0;
let pDepth = 0;
// Позиция центра перегородки относительно центра ящика
let pX = 0;
let pY = 0; // (это Z в 3D)
if (p.axis === 'x') {
// Вертикальная палка (делит ширину)
pWidth = thickness;
// Длина палки равна внутренней глубине ящика
pDepth = innerDepth;
// Смещение: p.offset (0..1) переводим в координаты.
// innerLeft = -innerWidth/2. Position = innerLeft + (innerWidth * offset)
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = 0; // По центру глубины
} else {
// Горизонтальная палка (делит глубину)
pWidth = innerWidth;
pDepth = thickness;
pX = 0; // По центру ширины
pY = (-innerDepth / 2) + (innerDepth * p.offset);
}
// Форма перегородки (скругленная или нет)
// Если скругленная, радиус берем такой же как у основной стенки, но не больше половины толщины
const pRadius = p.rounded ? Math.min(radius, thickness / 1.5) : 0;
const partShape = createRoundedRectShape(pWidth, pDepth, pRadius);
const partGeo = new THREE.ExtrudeGeometry(partShape, {
depth: p.height, // Высота перегородки (может отличаться от основной)
bevelEnabled: false,
curveSegments: 8
});
partGeo.rotateX(-Math.PI / 2);
// Поднимаем на толщину дна
partGeo.translate(pX, thickness, pY);
geometries.push(partGeo);
});
// 3. СЛИЯНИЕ
const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals();
return merged || new THREE.BoxGeometry(1, 1, 1);
};
// ... Остальной код экспорта (без изменений) ...
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter();
const result = exporter.parse(mesh, { binary: true });

View File

@@ -11,9 +11,20 @@ export interface AppConfig {
cornerRadius: number;
}
// Описание одной внутренней перегородки
export interface Partition {
id: string;
axis: 'x' | 'y'; // x - вертикальная палка, y - горизонтальная
offset: number; // позиция от 0 до 100% (0.5 = центр)
height: number; // высота стенки в мм
rounded: boolean; // скруглять ли края этой стенки
}
export interface LayoutSplits {
x: number[];
y: number[];
// Ключ: индекс ячейки "i-j", Значение: массив перегородок
partitions: Record<string, Partition[]>;
}
export interface GeneratedPart {
@@ -25,4 +36,6 @@ export interface GeneratedPart {
x: number;
y: number;
color: string;
// Передаем перегородки в генератор
internalPartitions: Partition[];
}