Try fix layout step

This commit is contained in:
Халимов Рустам
2026-01-10 16:57:20 +03:00
parent 4af73b00eb
commit f7911e7147
5 changed files with 86 additions and 75 deletions
+11 -2
View File
@@ -17,7 +17,7 @@ const App = () => {
cornerRadius: 4, cornerRadius: 4,
}); });
// ВАЖНО: Инициализируем partitions // ИНИЦИАЛИЗАЦИЯ: partitions обязательно присутствует
const [splits, setSplits] = useState<LayoutSplits>({ const [splits, setSplits] = useState<LayoutSplits>({
x: [], x: [],
y: [], y: [],
@@ -28,6 +28,7 @@ const App = () => {
const sharedData = parseShareUrl(); const sharedData = parseShareUrl();
if (sharedData) { if (sharedData) {
setConfig(sharedData.config); setConfig(sharedData.config);
// Защита: если в ссылке старый формат, подставляем пустые partitions
setSplits({ setSplits({
x: sharedData.splits.x || [], x: sharedData.splits.x || [],
y: sharedData.splits.y || [], y: sharedData.splits.y || [],
@@ -68,7 +69,15 @@ const App = () => {
<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"><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>}
{/* ШАГ 2 */}
{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>
)}
{step === 3 && <div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in"><PreviewStep parts={parts} config={config} splits={splits} /></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>
+24 -25
View File
@@ -1,6 +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, LayoutGrid, X, Plus, Settings2, Sliders } from 'lucide-react'; // Используем только безопасные, стандартные иконки
import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Move, Ban } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -15,18 +16,16 @@ 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');
// States for Lines
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);
// State for Cell Editor // Редактор ячеек
const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null); const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null);
// Safeties // --- SAFETY FIRST ---
const safeX = splits?.x || []; const safeX = splits?.x || [];
const safeY = splits?.y || []; const safeY = splits?.y || [];
const safePartitions = splits?.partitions || {}; const safePartitions = splits?.partitions || {};
@@ -38,7 +37,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
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]);
// --- PARTITION LOGIC --- // --- Логика перегородок ---
const getCurrentPartitions = () => { const getCurrentPartitions = () => {
if (!editingCell) return []; if (!editingCell) return [];
const key = `${editingCell.i}-${editingCell.j}`; const key = `${editingCell.i}-${editingCell.j}`;
@@ -53,7 +52,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
id: Date.now().toString(), id: Date.now().toString(),
axis, axis,
offset: 0.5, offset: 0.5,
height: config.drawer.height, // по умолчанию полная высота height: config.drawer.height,
rounded: false rounded: false
}; };
@@ -85,7 +84,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}); });
}; };
// --- MOUSE HANDLERS (Global) ---
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();
@@ -155,10 +153,10 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<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={`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} /> Границы <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={`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} /> Внутри ячеек <Grid size={14} /> Внутри ячеек
</button> </button>
</div> </div>
@@ -173,21 +171,21 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
{/* Instructions */} {/* 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="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"/> {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'} <MousePointer2 size={14} className="text-primary"/>
{mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
</div> </div>
{mode === 'lines' ? ( {mode === 'lines' ? (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight"> <ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-blue-400">Клик:</b> Новая граница</li> <li><b className="text-blue-400">Клик:</b> Новая линия</li>
<li><b className="text-orange-400">Драг:</b> Двигать</li> <li><b className="text-orange-400">Драг:</b> Двигать</li>
</ul> </ul>
) : ( ) : (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight"> <ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-green-400">Клик по ячейке:</b> Настройка стенок</li> <li><b className="text-green-400">Клик по ячейке:</b> Настройка</li>
</ul> </ul>
)} )}
</div> </div>
{/* Rulers */}
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]"> <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">0</span>
<span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span> <span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
@@ -217,7 +215,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)" />
{/* --- Cells & Partitions --- */} {/* --- Ячейки и перегородки --- */}
{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) => {
@@ -236,14 +234,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
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 }); } }}
/> />
{/* Render Partitions */} {/* Рисуем внутренние стенки */}
{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="3" />; return <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="4" />;
} 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="3" />; return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="4" />;
} }
})} })}
</g> </g>
@@ -251,7 +249,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}); });
})} })}
{/* --- Main Grid Lines --- */} {/* --- Основные линии сетки (Границы) --- */}
{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" : ""} />
@@ -284,22 +282,22 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
</div> </div>
{/* --- MODAL EDITOR FOR CELLS --- */} {/* --- ПАНЕЛЬ РЕДАКТОРА (Справа) --- */}
{mode === 'cells' && editingCell && ( {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="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">
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
<h3 className="text-lg font-bold text-white flex items-center gap-2"> <h3 className="text-lg font-bold text-white flex items-center gap-2">
<Settings2 size={18} className="text-primary"/> Редактор ячейки <Grid size={18} className="text-primary"/> Редактор ячейки
</h3> </h3>
<button onClick={() => setEditingCell(null)} className="text-gray-400 hover:text-white"><X size={20}/></button> <button onClick={() => setEditingCell(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
</div> </div>
<div className="flex gap-2 mb-6"> <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"> <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"/> Верт. <Plus size={14} className="text-green-400"/> + Верт.
</button> </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"> <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"/> Гориз. <Plus size={14} className="text-green-400"/> + Гориз.
</button> </button>
</div> </div>
@@ -345,7 +343,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
))} ))}
{getCurrentPartitions().length === 0 && ( {getCurrentPartitions().length === 0 && (
<div className="text-center text-gray-500 text-xs py-4 border border-dashed border-slate-700 rounded"> <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">
<Ban size={20} />
Нет перегородок Нет перегородок
</div> </div>
)} )}
+36 -11
View File
@@ -8,7 +8,7 @@ import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryG
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react'; import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
import { generateShareUrl } from '../utils/share'; import { generateShareUrl } from '../utils/share';
// --- DrawerFrame (Каркас) --- // --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => { const DrawerFrame = ({ config }: { config: AppConfig }) => {
const { width, depth, height } = config.drawer; const { width, depth, height } = config.drawer;
const offset = 0.5; const offset = 0.5;
@@ -32,6 +32,7 @@ interface BinMeshProps {
} }
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => { const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const geometry = useMemo(() => { const geometry = useMemo(() => {
return createBinGeometry( return createBinGeometry(
part.width, part.width,
@@ -39,25 +40,29 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
part.height, part.height,
thickness, thickness,
cornerRadius, cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
); );
}, [part, thickness, cornerRadius]); }, [part, thickness, cornerRadius]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
const edgesGeometry = useMemo(() => { const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20); return new THREE.EdgesGeometry(geometry, 20);
}, [geometry]); }, [geometry]);
return ( return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}> <group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
{/* Сама модель */}
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}> <mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
<meshStandardMaterial <meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color} color={isSelected ? '#f59e0b' : part.color}
roughness={0.5} roughness={0.5}
metalness={0.1} metalness={0.1}
side={THREE.DoubleSide} side={THREE.DoubleSide} // Рисуем обе стороны стенок
/> />
</mesh> </mesh>
{/* Белая подсветка при выборе */}
{isSelected && ( {isSelected && (
<lineSegments geometry={edgesGeometry}> <lineSegments geometry={edgesGeometry}>
<lineBasicMaterial color="white" linewidth={2} /> <lineBasicMaterial color="white" linewidth={2} />
@@ -67,7 +72,7 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
); );
}; };
// --- PreviewStep (Основной) --- // --- PreviewStep (Основной компонент) ---
interface Props { interface Props {
parts: GeneratedPart[]; parts: GeneratedPart[];
config: AppConfig; config: AppConfig;
@@ -80,25 +85,42 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
const [shareUrlCopied, setShareUrlCopied] = useState(false); const [shareUrlCopied, setShareUrlCopied] = useState(false);
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({}); const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// Скролл к выбранной детали в списке
useEffect(() => { useEffect(() => {
if (selectedId && itemRefs.current[selectedId]) { if (selectedId && itemRefs.current[selectedId]) {
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' }); itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} }
}, [selectedId]); }, [selectedId]);
// Скачивание одной детали
const handleDownload = (part: GeneratedPart) => { const handleDownload = (part: GeneratedPart) => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius); const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`); exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
}; };
// Скачивание всего архивом
const handleDownloadAll = async () => { const handleDownloadAll = async () => {
if (isZipping) return; if (isZipping) return;
setIsZipping(true); setIsZipping(true);
try { try {
const zip = new JSZip(); const zip = new JSZip();
parts.forEach(part => { parts.forEach(part => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius); const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
const stlData = generateSTL(mesh); const stlData = generateSTL(mesh);
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData); zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
@@ -117,6 +139,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
} }
}; };
// Поделиться ссылкой
const handleShare = async () => { const handleShare = async () => {
const url = generateShareUrl(config, splits); const url = generateShareUrl(config, splits);
let success = false; let success = false;
@@ -150,8 +173,9 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
{/* Верхняя панель */} {/* Верхняя панель: Размеры + Поделиться */}
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg"> <div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start"> <div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2"> <div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
<Ruler className="text-primary" size={20} /> <Ruler className="text-primary" size={20} />
@@ -173,6 +197,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span> <span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
</div> </div>
</div> </div>
<button <button
onClick={handleShare} onClick={handleShare}
className={` className={`
@@ -268,7 +293,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
`} `}
onClick={() => setSelectedId(part.id)} onClick={() => setSelectedId(part.id)}
> >
{/* Фон-индикатор */} {/* Индикатор цвета */}
<div <div
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none" className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
style={{ backgroundColor: part.color, opacity: 0.1 }} style={{ backgroundColor: part.color, opacity: 0.1 }}
@@ -285,12 +310,12 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
/> />
</div> </div>
{/* --- РАЗМЕРЫ (НОВОЕ) --- */} {/* Размеры */}
<div className="text-[10px] text-gray-400 font-mono z-10"> <div className="text-[10px] text-gray-400 font-mono z-10">
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)} {part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
</div> </div>
{/* Кнопка */} {/* Кнопка скачивания */}
<button <button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }} onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1" className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
+8 -29
View File
@@ -20,10 +20,8 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
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 = safeParts[`${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);
@@ -48,9 +46,7 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts; return parts;
}; };
// --- GEOMETRY GENERATION --- // Геометрия
// Создает форму скругленного прямоугольника (или обычного)
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;
@@ -77,7 +73,6 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
return shape; return shape;
}; };
// Генерирует геометрию ячейки С ПЕРЕГОРОДКАМИ
export const createBinGeometry = ( export const createBinGeometry = (
width: number, width: number,
depth: number, depth: number,
@@ -89,12 +84,13 @@ export const createBinGeometry = (
const geometries: THREE.BufferGeometry[] = []; const geometries: THREE.BufferGeometry[] = [];
// 1. ОСНОВНАЯ КОРОБКА (Дно + Стенки) // 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);
@@ -111,62 +107,45 @@ export const createBinGeometry = (
wallGeo.translate(0, thickness, 0); wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo); geometries.push(wallGeo);
// 2. ВНУТРЕННИЕ ПЕРЕГОРОДКИ // 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
// Мы создаем их внутри внутреннего пространства (innerWidth/innerDepth)
partitions.forEach(p => { partitions.forEach(p => {
// Размеры перегородки
let pWidth = 0; let pWidth = 0;
let pDepth = 0; let pDepth = 0;
// Позиция центра перегородки относительно центра ящика
let pX = 0; let pX = 0;
let pY = 0; // (это Z в 3D) let pY = 0;
if (p.axis === 'x') { if (p.axis === 'x') {
// Вертикальная палка (делит ширину)
pWidth = thickness; pWidth = thickness;
// Длина палки равна внутренней глубине ящика
pDepth = innerDepth; pDepth = innerDepth;
// Смещение: p.offset (0..1) переводим в координаты.
// innerLeft = -innerWidth/2. Position = innerLeft + (innerWidth * offset)
pX = (-innerWidth / 2) + (innerWidth * p.offset); pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = 0; // По центру глубины pY = 0;
} else { } else {
// Горизонтальная палка (делит глубину)
pWidth = innerWidth; pWidth = innerWidth;
pDepth = thickness; pDepth = thickness;
pX = 0;
pX = 0; // По центру ширины
pY = (-innerDepth / 2) + (innerDepth * p.offset); 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, // Высота перегородки (может отличаться от основной) depth: p.height,
bevelEnabled: false, bevelEnabled: false,
curveSegments: 8 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);
}); });
// 3. СЛИЯНИЕ
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 });
+5 -6
View File
@@ -14,16 +14,16 @@ export interface AppConfig {
// Описание одной внутренней перегородки // Описание одной внутренней перегородки
export interface Partition { export interface Partition {
id: string; id: string;
axis: 'x' | 'y'; // x - вертикальная палка, y - горизонтальная axis: 'x' | 'y';
offset: number; // позиция от 0 до 100% (0.5 = центр) offset: number; // 0.1 - 0.9
height: number; // высота стенки в мм height: number;
rounded: boolean; // скруглять ли края этой стенки rounded: boolean;
} }
export interface LayoutSplits { export interface LayoutSplits {
x: number[]; x: number[];
y: number[]; y: number[];
// Ключ: индекс ячейки "i-j", Значение: массив перегородок // Ключ: "i-j", Значение: массив перегородок
partitions: Record<string, Partition[]>; partitions: Record<string, Partition[]>;
} }
@@ -36,6 +36,5 @@ export interface GeneratedPart {
x: number; x: number;
y: number; y: number;
color: string; color: string;
// Передаем перегородки в генератор
internalPartitions: Partition[]; internalPartitions: Partition[];
} }