import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; interface Props { config: AppConfig; splits: LayoutSplits; onChange: (splits: LayoutSplits) => void; } type EditMode = 'lines' | 'cells'; type Axis = 'x' | 'y'; type DragTarget = | { type: 'main'; axis: Axis; index: number } | { type: 'partition'; cellKey: string; id: string; axis: Axis }; export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); // -- STATE -- const [mode, setMode] = useState('lines'); const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null); const [selectedPartitionId, setSelectedPartitionId] = useState(null); // -- DATA -- const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeY = Array.isArray(splits?.y) ? splits.y : []; const safePartitions = splits?.partitions || {}; const drawerW = Math.max(1, config.drawer.width || 300); const drawerD = Math.max(1, config.drawer.depth || 400); const wallThick = config.wallThickness || 1.2; const aspectRatio = drawerD / drawerW; const viewBoxW = 1000; const viewBoxH = viewBoxW * aspectRatio; const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); // -- LOGIC: Dynamic Neighbors Calculation -- // Эта функция пересчитывает реальные границы стенки на лету const calculateDynamicLimits = (target: { axis: Axis, offset: number, min?: number, max?: number }, parts: Partition[]) => { let min = 0; let max = 1; // Используем сохраненные min/max только как "подсказку" где центр стенки const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; parts.forEach(p => { if (p.axis === target.axis) return; // Игнорируем параллельные // Границы соседки (статические, но для соседки они тоже могут быть динамическими - тут упрощение для производительности) // В идеале нужен рекурсивный солвер, но для 2D UI достаточно проверить попадание const pMin = p.min ?? 0; const pMax = p.max ?? 1; if (target.offset > pMin && target.offset < pMax) { if (p.offset < mid) min = Math.max(min, p.offset); else if (p.offset > mid) max = Math.min(max, p.offset); } }); return { min, max }; }; // Поиск границ для НОВОЙ стенки (под курсором) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { return calculateDynamicLimits({ axis: 'x', offset: lx, min: ly, max: ly }, parts); // Hack: передаем ly как min/max чтобы найти соседей по Y для X-стенки? // Нет, для новой стенки логика чуть другая - мы ищем ближайшие стенки вокруг точки (lx, ly) let minX = 0, maxX = 1; let minY = 0, maxY = 1; parts.forEach(p => { // Вычисляем ДИНАМИЧЕСКИЕ границы для соседки, чтобы знать её реальную длину const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); if (p.axis === 'x') { if (ly >= pMin && ly <= pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { if (lx >= pMin && lx <= pMax) { if (p.offset < ly) minY = Math.max(minY, p.offset); if (p.offset > ly) maxY = Math.min(maxY, p.offset); } } }); return { minX, maxX, minY, maxY }; }; // -- ACTIONS -- const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => { const key = `${i}-${j}`; const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), axis, offset, min, max, height: config.drawer.height || 80, rounded: false }; onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); }; const updatePartition = (key: string, id: string, updates: Partial) => { const current = safePartitions[key] || []; const updated = current.map(p => p.id === id ? { ...p, ...updates } : p); onChange({ ...splits, partitions: { ...safePartitions, [key]: updated } }); }; const removePartition = (key: string, id: string) => { const current = safePartitions[key] || []; onChange({ ...splits, partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) } }); if (selectedPartitionId === id) setSelectedPartitionId(null); setHoveredPartition(null); }; const removeMainSplit = (axis: Axis, index: number) => { const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; newSplits[axis] = newSplits[axis].filter((_, i) => i !== index); onChange(newSplits); setHoveredMainSplit(null); setDragging(null); }; const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { const part = safePartitions[key].find(p => p.id === selectedPartitionId); if (part) return { key, part }; } return null; }; const selectedData = getSelectedPartition(); // -- MOUSE -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); if (rect.width === 0) return; 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)); setMousePos({ x: nx, y: ny }); if (dragging) { if (dragging.type === 'main') { const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; const val = dragging.axis === 'x' ? nx : ny; newSplits[dragging.axis][dragging.index] = val; onChange(newSplits); } else { const [iStr, jStr] = dragging.cellKey.split('-'); const i = parseInt(iStr); const j = parseInt(jStr); const cellX1 = sortedX[i]; const cellX2 = sortedX[i+1]; const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; if (dragging.axis === 'x') newOffset = (nx - cellX1) / (cellX2 - cellX1); else newOffset = (ny - cellY1) / (cellY2 - cellY1); newOffset = Math.max(0.02, Math.min(0.98, newOffset)); if (!isNaN(newOffset)) updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } return; } if (isButtonHovered) return; if (mode === 'lines') { setHoveredMainSplit(null); const SNAP = 0.015; if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) { const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP); const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP); if (!closeToX && !closeToY) setPhantomMainAxis(Math.min(nx, 1-nx) < Math.min(ny, 1-ny) ? 'y' : 'x'); else setPhantomMainAxis(null); } } else { setHoveredPartition(null); setPhantomPartition(null); setHoveredCell(null); let cellIdx = null; for (let i = 0; i < sortedX.length - 1; i++) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) { for (let j = 0; j < sortedY.length - 1; j++) { if (ny >= sortedY[j] && ny <= sortedY[j+1]) { cellIdx = { i, j }; break; } } } } if (cellIdx) { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1]; const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1]; const cw = cx2 - cx1; const ch = cy2 - cy1; const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; let found = null; const SNAP = 0.05; for (const p of parts) { // Для проверки наведения тоже используем динамические границы, чтобы не кликать в пустоту const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); if (p.axis === 'x') { if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { if (lx >= pMin && lx <= pMax && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p; } } if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { const bounds = getHoveredBoundaries(lx, ly, parts); const distL = lx - bounds.minX; const distR = bounds.maxX - lx; const distT = ly - bounds.minY; const distB = bounds.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); const axis = minX < minY ? 'y' : 'x'; const width = bounds.maxX - bounds.minX; const height = bounds.maxY - bounds.minY; if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { const offset = axis === 'x' ? lx : ly; const min = axis === 'x' ? bounds.minY : bounds.minX; const max = axis === 'x' ? bounds.maxY : bounds.maxX; setPhantomPartition({ axis, offset, min, max }); } } } } }; const handleMouseDown = (e: React.MouseEvent) => { if (isButtonHovered) return; if (mode === 'lines') { if (hoveredMainSplit) { if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit }); else if (e.button === 2) removeMainSplit(hoveredMainSplit.axis, hoveredMainSplit.index); } else if (phantomMainAxis) { const val = phantomMainAxis === 'x' ? mousePos.x : mousePos.y; const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; newSplits[phantomMainAxis] = [...newSplits[phantomMainAxis], val]; onChange(newSplits); setDragging({ type: 'main', axis: phantomMainAxis, index: newSplits[phantomMainAxis].length - 1 }); } } else { if (hoveredPartition) { const key = hoveredPartition.cellKey; const parts = safePartitions[key] || []; const part = parts.find(p => p.id === hoveredPartition.id); if (part) { if (e.button === 0) { setDragging({ type: 'partition', cellKey: key, id: part.id, axis: part.axis }); setSelectedPartitionId(part.id); } else if (e.button === 2) { removePartition(key, part.id); } } } else if (hoveredCell && phantomPartition) { if (e.button === 0) { createPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset, phantomPartition.min, phantomPartition.max); } } else { setSelectedPartitionId(null); } } }; const renderCellsAndPartitions = () => { const elements = []; for (let i = 0; i < sortedX.length - 1; i++) { for (let j = 0; j < sortedY.length - 1; j++) { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH; const key = `${i}-${j}`; const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; const isAnySelected = parts.some(p => p.id === selectedPartitionId); const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; const textW = Math.max(0, realW - wallThick).toFixed(0); const textD = Math.max(0, realD - wallThick).toFixed(0); if (cellH > 40 && cellW > 60) { elements.push( {textW} × {textD} ); } } elements.push( {isHovered && } {parts.map(p => { // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ГРАНИЦ ДЛЯ ОТРИСОВКИ const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts); let lx1, ly1, lx2, ly2; let dist1 = 0, dist2 = 0; let midX, midY; const isVertical = p.axis === 'x'; if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); // Для X-стенки, p.offset - это X координата. // pMin/pMax - это границы по Y. // Чтобы найти расстояние по бокам, нам нужны границы по X. // Мы ищем ВЕРТИКАЛЬНЫХ соседей в диапазоне Y [pMin, pMax] // calculateDynamicLimits дает границы ВДОЛЬ самой стенки. Это нам дало высоту. // Теперь найдем ширину (слева/справа). // Мы берем точку в центре стенки и ищем ближайших вертикальных соседей const { min: leftLim, max: rightLim } = calculateDynamicLimits({ axis: 'y', offset: (pMin + pMax)/2, min: 0, max: 1 }, parts.filter(pp => pp.axis === 'x')); // Это хак. Правильнее: let left = 0, right = 1; const cy = (pMin + pMax)/2; parts.forEach(n => { if (n.axis === 'x') { // Соседка перекрывает нас по высоте? // Нужно найти её реальные границы const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); if (cy > nMin && cy < nMax) { if (n.offset < p.offset) left = Math.max(left, n.offset); if (n.offset > p.offset) right = Math.min(right, n.offset); } } }); dist1 = (p.offset - left) * realW - wallThick; dist2 = (right - p.offset) * realW - wallThick; midX = px; midY = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); let top = 0, bot = 1; const cx = (pMin + pMax)/2; parts.forEach(n => { if (n.axis === 'y') { const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts); if (cx > nMin && cx < nMax) { if (n.offset < p.offset) top = Math.max(top, n.offset); if (n.offset > p.offset) bot = Math.min(bot, n.offset); } } }); dist1 = (p.offset - top) * realD - wallThick; dist2 = (bot - p.offset) * realD - wallThick; midX = (lx1 + lx2) / 2; midY = py; } const isSel = selectedPartitionId === p.id; const isHov = hoveredPartition?.id === p.id; const textOffset = 10; return ( { e.stopPropagation(); removePartition(key, p.id); }}> {isVertical ? ( <> {Math.max(0, dist1).toFixed(0)} {Math.max(0, dist2).toFixed(0)} ) : ( <> {Math.max(0, dist1).toFixed(0)} {Math.max(0, dist2).toFixed(0)} )} ); })} {isHovered && phantomPartition && !hoveredPartition && !dragging && ( {(() => { const { min: pMin, max: pMax } = phantomPartition; let fx1, fy1, fx2, fy2; if (phantomPartition.axis === 'x') { const px = cellX + (cellW * phantomPartition.offset); fx1 = px; fx2 = px; fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax); } else { const py = cellY + (cellH * phantomPartition.offset); fy1 = py; fy2 = py; fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax); } return ; })()} )} ); } } return elements; }; return (

2. Редактор макета

{mode === 'lines' ? (
ЛКМ: ЛинияПКМ: Удалить
) : (
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
)}
1 ? 'auto' : '100%', height: aspectRatio > 1 ? '100%' : 'auto', aspectRatio: `${1/aspectRatio}`, maxHeight: '100%', maxWidth: '100%', cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair') : (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default') }}> setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}> {renderCellsAndPartitions()} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && ( )}
{mode === 'cells' && selectedData && (

Настройки стенки

Высота {selectedData.part.height} мм
updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/>
updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/>
)}
); };