Fixed layout step

This commit is contained in:
Халимов Рустам
2025-12-27 23:06:22 +03:00
parent 8999d1f06a
commit 6c6c859a3b
3 changed files with 169 additions and 233 deletions

View File

@@ -1,6 +1,6 @@
import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X } from 'lucide-react';
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Minus, SplitSquareVertical, SplitSquareHorizontal } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -8,54 +8,55 @@ interface Props {
onChange: (splits: LayoutSplits) => void;
}
type Axis = 'x' | 'y';
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
// State
// Режимы: 'lines' (двигать линии) или 'cells' (дробить ячейки)
const [mode, setMode] = useState<EditMode>('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);
// New State for Cells
// Состояние для ячеек
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width;
const viewBoxH = viewBoxW * aspectRatio;
// Сортируем линии, чтобы понимать границы ячеек
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]);
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
// --- Helpers for Subdivision ---
const updateSubdivision = (i: number, j: number, field: 'rows' | 'cols', delta: number) => {
const key = `${i}-${j}`;
const current = splits.subdivisions?.[key] || { rows: 1, cols: 1 };
const newVal = Math.max(1, Math.min(10, current[field] + delta));
// Если 1x1, удаляем запись, чтобы не засорять
const newSubdivisions = { ...splits.subdivisions };
if (newVal === 1 && (field === 'rows' ? current.cols : current.rows) === 1) {
delete newSubdivisions[key];
} else {
newSubdivisions[key] = { ...current, [field]: newVal };
}
onChange({ ...splits, subdivisions: newSubdivisions });
};
// --- Логика разделения ячеек ---
const getSubdivision = (i: number, j: number) => {
return splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
};
// --- Handlers ---
const updateSubdivision = (i: number, j: number, type: 'rows' | 'cols', delta: number) => {
const key = `${i}-${j}`;
const current = getSubdivision(i, j);
const newVal = Math.max(1, Math.min(10, current[type] + delta));
const newSubdivisions = { ...splits.subdivisions };
// Если вернулись к 1x1, удаляем запись для чистоты
if (newVal === 1 && (type === 'rows' ? current.cols : current.rows) === 1) {
delete newSubdivisions[key];
} else {
newSubdivisions[key] = { ...current, [type]: newVal };
}
onChange({ ...splits, subdivisions: newSubdivisions });
};
// --- Обработчики мыши ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
@@ -72,35 +73,31 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onChange(newSplits);
return;
}
if (isButtonHovered) return;
setHoveredSplit(null);
// Phantom Logic (Creation)
const SNAP_THRESHOLD = 0.02;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
// Фантомная линия (только если не рядом с существующей)
const SNAP = 0.02;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
const distLeft = nx; const distRight = 1 - nx;
const distTop = ny; const distBottom = 1 - ny;
const minXDist = Math.min(distLeft, distRight);
const minYDist = Math.min(distTop, distBottom);
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
let valid = true;
if (potentialAxis === 'x') { if (closeToX || closeToEdgeX) valid = false; }
else { if (closeToY || closeToEdgeY) valid = false; }
if (valid) setPhantomAxis(potentialAxis);
else setPhantomAxis(null);
if (!closeToX && !closeToY && !closeToEdgeX && !closeToEdgeY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
const minXDist = Math.min(nx, distRight);
const minYDist = Math.min(ny, distBottom);
setPhantomAxis(minXDist < minYDist ? 'y' : 'x');
} else {
setPhantomAxis(null);
}
}
};
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
if (mode !== 'lines') return;
if (dragging) return;
if (mode !== 'lines' || dragging) return;
e.stopPropagation();
setHoveredSplit({ axis, index });
setPhantomAxis(null);
@@ -108,10 +105,10 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const handleMouseDown = (e: React.MouseEvent) => {
if (mode === 'lines') {
if (hoveredSplit) {
if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis) {
} else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
@@ -119,16 +116,11 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
} else {
// Mode === 'cells'
// Клик обрабатывается в самом rect ячейки, а здесь можно сбрасывать выделение
if (e.target === svgRef.current) {
setSelectedCell(null);
}
// В режиме ячеек сбрасываем выделение при клике в пустоту
if (e.target === svgRef.current) setSelectedCell(null);
}
};
const handleMouseUp = () => setDragging(null);
const removeSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
@@ -140,24 +132,25 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative">
{/* --- HEADER CONTROLS --- */}
<div className="flex justify-between items-center mb-4 z-20">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
<Grid size={24} /> 2. Редактор макета
</h2>
{/* --- TOGGLE MODE --- */}
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
<button
onClick={() => { setMode('lines'); setSelectedCell(null); }}
className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}
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} /> Границы
<Grid size={16} /> Основные границы
</button>
<button
onClick={() => setMode('cells')}
className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}
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} /> Ячейки
<LayoutGrid size={16} /> Деление ячеек
</button>
</div>
@@ -165,73 +158,33 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onClick={() => onChange({ x: [], y: [], subdivisions: {} })}
className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
>
<RotateCcw size={14} /> Сбросить
<RotateCcw size={14} /> Сбросить всё
</button>
</div>
<div className="flex flex-col h-full select-none relative">
{/* Панель настроек выбранной ячейки (Появляется только в режиме Cells) */}
{mode === 'cells' && selectedCell && (
<div className="absolute top-4 right-4 z-30 bg-slate-800/90 backdrop-blur p-4 rounded-xl border border-slate-600 shadow-2xl animate-in slide-in-from-top-2 fade-in">
<div className="flex justify-between items-start mb-3">
<span className="text-xs font-bold text-gray-400 uppercase tracking-wide">Настройка ячейки</span>
<button onClick={() => setSelectedCell(null)} className="text-gray-500 hover:text-white"><X size={14}/></button>
</div>
<div className="flex gap-4">
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-500 mb-1">КОЛОНКИ (X)</span>
<div className="flex items-center bg-slate-900 rounded border border-slate-700">
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', -1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-r border-slate-700"
>-</button>
<span className="w-8 text-center font-mono font-bold">{getSubdivision(selectedCell.i, selectedCell.j).cols}</span>
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', 1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-l border-slate-700"
>+</button>
</div>
</div>
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-500 mb-1">РЯДЫ (Y)</span>
<div className="flex items-center bg-slate-900 rounded border border-slate-700">
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', -1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-r border-slate-700"
>-</button>
<span className="w-8 text-center font-mono font-bold">{getSubdivision(selectedCell.i, selectedCell.j).rows}</span>
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', 1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-l border-slate-700"
>+</button>
</div>
</div>
</div>
</div>
)}
<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">
{/* Instruction Box */}
{/* 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="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
<MousePointer2 size={14} className="text-primary"/> Инструкция
<MousePointer2 size={14} className="text-primary"/> Режим: {mode === 'lines' ? 'Границы' : 'Ячейки'}
</div>
{mode === 'lines' ? (
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight">
<li><b className="text-blue-400">Клик у края:</b> Новая линия</li>
<li><b className="text-orange-400">Драг:</b> Переместить</li>
<li><b className="text-red-400">ПКМ:</b> Удалить</li>
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-blue-400">Клик:</b> Новая линия</li>
<li><b className="text-orange-400">Драг:</b> Двигать линию</li>
<li><b className="text-red-400">ПКМ:</b> Удалить линию</li>
</ul>
) : (
<ul className="space-y-1.5 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>Настрой деление в панели</li>
<li>Используй меню для деления внутри</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>
@@ -243,8 +196,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
</div>
{/* SVG Container */}
<div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group"
style={{
width: '100%',
maxWidth: '900px',
@@ -259,8 +213,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
className="w-full h-full touch-none"
onMouseMove={handleGlobalMouseMove}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onMouseUp={() => setDragging(null)}
onContextMenu={(e) => e.preventDefault()}
>
<defs>
@@ -270,34 +223,27 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- CELLS & SUBDIVISIONS --- */}
{/* Рисуем ячейки ПЕРЕД линиями, чтобы ловить клики в режиме Cells */}
{/* --- РЕНДЕРИНГ ЯЧЕЕК --- */}
{sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => {
const y2 = sortedY[j + 1];
const width = (x2 - x1) * config.drawer.width;
const depth = (y2 - y1) * config.drawer.depth;
const centerX = ((x1 + x2) / 2) * viewBoxW;
const centerY = ((y1 + y2) / 2) * viewBoxH;
const cellX = x1 * viewBoxW;
const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW;
const cellH = (y2 - y1) * viewBoxH;
const isSelected = selectedCell?.i === i && selectedCell?.j === j;
const subdiv = getSubdivision(i, j);
return (
<g key={`cell-${i}-${j}`}>
{/* Интерактивный прямоугольник ячейки */}
{/* Прямоугольник ячейки */}
<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.15)" : "transparent"}
stroke={isSelected ? "#3b82f6" : "transparent"}
strokeWidth="2"
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-colors" : ""}
strokeWidth="3"
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""}
onClick={(e) => {
if (mode === 'cells') {
e.stopPropagation();
@@ -306,118 +252,111 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}}
/>
{/* Отрисовка внутренних разделителей (Визуализация) */}
{/* Внутренние пунктирные линии */}
{subdiv.cols > 1 && Array.from({ length: subdiv.cols - 1 }).map((_, cI) => {
const splitX = cellX + (cellW / subdiv.cols) * (cI + 1);
return (
<line
key={`sub-c-${cI}`}
x1={splitX} y1={cellY} x2={splitX} y2={cellY + cellH}
stroke="rgba(255,255,255,0.3)" strokeWidth="1" strokeDasharray="4,2"
className="pointer-events-none"
/>
);
return <line key={`sc-${cI}`} x1={splitX} y1={cellY} x2={splitX} y2={cellY + cellH} stroke="#3b82f6" strokeWidth="2" strokeDasharray="5,5" className="pointer-events-none opacity-70"/>;
})}
{subdiv.rows > 1 && Array.from({ length: subdiv.rows - 1 }).map((_, rI) => {
const splitY = cellY + (cellH / subdiv.rows) * (rI + 1);
return (
<line
key={`sub-r-${rI}`}
x1={cellX} y1={splitY} x2={cellX + cellW} y2={splitY}
stroke="rgba(255,255,255,0.3)" strokeWidth="1" strokeDasharray="4,2"
className="pointer-events-none"
/>
);
return <line key={`sr-${rI}`} x1={cellX} y1={splitY} x2={cellX + cellW} y2={splitY} stroke="#3b82f6" strokeWidth="2" strokeDasharray="5,5" className="pointer-events-none opacity-70"/>;
})}
{/* Текст размеров (Скрываем если ячейка разбита или слишком мелкая) */}
{/* РАЗМЕРЫ: показываем только если ячейка не разбита */}
{subdiv.rows === 1 && subdiv.cols === 1 && (
<text
x={centerX} y={centerY}
x={cellX + cellW/2} y={cellY + cellH/2}
textAnchor="middle" dominantBaseline="middle"
className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200"
style={{
fontSize: `${Math.min(36, cellH * 0.6, cellW * 0.25)}px`,
textShadow: '1px 1px 3px rgba(0,0,0,0.8)',
opacity: Math.min(36, cellH * 0.6, cellW * 0.25) < 10 ? 0 : 1
}}
className="pointer-events-none select-none fill-slate-300 font-bold font-mono text-[24px] opacity-50"
style={{ textShadow: '1px 1px 2px black' }}
>
{width.toFixed(0)} × {depth.toFixed(0)}
{((x2 - x1) * config.drawer.width).toFixed(0)}×{((y2 - y1) * config.drawer.depth).toFixed(0)}
</text>
)}
</g>
);
});
})}
{/* --- Main Grid Lines (X) --- */}
{splits.x.map((x, i) => {
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'x' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
return (
<g
key={`x-${i}`}
onDoubleClick={() => removeSplit('x', i)}
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
className={mode === 'lines' ? "cursor-col-resize" : ""}
>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="80" />
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{mode === 'lines' && (isHovered || isDragging) && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- ЛИНИИ СЕТКИ (Поверх ячеек) --- */}
{splits.x.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => handleSplitHover(e, 'x', i)}>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
{mode === 'lines' && hoveredSplit?.axis === 'x' && hoveredSplit.index === i && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
</g>
))}
{/* --- Main Grid Lines (Y) --- */}
{splits.y.map((y, i) => {
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'y' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
{splits.y.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => handleSplitHover(e, 'y', i)}>
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-row-resize" : ""} />
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
{mode === 'lines' && hoveredSplit?.axis === 'y' && hoveredSplit.index === i && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
</g>
))}
return (
<g
key={`y-${i}`}
onDoubleClick={() => removeSplit('y', i)}
onMouseMove={(e) => handleSplitHover(e, 'y', i)}
className={mode === 'lines' ? "cursor-row-resize" : ""}
>
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="80" />
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{mode === 'lines' && (isHovered || isDragging) && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- Phantom Lines --- */}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && (
<g className="pointer-events-none opacity-60">
<line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
</g>
)}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && (
<g className="pointer-events-none opacity-60">
<line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
</g>
{/* Фантомная линия */}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis && (
<line
x1={phantomAxis === 'x' ? mousePos.x * viewBoxW : 0}
y1={phantomAxis === 'x' ? 0 : mousePos.y * viewBoxH}
x2={phantomAxis === 'x' ? mousePos.x * viewBoxW : viewBoxW}
y2={phantomAxis === 'x' ? viewBoxH : mousePos.y * viewBoxH}
stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"
/>
)}
</svg>
{/* --- КОНТРОЛЫ ЯЧЕЙКИ (Поверх SVG) --- */}
{mode === 'cells' && selectedCell && (
<div
className="absolute flex flex-col gap-2 p-2 bg-slate-800/90 backdrop-blur rounded-lg border border-blue-500 shadow-2xl transform -translate-x-1/2 -translate-y-1/2"
style={{
// Позиционируем прямо по центру выбранной ячейки
left: `${((sortedX[selectedCell.i] + sortedX[selectedCell.i+1])/2) * 100}%`,
top: `${((sortedY[selectedCell.j] + sortedY[selectedCell.j+1])/2) * 100}%`,
}}
onMouseDown={(e) => e.stopPropagation()} // Чтобы клик не снимал выделение
>
{/* Ряды (Горизонтально) */}
<div className="flex items-center gap-2">
<SplitSquareVertical size={16} className="text-blue-400" />
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', -1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Minus size={12}/></button>
<span className="font-mono font-bold w-4 text-center">{getSubdivision(selectedCell.i, selectedCell.j).cols}</span>
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', 1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Plus size={12}/></button>
</div>
{/* Колонки (Вертикально) */}
<div className="flex items-center gap-2">
<SplitSquareHorizontal size={16} className="text-blue-400" />
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', -1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Minus size={12}/></button>
<span className="font-mono font-bold w-4 text-center">{getSubdivision(selectedCell.i, selectedCell.j).rows}</span>
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', 1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Plus size={12}/></button>
</div>
<button
onClick={() => setSelectedCell(null)}
className="mt-1 text-[10px] text-gray-400 hover:text-white text-center bg-slate-700/50 rounded py-1"
>
Готово
</button>
</div>
)}
</div>
</div>
</div>

View File

@@ -16,17 +16,14 @@ export const calculateParts = (
for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) {
// Глобальные размеры ячейки сетки
const rawX = xPoints[i] * config.drawer.width;
const rawY = yPoints[j] * config.drawer.depth;
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
// Проверяем, есть ли разделение для этой ячейки
// Получаем настройки деления для этой ячейки
const subdiv = splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
// Вычисляем размер одной "под-ячейки"
// Делим общую ширину на кол-во колонок
const subCellWidth = rawW / subdiv.cols;
const subCellDepth = rawD / subdiv.rows;
@@ -37,7 +34,6 @@ export const calculateParts = (
const subX = rawX + (c * subCellWidth);
const subY = rawY + (r * subCellDepth);
// Применяем Tolerance (зазор) к каждой микро-ячейке
const realWidth = subCellWidth - config.printerTolerance;
const realDepth = subCellDepth - config.printerTolerance;
const realX = subX + (config.printerTolerance / 2);
@@ -45,9 +41,15 @@ export const calculateParts = (
if (realWidth < 5 || realDepth < 5) continue;
// Формируем имя: если ячейка поделена, добавляем индексы (1-1, 1-2...)
let partName = `Ячейка ${i+1}-${j+1}`;
if (subdiv.rows > 1 || subdiv.cols > 1) {
partName += ` (${r+1}-${c+1})`;
}
parts.push({
id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}` + (subdiv.rows > 1 || subdiv.cols > 1 ? ` (${r+1}x${c+1})` : ''),
name: partName,
width: realWidth,
depth: realDepth,
height: config.drawer.height,
@@ -64,8 +66,7 @@ export const calculateParts = (
return parts;
};
// ... Остальной код (createBinGeometry, exportSTL) остается без изменений ...
// (Копируй функции createRoundedRectShape, createBinGeometry и прочие из предыдущего файла, они не менялись)
// ... Вспомогательные функции генерации геометрии (без изменений) ...
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape();
const x = -width / 2;
@@ -101,9 +102,7 @@ export const createBinGeometry = (
): THREE.BufferGeometry => {
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
depth: thickness,
bevelEnabled: false,
curveSegments: 16
depth: thickness, bevelEnabled: false, curveSegments: 16
});
floorGeo.rotateX(-Math.PI / 2);
@@ -119,9 +118,7 @@ export const createBinGeometry = (
const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: wallHeight,
bevelEnabled: false,
curveSegments: 16
depth: wallHeight, bevelEnabled: false, curveSegments: 16
});
wallGeo.rotateX(-Math.PI / 2);

View File

@@ -11,16 +11,16 @@ export interface AppConfig {
cornerRadius: number;
}
// Конфигурация разделения одной ячейки
// Новая структура: сколько рядов и колонок внутри конкретной ячейки
export interface CellSubdivision {
rows: number; // По умолчанию 1
cols: number; // По умолчанию 1
rows: number; // горизонтальные ряды
cols: number; // вертикальные колонки
}
export interface LayoutSplits {
x: number[];
y: number[];
// Ключ: "xIndex-yIndex" (например "0-0" для первой ячейки)
// Ключ - это индекс ячейки "xIndex-yIndex" (например "0-0")
subdivisions: Record<string, CellSubdivision>;
}