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

View File

@@ -1,6 +1,7 @@
import React, { useRef, useState, useMemo } from 'react';
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 {
config: AppConfig;
@@ -15,18 +16,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
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);
const [isButtonHovered, setIsButtonHovered] = useState(false);
// State for Cell Editor
// Редактор ячеек
const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null);
// Safeties
// --- SAFETY FIRST ---
const safeX = splits?.x || [];
const safeY = splits?.y || [];
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 sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- PARTITION LOGIC ---
// --- Логика перегородок ---
const getCurrentPartitions = () => {
if (!editingCell) return [];
const key = `${editingCell.i}-${editingCell.j}`;
@@ -53,7 +52,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
id: Date.now().toString(),
axis,
offset: 0.5,
height: config.drawer.height, // по умолчанию полная высота
height: config.drawer.height,
rounded: false
};
@@ -85,7 +84,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
});
};
// --- MOUSE HANDLERS (Global) ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
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">
<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 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>
</div>
@@ -173,21 +171,21 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
{/* 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"/> {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
<MousePointer2 size={14} className="text-primary"/>
{mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
</div>
{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-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>
<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>
@@ -217,7 +215,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Cells & Partitions --- */}
{/* --- Ячейки и перегородки --- */}
{sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1];
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" : ""}
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" />;
return <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="4" />;
} 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" />;
return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="4" />;
}
})}
</g>
@@ -251,7 +249,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
});
})}
{/* --- 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" : ""} />
@@ -284,22 +282,22 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</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="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">
<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>
<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"/> Верт.
<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"/> Гориз.
<Plus size={14} className="text-green-400"/> + Гориз.
</button>
</div>
@@ -345,7 +343,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div>
))}
{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>
)}

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 { generateShareUrl } from '../utils/share';
// --- DrawerFrame (Каркас) ---
// --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => {
const { width, depth, height } = config.drawer;
const offset = 0.5;
@@ -32,32 +32,37 @@ interface BinMeshProps {
}
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const geometry = useMemo(() => {
return createBinGeometry(
part.width,
part.depth,
part.height,
thickness,
cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки
cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
);
}, [part, thickness, cornerRadius]);
}, [part, thickness, cornerRadius]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20);
}, [geometry]);
return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
{/* Сама модель */}
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
<meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color}
roughness={0.5}
metalness={0.1}
side={THREE.DoubleSide}
side={THREE.DoubleSide} // Рисуем обе стороны стенок
/>
</mesh>
{/* Белая подсветка при выборе */}
{isSelected && (
<lineSegments geometry={edgesGeometry}>
<lineBasicMaterial color="white" linewidth={2} />
@@ -67,7 +72,7 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
);
};
// --- PreviewStep (Основной) ---
// --- PreviewStep (Основной компонент) ---
interface Props {
parts: GeneratedPart[];
config: AppConfig;
@@ -80,25 +85,42 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
const [shareUrlCopied, setShareUrlCopied] = useState(false);
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// Скролл к выбранной детали в списке
useEffect(() => {
if (selectedId && itemRefs.current[selectedId]) {
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [selectedId]);
// Скачивание одной детали
const handleDownload = (part: GeneratedPart) => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, 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());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
};
// Скачивание всего архивом
const handleDownloadAll = async () => {
if (isZipping) return;
setIsZipping(true);
try {
const zip = new JSZip();
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 stlData = generateSTL(mesh);
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 url = generateShareUrl(config, splits);
let success = false;
@@ -150,8 +173,9 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
return (
<div className="flex flex-col h-full">
{/* Верхняя панель */}
{/* Верхняя панель: Размеры + Поделиться */}
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
<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>
</div>
</div>
<button
onClick={handleShare}
className={`
@@ -268,7 +293,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
`}
onClick={() => setSelectedId(part.id)}
>
{/* Фон-индикатор */}
{/* Индикатор цвета */}
<div
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
style={{ backgroundColor: part.color, opacity: 0.1 }}
@@ -285,12 +310,12 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
/>
</div>
{/* --- РАЗМЕРЫ (НОВОЕ) --- */}
{/* Размеры */}
<div className="text-[10px] text-gray-400 font-mono z-10">
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
</div>
{/* Кнопка */}
{/* Кнопка скачивания */}
<button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"