From 89734eedea544b4be8fedd74cb5764c600d8b2bb 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 17:57:22 +0300 Subject: [PATCH] Layout step --- src/components/LayoutStep.tsx | 507 +++++++++++++++++++++++----------- 1 file changed, 347 insertions(+), 160 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 1d66ced..4724871 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 } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus, Settings2, Move } from 'lucide-react'; interface Props { config: AppConfig; @@ -11,31 +11,39 @@ interface Props { type EditMode = 'lines' | 'cells'; type Axis = 'x' | 'y'; -export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - // Логируем рендер для отладки - console.log("LayoutStep Render"); +// Тип для перетаскивания: либо основная линия, либо внутренняя перегородка +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'); - // 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 }); // Глобальные координаты (0..1) const [isButtonHovered, setIsButtonHovered] = useState(false); - // Editor State - const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null); + // Состояния для 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); + + // --- SAFE DATA --- 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); - const viewBoxW = 1000; const aspectRatio = depth / width; const viewBoxH = viewBoxW * aspectRatio; @@ -43,99 +51,241 @@ 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]); - // --- ЛОГИКА --- - const addPartition = (axis: 'x' | 'y') => { - if (!editingCell) return; - const key = `${editingCell.i}-${editingCell.j}`; + // --- 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}`; 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); }; - // --- MOUSE HANDLERS --- - const handleGlobalMouseMove = (e: React.MouseEvent) => { + // --- MOUSE LOGIC --- + 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 (mode === 'lines') { - if (dragging) { + // 1. 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 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 }); } - if (isButtonHovered) return; - setHoveredSplit(null); + return; + } + 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; - 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); } + } + } + + // 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 }); + } + } } } }; 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 (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 && 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); } - } else { - if (e.target === svgRef.current) setEditingCell(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); + 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 (
@@ -146,17 +296,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
-
-
@@ -164,11 +314,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
-
+ {/* Instruction Overlay */} +
- {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'} + + {mode === 'lines' ? 'Режим: Основные границы' : 'Режим: Стенки в ячейках'}
-

{mode === 'lines' ? 'Клик: создать. Драг: двигать.' : 'Кликни по ячейке для настройки.'}

+
    +
  • Клик: Создать линию
  • +
  • Драг: Переместить
  • +
  • Двойной клик: Удалить
  • +
@@ -181,10 +337,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {
setDragging(null)} onContextMenu={(e) => e.preventDefault()} + onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > @@ -193,131 +349,162 @@ 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 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 isSelected = editingCell?.i === i && editingCell?.j === j; - const parts = safePartitions[`${i}-${j}`] || []; + const key = `${i}-${j}`; + const parts = safePartitions[key] || []; + const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; return ( - - { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }} - /> + + {/* Подсветка ячейки при наведении в режиме Cells */} + {isHovered && ( + + )} + + {/* Существующие перегородки */} {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); - 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); }} + className={mode === 'cells' ? "cursor-grab" : ""} + > + {/* Невидимая зона захвата */} + + {/* Видимая линия */} + + + ); })} + + {/* Фантомная перегородка (только если наведена мышь на эту ячейку и нет перегородки под курсором) */} + {isHovered && phantomPartition && !hoveredPartition && ( + + {phantomPartition.axis === 'x' ? ( + + ) : ( + + )} + + )} ); }); })} - {/* GRID LINES X */} - {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)}> - - - - )} - - ))} + {/* --- 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); }} + > + + + + ); + })} - {/* GRID LINES Y */} - {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 ( + handleMainSplitHover(e, 'y', i)} + onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }} + > + + + + ); + })} - {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && } - {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && } + {/* Фантомная линия (для Main Grid) */} + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && }
- {/* --- EDITOR PANEL --- */} - {mode === 'cells' && editingCell && ( -
+ {/* --- SIDEBAR FOR SELECTED PARTITION SETTINGS --- */} + {mode === 'cells' && selectedData && ( +
-

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

- +

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

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