From 8d4b26c0012226ff3678736e01a8c245c0fc3642 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sat, 10 Jan 2026 18:35:39 +0300 Subject: [PATCH] Fixed --- src/components/LayoutStep.tsx | 556 ++++++++++++++++++++++------------ 1 file changed, 359 insertions(+), 197 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index c7861c5..15730a7 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,6 +1,6 @@ -import React, { useRef, useState, useMemo } from 'react'; +import React, { useRef, useState, useMemo, useEffect } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Move } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; interface Props { config: AppConfig; @@ -11,197 +11,331 @@ interface Props { 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); + const containerRef = useRef(null); + const [mode, setMode] = useState('lines'); - // States - const [phantomAxis, setPhantomAxis] = useState(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 [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Editor State - const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null); + // Main Grid States + const [phantomMainAxis, setPhantomMainAxis] = useState(null); + const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // --- SAFE DATA --- + // Partition States + 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 } | null>(null); + + // Selection & Dragging + const [selectedPartitionId, setSelectedPartitionId] = useState(null); + const [dragging, setDragging] = useState(null); + + // --- Safe Data Access --- const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeY = Array.isArray(splits?.y) ? splits.y : []; const safePartitions = splits?.partitions || {}; - const width = Math.max(1, config.drawer.width || 300); - const depth = Math.max(1, config.drawer.depth || 400); - + // --- Dimensions & Aspect Ratio --- + const drawerW = Math.max(1, config.drawer.width || 300); + const drawerD = Math.max(1, config.drawer.depth || 400); + const aspectRatio = drawerD / drawerW; + + // ViewBox (internal SVG coordinates) const viewBoxW = 1000; - const aspectRatio = depth / width; 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]); - // --- ACTIONS --- - const addPartition = (axis: 'x' | 'y') => { - if (!editingCell) return; - const key = `${editingCell.i}-${editingCell.j}`; + // --- Helper: Get Partition Data --- + 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(); + + // --- ACTIONS: MAIN GRID --- + 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); + setIsButtonHovered(false); + }; + + // --- ACTIONS: PARTITIONS --- + const createPartition = (i: number, j: number, axis: Axis, offset: number) => { + const key = `${i}-${j}`; const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), axis, - offset: 0.5, + offset, height: config.drawer.height || 80, rounded: false }; onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); + setSelectedPartitionId(newPart.id); }; - const updatePartition = (id: string, updates: Partial) => { - if (!editingCell) return; - const key = `${editingCell.i}-${editingCell.j}`; + 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 = (id: string) => { - if (!editingCell) return; - const key = `${editingCell.i}-${editingCell.j}`; + 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); - setHoveredSplit(null); - setDragging(null); - setIsButtonHovered(false); - }; - - // --- MOUSE HANDLERS --- - const handleGlobalMouseMove = (e: React.MouseEvent) => { + // --- MOUSE HANDLER --- + const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); if (rect.width === 0) return; + // Normalize coordinates (0 to 1) 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 (mode === 'lines') { - if (dragging) { + // --- DRAGGING LOGIC --- + 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); - return; + } else { + // Dragging Partition + 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.05, Math.min(0.95, newOffset)); + updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } - if (isButtonHovered) return; - setHoveredSplit(null); + return; + } - const SNAP = 0.02; + if (isButtonHovered) return; + + // --- HOVER LOGIC: MAIN LINES --- + if (mode === 'lines') { + setHoveredMainSplit(null); + const SNAP = 0.015; // Чувствительность + // Check hover existing + // (Logic handled in individual line elements via onMouseMove to simplify global handler) + + // Phantom Line 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) { const distRight = 1 - nx; const distBottom = 1 - ny; - setPhantomAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); - } else { - setPhantomAxis(null); - } + setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); + } else { setPhantomMainAxis(null); } + } + } + + // --- HOVER LOGIC: PARTITIONS --- + else if (mode === 'cells') { + setHoveredPartition(null); + setPhantomPartition(null); + setHoveredCell(null); + + // 1. Find which cell we are in + let cellIndex = null; + for(let i=0; i= sortedX[i] && nx <= sortedX[i+1]) { + for(let j=0; j= sortedY[j] && ny <= sortedY[j+1]) { + cellIndex = { i, j }; + break; + } + } + } + } + + if (cellIndex) { + setHoveredCell(cellIndex); + const key = `${cellIndex.i}-${cellIndex.j}`; + const parts = safePartitions[key] || []; + + const cx1 = sortedX[cellIndex.i]; const cx2 = sortedX[cellIndex.i+1]; + const cy1 = sortedY[cellIndex.j]; const cy2 = sortedY[cellIndex.j+1]; + const cw = cx2 - cx1; const ch = cy2 - cy1; + + // Local coords in cell (0..1) + const lx = (nx - cx1) / cw; + const ly = (ny - cy1) / ch; + + // Check existing partitions + let foundPart = null; + const PART_SNAP = 0.05; + + for (const p of parts) { + if (p.axis === 'x') { + if (Math.abs(lx - p.offset) < PART_SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) foundPart = p; + } else { + if (Math.abs(ly - p.offset) < PART_SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) foundPart = p; + } + } + + if (foundPart) { + setHoveredPartition({ id: foundPart.id, cellKey: key }); + } else { + // Show Phantom Partition based on movement direction logic + // If moving more horizontally -> vertical split. Moving vertically -> horizontal split. + // Simplified: Distance to edges + const distLeft = lx; const distRight = 1 - lx; + const distTop = ly; const distBottom = 1 - ly; + const minX = Math.min(distLeft, distRight); + const minY = Math.min(distTop, distBottom); + + const axis = minX < minY ? 'y' : 'x'; + + if (lx > 0.05 && lx < 0.95 && ly > 0.05 && ly < 0.95) { + setPhantomPartition({ axis, offset: axis === 'x' ? lx : ly }); + } + } } } }; const handleMouseDown = (e: React.MouseEvent) => { + if (isButtonHovered) return; + if (mode === 'lines') { - if (hoveredSplit && !isButtonHovered) { - if (e.button === 0) setDragging(hoveredSplit); - else if (e.button === 2) removeMainSplit(hoveredSplit.axis, hoveredSplit.index); - } else if (phantomAxis && !isButtonHovered) { - const val = phantomAxis === 'x' ? mousePos.x : mousePos.y; + 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[phantomAxis] = [...newSplits[phantomAxis], val]; + newSplits[phantomMainAxis] = [...newSplits[phantomMainAxis], val]; onChange(newSplits); - setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); + setDragging({ type: 'main', axis: phantomMainAxis, index: newSplits[phantomMainAxis].length - 1 }); + } + } + else if (mode === 'cells') { + 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); + } + } else { + setSelectedPartitionId(null); } - } else { - if (e.target === svgRef.current) setEditingCell(null); } }; return ( -
+
- {/* HEADER & CONTROLS */} -
-

- 2. Макет + {/* HEADER */} +
+

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

-
-
- {/* --- INSTRUCTIONS BAR (MOVED UP) --- */} -
-
- -
+ {/* --- INSTRUCTIONS --- */} +
+ {mode === 'lines' ? ( -
+
ЛКМ: Создать/Тянуть линию - ПКМ: Удалить линию + 2xЛКМ / ПКМ: Удалить
) : ( -
- Режим ячеек: Кликни по любой ячейке, чтобы добавить внутренние перегородки. +
+ ЛКМ в ячейке: Создать перегородку + Драг: Двигать + 2xЛКМ: Удалить
)}
-
-
+ {/* --- CANVAS AREA --- */} +
- {/* Horizontal Ruler */} -
- 0 - {width} мм -
- -
- {/* Vertical Ruler */} -
- 0 - {depth} мм -
- - {/* SVG Container */} -
+
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)} onContextMenu={(e) => e.preventDefault()} + setDragging(null)} + onMouseLeave={() => setDragging(null)} + onContextMenu={(e) => e.preventDefault()} > @@ -210,133 +344,161 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {/* --- ЯЧЕЙКИ И ПЕРЕГОРОДКИ --- */} + {/* --- ЯЧЕЙКИ И ВНУТРЕННОСТИ --- */} {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]; // Исправлено: переменная y2 определена + const y2 = sortedY[j + 1]; + const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; + const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH; - const cellX = x1 * viewBoxW; - const cellY = y1 * viewBoxH; - const cellW = (x2 - x1) * viewBoxW; - const cellH = (y2 - y1) * viewBoxH; + const key = `${i}-${j}`; + const parts = safePartitions[key] || []; - const isSelected = editingCell?.i === i && editingCell?.j === j; - const parts = safePartitions[`${i}-${j}`] || []; + // Логика выделения ячейки + const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; + const isAnyPartSelected = parts.some(p => p.id === selectedPartitionId); return ( - - { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }} - /> - {/* Отрисовка внутренних перегородок */} + + {/* Фон ячейки при наведении */} + {isHovered && ( + + )} + + {/* Рамка если выбрана стенка внутри этой ячейки */} + {isAnyPartSelected && mode === 'cells' && ( + + )} + + {/* Перегородки */} {parts.map(p => { + const isSelected = selectedPartitionId === p.id; + const isHoveredPart = hoveredPartition?.id === p.id; + + let lx1, ly1, lx2, ly2; if (p.axis === 'x') { const px = cellX + (cellW * p.offset); - return ; + lx1 = px; ly1 = cellY; lx2 = px; ly2 = cellY + cellH; } else { const py = cellY + (cellH * p.offset); - return ; + lx1 = cellX; ly1 = py; lx2 = cellX + cellW; ly2 = py; } + + return ( + { e.stopPropagation(); removePartition(key, p.id); }}> + {/* Толстая невидимая линия для захвата */} + + {/* Видимая линия */} + + + ); })} + + {/* Фантомная перегородка (только если наведена мышь на ячейку и нет перегородки под курсором) */} + {isHovered && phantomPartition && !hoveredPartition && !dragging && ( + + {phantomPartition.axis === 'x' ? ( + + ) : ( + + )} + + )} ); }); })} - {/* --- ГРАНИЦЫ (СЕТКА) --- */} - {/* Используем 100% для y2/x2, чтобы линии точно доходили до краев */} - {safeX.map((x, i) => ( - { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'x', index: i }); setPhantomAxis(null); } }}> - - - {mode === 'lines' && hoveredSplit?.axis === 'x' && hoveredSplit.index === i && ( - { e.stopPropagation(); removeMainSplit('x', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}> - - - - )} - - ))} + {/* --- ГЛАВНЫЕ ЛИНИИ (Поверх всего) --- */} + {safeX.map((x, i) => { + const isHovered = hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i; + return ( + { 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(); setHoveredSplit({ axis: 'y', index: i }); setPhantomAxis(null); } }}> - - - {mode === 'lines' && hoveredSplit?.axis === 'y' && hoveredSplit.index === i && ( - { e.stopPropagation(); removeMainSplit('y', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}> - - - - )} - - ))} + {safeY.map((y, i) => { + const isHovered = hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i; + return ( + { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} + onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }} + > + + + + ); + })} - {/* --- ФАНТОМНЫЕ ЛИНИИ --- */} - {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && } - {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && } + {/* Фантомная главная линия */} + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && }
- {/* --- ПРАВАЯ ПАНЕЛЬ (РЕДАКТОР ЯЧЕЕК) --- */} - {mode === 'cells' && editingCell && ( -
+ {/* --- SIDEBAR FOR SELECTED PARTITION SETTINGS --- */} + {mode === 'cells' && selectedData && ( +
-

Редактор ячейки

- +

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

+
-
- - -
- -
- {(safePartitions[`${editingCell.i}-${editingCell.j}`] || []).map((p, idx) => ( -
-
- - Стенка #{idx+1} ({p.axis === 'x' ? 'Верт' : 'Гориз'}) - - -
-
-
-
- Позиция {(p.offset * 100).toFixed(0)}% -
- updatePartition(p.id, { offset: parseFloat(e.target.value) })} - className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500" - /> -
-
-
- Высота {p.height} мм -
- updatePartition(p.id, { height: parseFloat(e.target.value) })} - className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-blue-500" - /> -
-
- updatePartition(p.id, { rounded: e.target.checked })} - className="rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0" - /> - -
-
+
+ {/* Высота */} +
+
+ Высота + {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" + /> +
+ + {/* Удалить */} + +
+ +
+ Выделите стенку для настройки.
Двойной клик удаляет её.
)}