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

@@ -17,7 +17,7 @@ const App = () => {
cornerRadius: 4,
});
// ВАЖНО: Инициализируем partitions
// ИНИЦИАЛИЗАЦИЯ: partitions обязательно присутствует
const [splits, setSplits] = useState<LayoutSplits>({
x: [],
y: [],
@@ -28,6 +28,7 @@ const App = () => {
const sharedData = parseShareUrl();
if (sharedData) {
setConfig(sharedData.config);
// Защита: если в ссылке старый формат, подставляем пустые partitions
setSplits({
x: sharedData.splits.x || [],
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">
{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>}
</main>

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"

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 rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
// Получаем перегородки для этой ячейки
const internalPartitions = safeParts[`${i}-${j}`] || [];
// Рассчитываем реальные размеры с учетом допуска принтера
const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2);
@@ -48,9 +46,7 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts;
};
// --- GEOMETRY GENERATION ---
// Создает форму скругленного прямоугольника (или обычного)
// Геометрия
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape();
const x = -width / 2;
@@ -77,7 +73,6 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
return shape;
};
// Генерирует геометрию ячейки С ПЕРЕГОРОДКАМИ
export const createBinGeometry = (
width: number,
depth: number,
@@ -89,12 +84,13 @@ export const createBinGeometry = (
const geometries: THREE.BufferGeometry[] = [];
// 1. ОСНОВНАЯ КОРОБКА (Дно + Стенки)
// 1. ДНО
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 });
floorGeo.rotateX(-Math.PI / 2);
geometries.push(floorGeo);
// 2. ВНЕШНИЕ СТЕНКИ
const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0, radius - thickness);
const innerWidth = width - (2 * thickness);
@@ -111,62 +107,45 @@ export const createBinGeometry = (
wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo);
// 2. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
// Мы создаем их внутри внутреннего пространства (innerWidth/innerDepth)
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
partitions.forEach(p => {
// Размеры перегородки
let pWidth = 0;
let pDepth = 0;
// Позиция центра перегородки относительно центра ящика
let pX = 0;
let pY = 0; // (это Z в 3D)
let pY = 0;
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; // По центру глубины
pY = 0;
} else {
// Горизонтальная палка (делит глубину)
pWidth = innerWidth;
pDepth = thickness;
pX = 0; // По центру ширины
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, // Высота перегородки (может отличаться от основной)
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

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