From 568632c7fb015921c64b9105b79b8f5a13d930a2 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:09:58 +0300 Subject: [PATCH] Fix --- src/components/LayoutStep.tsx | 540 ++++++++++++---------------------- 1 file changed, 186 insertions(+), 354 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 4724871..c7861c5 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,6 +1,6 @@ -import React, { useRef, useState, useMemo, useEffect } from 'react'; +import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Settings2, Move } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Move } from 'lucide-react'; interface Props { config: AppConfig; @@ -11,31 +11,19 @@ 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 [mode, setMode] = useState('lines'); - // Общие состояния - const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); // Глобальные координаты (0..1) + // 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 [isButtonHovered, setIsButtonHovered] = useState(false); - // Состояния для MAIN линий - const [phantomMainAxis, setPhantomMainAxis] = useState(null); - const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - - // Состояния для CELL (внутренних) - 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); - const [selectedPartitionId, setSelectedPartitionId] = useState(null); // Для настройки высоты/скругления - - // Общее состояние перетаскивания - const [dragging, setDragging] = useState(null); + // Editor State + const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null); // --- SAFE DATA --- const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -44,6 +32,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const width = Math.max(1, config.drawer.width || 300); const depth = Math.max(1, config.drawer.depth || 400); + const viewBoxW = 1000; const aspectRatio = depth / width; const viewBoxH = viewBoxW * aspectRatio; @@ -51,257 +40,115 @@ export const LayoutStep: React.FC = ({ 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]); - // --- 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 addPartition = (i: number, j: number, axis: Axis, offset: number) => { - const key = `${i}-${j}`; + // --- ACTIONS --- + const addPartition = (axis: 'x' | 'y') => { + if (!editingCell) return; + const key = `${editingCell.i}-${editingCell.j}`; const current = safePartitions[key] || []; const newPart: Partition = { id: Math.random().toString(36).substr(2, 9), axis, - offset, // Позиция клика + offset: 0.5, 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 updatePartition = (id: string, updates: Partial) => { + if (!editingCell) return; + const key = `${editingCell.i}-${editingCell.j}`; 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 removePartition = (id: string) => { + if (!editingCell) return; + const key = `${editingCell.i}-${editingCell.j}`; const current = safePartitions[key] || []; onChange({ ...splits, partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) } }); - if (selectedPartitionId === id) setSelectedPartitionId(null); - setHoveredPartition(null); }; - // --- MOUSE LOGIC --- - const handleMouseMove = (e: React.MouseEvent) => { + 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) => { 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 }); - // 1. DRAGGING LOGIC - if (dragging) { - if (dragging.type === 'main') { + if (mode === 'lines') { + if (dragging) { const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; const val = dragging.axis === 'x' ? nx : ny; newSplits[dragging.axis][dragging.index] = val; onChange(newSplits); - } else if (dragging.type === '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') { - // Локальный X внутри ячейки (0..1) - newOffset = (nx - cellX1) / (cellX2 - cellX1); - } else { - // Локальный Y внутри ячейки (0..1) - newOffset = (ny - cellY1) / (cellY2 - cellY1); - } - // Ограничиваем, чтобы не вытащить за пределы ячейки - newOffset = Math.max(0.05, Math.min(0.95, newOffset)); - - updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); + return; } - return; - } + if (isButtonHovered) return; + setHoveredSplit(null); - if (isButtonHovered) return; - - // 2. MODE: LINES (MAIN GRID) - if (mode === 'lines') { - setHoveredMainSplit(null); - // Фантомная линия const SNAP = 0.02; 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; - setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); - } else { setPhantomMainAxis(null); } - } - } - - // 3. MODE: CELLS (INTERNAL PARTITIONS) - else if (mode === 'cells') { - setHoveredPartition(null); - setPhantomPartition(null); - setHoveredCell(null); - - // Находим, над какой ячейкой мышь - 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; - - // Локальные координаты мыши внутри ячейки (0..1) - const lx = (nx - cx1) / cw; - const ly = (ny - cy1) / ch; - - // Проверяем наведение на существующие перегородки - let foundPart = null; - const PARTITION_SNAP = 0.03; // Чувствительность захвата перегородки - - // При наведении проверяем дистанцию в локальных координатах - parts.forEach(p => { - if (p.axis === 'x') { - // Вертикальная перегородка: сравниваем X - if (Math.abs(lx - p.offset) < PARTITION_SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) { - foundPart = p; - } - } else { - // Горизонтальная: сравниваем Y - if (Math.abs(ly - p.offset) < PARTITION_SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) { - foundPart = p; - } - } - }); - - if (foundPart) { - setHoveredPartition({ id: foundPart.id, cellKey: key }); - } else { - // Если не на перегородке - показываем фантом - // Определяем ось фантома (ближе к вертикали или горизонтали внутри ячейки) - // Логика: если мышь ближе к бокам ячейки -> вертикальная, к верху/низу -> горизонтальная? - // Или просто: куда ближе к центру по одной из осей? - // Простой вариант: - const distToCenterX = Math.abs(0.5 - lx); - const distToCenterY = Math.abs(0.5 - ly); - // Если мы ближе к вертикальной оси центра, рисуем вертикальную линию? Нет. - // Давай так: если мышь движется, рисуем линию перпендикулярно ближайшей стороне? - // Упростим: как в Main Grid. - 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'; // Перпендикулярно ближайшей стороне - const offset = axis === 'y' ? ly : lx; // Позиция - - // Не рисовать слишком близко к краям - if (offset > 0.05 && offset < 0.95) { - setPhantomPartition({ axis, offset }); - } - } + setPhantomAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); + } else { + setPhantomAxis(null); + } } } }; const handleMouseDown = (e: React.MouseEvent) => { - if (isButtonHovered) return; - if (mode === 'lines') { - if (hoveredMainSplit) { - if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit }); - } else if (phantomMainAxis) { - const val = phantomMainAxis === 'x' ? mousePos.x : mousePos.y; + 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; const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; - newSplits[phantomMainAxis] = [...newSplits[phantomMainAxis], val]; + newSplits[phantomAxis] = [...newSplits[phantomAxis], val]; onChange(newSplits); - 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 && e.button === 0) { - setDragging({ type: 'partition', cellKey: key, id: part.id, axis: part.axis }); - setSelectedPartitionId(part.id); // Выбираем для панели настроек - } - } else if (hoveredCell && phantomPartition) { - if (e.button === 0) { - // Создаем новую перегородку - addPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset); - // Сразу начинаем тащить только что созданную? Сложно найти ID. - // Оставим просто создание. - } - } else { - // Клик в пустоту - снимаем выделение - setSelectedPartitionId(null); + setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); } + } else { + if (e.target === svgRef.current) setEditingCell(null); } }; - const handleMainSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => { - if (mode !== 'lines' || dragging) return; - e.stopPropagation(); - setHoveredMainSplit({ axis, index }); - setPhantomMainAxis(null); - }; - - // --- UI COMPONENTS --- - - // Получаем настройки выбранной перегородки для Sidebar - const getSelectedPartitionData = () => { - if (!selectedPartitionId) return null; - for (const key in safePartitions) { - const p = safePartitions[key].find(x => x.id === selectedPartitionId); - if (p) return { key, part: p }; - } - return null; - }; - const selectedData = getSelectedPartitionData(); - return (
- {/* HEADER */} + {/* HEADER & CONTROLS */}

2. Макет

-
@@ -311,36 +158,50 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
-
-
- - {/* Instruction Overlay */} -
-
- - {mode === 'lines' ? 'Режим: Основные границы' : 'Режим: Стенки в ячейках'} -
-
    -
  • Клик: Создать линию
  • -
  • Драг: Переместить
  • -
  • Двойной клик: Удалить
  • -
-
+ {/* --- INSTRUCTIONS BAR (MOVED UP) --- */} +
+
+ +
+ {mode === 'lines' ? ( +
+ ЛКМ: Создать/Тянуть линию + ПКМ: Удалить линию +
+ ) : ( +
+ Режим ячеек: Кликни по любой ячейке, чтобы добавить внутренние перегородки. +
+ )} +
+
+
+ + {/* Horizontal Ruler */}
- 0{width} мм + 0 + {width} мм
+ {/* Vertical Ruler */}
- 0{depth} мм + 0 + {depth} мм
+ {/* SVG Container */}
setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} + onMouseMove={handleGlobalMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > @@ -349,162 +210,133 @@ 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]; - const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; - const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH; + const y2 = sortedY[j + 1]; // Исправлено: переменная y2 определена - const key = `${i}-${j}`; - const parts = safePartitions[key] || []; - const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; + const cellX = x1 * viewBoxW; + const cellY = y1 * viewBoxH; + const cellW = (x2 - x1) * viewBoxW; + const cellH = (y2 - y1) * viewBoxH; + + const isSelected = editingCell?.i === i && editingCell?.j === j; + const parts = safePartitions[`${i}-${j}`] || []; return ( - - {/* Подсветка ячейки при наведении в режиме Cells */} - {isHovered && ( - - )} - - {/* Существующие перегородки */} + + { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }} + /> + {/* Отрисовка внутренних перегородок */} {parts.map(p => { - const isPartHovered = hoveredPartition?.id === p.id; - const isSelected = selectedPartitionId === p.id; - const strokeColor = isSelected ? "#a855f7" : (isPartHovered ? "#d8b4fe" : "#7e22ce"); // Purple - - // Координаты линии перегородки - let lx1, ly1, lx2, ly2; if (p.axis === 'x') { const px = cellX + (cellW * p.offset); - lx1 = px; ly1 = cellY; lx2 = px; ly2 = cellY + cellH; + return ; } else { const py = cellY + (cellH * p.offset); - lx1 = cellX; ly1 = py; lx2 = cellX + cellW; ly2 = py; + return ; } - - return ( - { e.stopPropagation(); removePartition(key, p.id); }} - className={mode === 'cells' ? "cursor-grab" : ""} - > - {/* Невидимая зона захвата */} - - {/* Видимая линия */} - - - ); })} - - {/* Фантомная перегородка (только если наведена мышь на эту ячейку и нет перегородки под курсором) */} - {isHovered && phantomPartition && !hoveredPartition && ( - - {phantomPartition.axis === 'x' ? ( - - ) : ( - - )} - - )} ); }); })} - {/* --- MAIN GRID LINES (Отрисовываем поверх всего) --- */} - {safeX.map((x, i) => { - const isHovered = hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i; - return ( - handleMainSplitHover(e, 'x', i)} - onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }} - > - - - - ); - })} + {/* --- ГРАНИЦЫ (СЕТКА) --- */} + {/* Используем 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)}> + + + + )} + + ))} - {safeY.map((y, i) => { - const isHovered = hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i; - return ( - handleMainSplitHover(e, 'y', i)} - onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', 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)}> + + + + )} + + ))} - {/* Фантомная линия (для Main Grid) */} - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } + {/* --- ФАНТОМНЫЕ ЛИНИИ --- */} + {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && } + {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && }
- {/* --- SIDEBAR FOR SELECTED PARTITION SETTINGS --- */} - {mode === 'cells' && selectedData && ( -
+ {/* --- ПРАВАЯ ПАНЕЛЬ (РЕДАКТОР ЯЧЕЕК) --- */} + {mode === 'cells' && editingCell && ( +
-

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

- +

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

+
-
-
- - Выбрана: {selectedData.part.axis === 'x' ? 'Вертикальная' : 'Горизонтальная'} - -
+
+ + +
-
- {/* Высота */} -
-
- Высота - {selectedData.part.height} мм +
+ {(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" + /> + +
- 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-blue-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" - /> -
- - {/* Кнопка удаления */} - -
-
- -
- Выделите другую стенку или нажмите в пустое место для создания новой. + ))}
)}