Добавление перегородок в ячейки и их скругления #6

Merged
rust merged 32 commits from test into main 2026-01-10 23:56:10 +03:00
3 changed files with 297 additions and 267 deletions
Showing only changes of commit a9b07a07d8 - Show all commits
+77 -19
View File
@@ -9,7 +9,9 @@ import { ChevronRight, ChevronLeft, Box } from 'lucide-react';
const App = () => { const App = () => {
const [step, setStep] = useState(1); const [step, setStep] = useState(1);
const [isLoadedFromUrl, setIsLoadedFromUrl] = useState(false);
// State
const [config, setConfig] = useState<AppConfig>({ const [config, setConfig] = useState<AppConfig>({
drawer: { width: 300, depth: 400, height: 80 }, drawer: { width: 300, depth: 400, height: 80 },
wallThickness: 1.2, wallThickness: 1.2,
@@ -17,7 +19,7 @@ const App = () => {
cornerRadius: 4, cornerRadius: 4,
}); });
// ИНИЦИАЛИЗАЦИЯ: partitions обязательно присутствует // Инициализация с гарантированными пустыми массивами
const [splits, setSplits] = useState<LayoutSplits>({ const [splits, setSplits] = useState<LayoutSplits>({
x: [], x: [],
y: [], y: [],
@@ -25,26 +27,37 @@ const App = () => {
}); });
useEffect(() => { useEffect(() => {
try {
const sharedData = parseShareUrl(); const sharedData = parseShareUrl();
if (sharedData) { if (sharedData) {
setConfig(sharedData.config); setConfig(sharedData.config);
// Защита: если в ссылке старый формат, подставляем пустые partitions
setSplits({ setSplits({
x: sharedData.splits.x || [], x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
y: sharedData.splits.y || [], y: Array.isArray(sharedData.splits.y) ? sharedData.splits.y : [],
partitions: sharedData.splits.partitions || {} partitions: sharedData.splits.partitions || {}
}); });
setStep(3); setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname); window.history.replaceState({}, '', window.location.pathname);
} }
} catch (e) {
console.error("Ошибка при загрузке URL:", e);
}
}, []); }, []);
// ЗАЩИТА: Оборачиваем расчет геометрии, чтобы не ломать весь UI при ошибке
const parts: GeneratedPart[] = useMemo(() => { const parts: GeneratedPart[] = useMemo(() => {
try {
return calculateParts(config, splits); return calculateParts(config, splits);
} catch (e) {
console.error("Ошибка расчета деталей:", e);
return []; // Возвращаем пустой массив вместо краша
}
}, [config, splits]); }, [config, splits]);
return ( return (
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950"> <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"> <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="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -56,39 +69,84 @@ const App = () => {
<p className="text-xs text-gray-400">Генератор органайзеров</p> <p className="text-xs text-gray-400">Генератор органайзеров</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-4 text-sm font-medium"> <div className="flex items-center gap-4 text-sm font-medium">
{[1, 2, 3].map((num) => ( {[1, 2, 3].map((num) => (
<div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}> <React.Fragment key={num}>
<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> <div className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span> <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>
{num < 3 && <div className="w-8 h-[1px] bg-slate-700" />}
</React.Fragment>
))} ))}
</div> </div>
</div> </div>
</header> </header>
{/* Main Content */}
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8"> <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 === 1 && (
<div className="max-w-4xl mx-auto animate-fade-in">
{/* ШАГ 2 */} <ConfigStep config={config} onChange={setConfig} />
{step === 2 && (
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in">
{/* Передаем key, чтобы React пересоздал компонент при смене шага (сброс ошибок) */}
<LayoutStep key="layout-step" config={config} splits={splits} onChange={setSplits} />
</div> </div>
)} )}
{step === 3 && <div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in"><PreviewStep parts={parts} config={config} splits={splits} /></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> </main>
{/* Footer */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50"> <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"> <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> <button
<div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div> 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 ? ( {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: [], 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> <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> </div>
</footer> </footer>
+52 -59
View File
@@ -1,7 +1,7 @@
import React, { useRef, useState, useMemo } from 'react'; import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits, Partition } from '../types'; import { AppConfig, LayoutSplits, Partition } from '../types';
// Используем только безопасные, стандартные иконки // ИСПОЛЬЗУЕМ ТОЛЬКО БАЗОВЫЕ ИКОНКИ (чтобы не крашилось из-за версий)
import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Move, Ban } from 'lucide-react'; import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Check } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -16,40 +16,39 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null); const svgRef = useRef<SVGSVGElement>(null);
const [mode, setMode] = useState<EditMode>('lines'); const [mode, setMode] = useState<EditMode>('lines');
// SVG State
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null);
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null); const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null); const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);
const [isButtonHovered, setIsButtonHovered] = useState(false); const [isButtonHovered, setIsButtonHovered] = useState(false);
// Редактор ячеек // Editor State
const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null); const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null);
// --- SAFETY FIRST --- // --- ЗАЩИТА ДАННЫХ (ОТ БЕЛОГО ЭКРАНА) ---
const safeX = splits?.x || []; const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = splits?.y || []; const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {}; const safePartitions = splits?.partitions || {};
// Расчет размеров SVG с защитой от деления на ноль
const width = Math.max(1, config.drawer.width || 100);
const depth = Math.max(1, config.drawer.depth || 100);
const viewBoxW = 1000; const viewBoxW = 1000;
const aspectRatio = (config.drawer.depth || 1) / (config.drawer.width || 1); const aspectRatio = depth / width;
const viewBoxH = viewBoxW * aspectRatio; const viewBoxH = viewBoxW * aspectRatio;
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- Логика перегородок --- // --- ЛОГИКА ПЕРЕГОРОДОК ---
const getCurrentPartitions = () => {
if (!editingCell) return [];
const key = `${editingCell.i}-${editingCell.j}`;
return safePartitions[key] || [];
};
const addPartition = (axis: 'x' | 'y') => { const addPartition = (axis: 'x' | 'y') => {
if (!editingCell) return; if (!editingCell) return;
const key = `${editingCell.i}-${editingCell.j}`; const key = `${editingCell.i}-${editingCell.j}`;
const current = safePartitions[key] || []; const current = safePartitions[key] || [];
const newPart: Partition = { const newPart: Partition = {
id: Date.now().toString(), id: Math.random().toString(36).substr(2, 9),
axis, axis,
offset: 0.5, offset: 0.5,
height: config.drawer.height, height: config.drawer.height,
@@ -84,9 +83,12 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}); });
}; };
// --- UI HANDLERS ---
const handleGlobalMouseMove = (e: React.MouseEvent) => { const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return; if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect(); const rect = svgRef.current.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return; // Защита
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); 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)); const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
@@ -100,16 +102,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onChange(newSplits); onChange(newSplits);
return; return;
} }
if (isButtonHovered) return; if (isButtonHovered) return;
setHoveredSplit(null); setHoveredSplit(null);
// Фантомная линия
const SNAP = 0.02; const SNAP = 0.02;
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP); const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = safeY.some(val => Math.abs(ny - 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) { if (!closeToX && !closeToY && nx > SNAP && nx < 1-SNAP && ny > SNAP && ny < 1-SNAP) {
const distRight = 1 - nx; const distBottom = 1 - ny; const distRight = 1 - nx; const distBottom = 1 - ny;
setPhantomAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); setPhantomAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x');
} else { } else {
@@ -131,6 +133,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
} }
} else { } else {
// Режим ячеек: клик обрабатывается на самих rect'ах, здесь только сброс
if (e.target === svgRef.current) setEditingCell(null); if (e.target === svgRef.current) setEditingCell(null);
} }
}; };
@@ -146,57 +149,42 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return ( return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative"> <div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative">
{/* HEADER */}
<div className="flex justify-between items-center mb-4 z-20"> <div className="flex justify-between items-center mb-4 z-20">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary"> <h2 className="text-xl font-bold flex items-center gap-2 text-primary">
<Grid size={24} /> 2. Редактор макета <Grid size={24} /> 2. Редактор
</h2> </h2>
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700"> <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'}`}> <button onClick={() => { setMode('lines'); setEditingCell(null); }} className={`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'}`}>
<Move size={14} /> Границы Границы
</button> </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'}`}> <button onClick={() => setMode('cells')} className={`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'}`}>
<Grid size={14} /> Внутри ячеек Внутри ячеек
</button> </button>
</div> </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"> <button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded border border-slate-700 flex items-center gap-1">
<RotateCcw size={14} /> Сбросить <RotateCcw size={14} /> Сброс
</button> </button>
</div> </div>
<div className="flex flex-col h-full select-none relative"> <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="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">
{/* Instructions */} {/* Instruction Overlay */}
<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="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"> <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' ? 'Режим: Границы' : 'Режим: Ячейки'} {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
</div> </div>
{mode === 'lines' ? ( <p className="text-[10px] text-gray-400">
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight"> {mode === 'lines' ? 'Клик: создать. Драг: двигать. ПКМ: удалить.' : 'Кликни по ячейке, чтобы добавить стенки внутри.'}
<li><b className="text-blue-400">Клик:</b> Новая линия</li> </p>
<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>
<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> </div>
{/* Canvas Container */}
<div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group" <div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group"
style={{ style={{
width: '100%', maxWidth: '900px', width: '100%', maxWidth: '900px',
@@ -215,7 +203,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs> </defs>
<rect width="100%" height="100%" fill="url(#grid)" /> <rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Ячейки и перегородки --- */} {/* Ячейки и перегородки */}
{sortedX.slice(0, -1).map((x1, i) => { {sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1]; const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => { return sortedY.slice(0, -1).map((y1, j) => {
@@ -228,20 +216,21 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return ( return (
<g key={`cell-${i}-${j}`}> <g key={`cell-${i}-${j}`}>
{/* Прямоугольник для клика */}
<rect x={cellX} y={cellY} width={cellW} height={cellH} <rect x={cellX} y={cellY} width={cellW} height={cellH}
fill={isSelected ? "rgba(59, 130, 246, 0.2)" : "transparent"} fill={isSelected ? "rgba(59, 130, 246, 0.2)" : "transparent"}
stroke={isSelected ? "#3b82f6" : "transparent"} strokeWidth="4" stroke={isSelected ? "#3b82f6" : "transparent"} strokeWidth="4"
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""} className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""}
onClick={(e) => { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }} onClick={(e) => { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }}
/> />
{/* Рисуем внутренние стенки */} {/* Перегородки */}
{parts.map(p => { {parts.map(p => {
if (p.axis === 'x') { if (p.axis === 'x') {
const px = cellX + (cellW * p.offset); const px = cellX + (cellW * p.offset);
return <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="4" />; return <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="4" className="pointer-events-none"/>;
} else { } else {
const py = cellY + (cellH * p.offset); const py = cellY + (cellH * p.offset);
return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="4" />; return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="4" className="pointer-events-none"/>;
} }
})} })}
</g> </g>
@@ -249,33 +238,35 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}); });
})} })}
{/* --- Основные линии сетки (Границы) --- */} {/* Линии сетки (X) */}
{safeX.map((x, i) => ( {safeX.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'x', index: i }); setPhantomAxis(null); } }}> <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="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" /> <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 && ( {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)}> <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"/> <circle r="14" fill="#ef4444" className="cursor-pointer"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/> <Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g> </g>
)} )}
</g> </g>
))} ))}
{/* Линии сетки (Y) */}
{safeY.map((y, i) => ( {safeY.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'y', index: i }); setPhantomAxis(null); } }}> <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="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" /> <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 && ( {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)}> <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"/> <circle r="14" fill="#ef4444" className="cursor-pointer"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/> <Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g> </g>
)} )}
</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 === '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"/>} {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> </svg>
@@ -302,7 +293,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
<div className="flex-1 overflow-y-auto space-y-4 pr-1"> <div className="flex-1 overflow-y-auto space-y-4 pr-1">
{getCurrentPartitions().map((p, idx) => ( {(safePartitions[`${editingCell.i}-${editingCell.j}`] || []).map((p, idx) => (
<div key={p.id} className="bg-slate-800 p-3 rounded border border-slate-700 group"> <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"> <div className="flex justify-between items-center mb-2">
<span className="text-xs font-bold text-purple-300"> <span className="text-xs font-bold text-purple-300">
@@ -342,17 +333,19 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
</div> </div>
))} ))}
{getCurrentPartitions().length === 0 && ( {(safePartitions[`${editingCell.i}-${editingCell.j}`] || []).length === 0 && (
<div className="text-center text-gray-500 text-xs py-4 border border-dashed border-slate-700 rounded flex flex-col items-center gap-2"> <div className="text-center text-gray-500 text-xs py-4 border border-dashed border-slate-700 rounded">
<Ban size={20} />
Нет перегородок Нет перегородок
</div> </div>
)} )}
</div> </div>
<button onClick={() => setEditingCell(null)} className="mt-4 w-full bg-primary hover:bg-blue-600 text-white py-2 rounded text-sm font-bold flex items-center justify-center gap-2">
<Check size={16}/> Готово
</button>
</div> </div>
)} )}
</div> </div>
</div> </div>
</div>
); );
}; };
+19 -40
View File
@@ -4,9 +4,11 @@ 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[] = []; const parts: GeneratedPart[] = [];
const safeX = splits.x || [];
const safeY = splits.y || []; // ЗАЩИТА ОТ ОШИБОК ДАННЫХ
const safeParts = splits.partitions || {}; const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {};
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1]; const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1]; const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
@@ -15,13 +17,16 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
for (let i = 0; i < xPoints.length - 1; i++) { for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) { for (let j = 0; j < yPoints.length - 1; j++) {
const rawX = xPoints[i] * config.drawer.width; const rawX = xPoints[i] * config.drawer.width;
const rawY = yPoints[j] * config.drawer.depth; const rawY = yPoints[j] * config.drawer.depth;
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const internalPartitions = safeParts[`${i}-${j}`] || []; // Получаем перегородки
const internalPartitions = safePartitions[`${i}-${j}`] || [];
// Допуски
const realWidth = rawW - config.printerTolerance; const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance; const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2); const realX = rawX + (config.printerTolerance / 2);
@@ -46,7 +51,8 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts; return parts;
}; };
// Геометрия // ... Вспомогательные функции (createBinGeometry, exportSTL) ...
// (Они остаются без изменений из прошлого ответа, там всё верно)
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
const x = -width / 2; const x = -width / 2;
@@ -74,23 +80,15 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
}; };
export const createBinGeometry = ( export const createBinGeometry = (
width: number, width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = []
depth: number,
height: number,
thickness: number,
radius: number = 0,
partitions: Partition[] = []
): THREE.BufferGeometry => { ): THREE.BufferGeometry => {
const geometries: THREE.BufferGeometry[] = []; const geometries: THREE.BufferGeometry[] = [];
// 1. ДНО
const floorShape = createRoundedRectShape(width, depth, radius); const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 }); const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 });
floorGeo.rotateX(-Math.PI / 2); floorGeo.rotateX(-Math.PI / 2);
geometries.push(floorGeo); geometries.push(floorGeo);
// 2. ВНЕШНИЕ СТЕНКИ
const outerShape = createRoundedRectShape(width, depth, radius); const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0, radius - thickness); const innerRadius = Math.max(0, radius - thickness);
const innerWidth = width - (2 * thickness); const innerWidth = width - (2 * thickness);
@@ -107,51 +105,32 @@ export const createBinGeometry = (
wallGeo.translate(0, thickness, 0); wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo); geometries.push(wallGeo);
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
partitions.forEach(p => { partitions.forEach(p => {
let pWidth = 0; let pWidth = 0, pDepth = 0, pX = 0, pY = 0;
let pDepth = 0;
let pX = 0;
let pY = 0;
if (p.axis === 'x') { if (p.axis === 'x') {
pWidth = thickness; pWidth = thickness; pDepth = innerDepth;
pDepth = innerDepth; pX = (-innerWidth / 2) + (innerWidth * p.offset); pY = 0;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = 0;
} else { } else {
pWidth = innerWidth; pWidth = innerWidth; pDepth = thickness;
pDepth = thickness; pX = 0; pY = (-innerDepth / 2) + (innerDepth * p.offset);
pX = 0;
pY = (-innerDepth / 2) + (innerDepth * p.offset);
} }
const pRadius = p.rounded ? Math.min(radius, thickness / 1.5) : 0; const pRadius = p.rounded ? Math.min(radius, thickness / 1.5) : 0;
const partShape = createRoundedRectShape(pWidth, pDepth, pRadius); const partShape = createRoundedRectShape(pWidth, pDepth, pRadius);
const partGeo = new THREE.ExtrudeGeometry(partShape, { const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 8 });
depth: p.height,
bevelEnabled: false,
curveSegments: 8
});
partGeo.rotateX(-Math.PI / 2); partGeo.rotateX(-Math.PI / 2);
partGeo.translate(pX, thickness, pY); partGeo.translate(pX, thickness, pY);
geometries.push(partGeo); geometries.push(partGeo);
}); });
const merged = mergeBufferGeometries(geometries); const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals(); if (merged) merged.computeVertexNormals();
return merged || new THREE.BoxGeometry(1, 1, 1); return merged || new THREE.BoxGeometry(1, 1, 1);
}; };
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter(); const exporter = new STLExporter();
const result = exporter.parse(mesh, { binary: true }); const result = exporter.parse(mesh, { binary: true });
if (result instanceof DataView) { if (result instanceof DataView) return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
}
return result as string; return result as string;
}; };