From d85cac8a16990360632387ba2b958dc536a3a308 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: Sun, 11 Jan 2026 13:34:11 +0300 Subject: [PATCH] 1 --- src/components/LayoutStep.tsx | 192 +++++++++++++++++++--------------- 1 file changed, 105 insertions(+), 87 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 4d83fec..0155872 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,6 +1,6 @@ import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2, Plus } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; interface Props { config: AppConfig; @@ -18,31 +18,31 @@ type DragTarget = export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const svgRef = useRef(null); - // -- STATE -- + // --- STATE --- const [mode, setMode] = useState('lines'); const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Main Grid Hover + // Main Grid const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // Partition Hover + // Partitions 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); - // -- SAFE DATA -- + // --- SAFE 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 thickness = config.wallThickness || 1.2; const viewBoxW = 1000; const viewBoxH = viewBoxW * aspectRatio; @@ -50,7 +50,7 @@ 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]); - // -- HELPERS -- + // --- HELPERS --- const getSelectedPartition = () => { if (!selectedPartitionId) return null; for (const key in safePartitions) { @@ -61,48 +61,29 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // --- ИСПРАВЛЕННЫЙ РАСЧЕТ СОСЕДЕЙ ДЛЯ РАЗМЕРОВ --- - // targetOffset: позиция стенки (0..1) по её основной оси - // crossPos: позиция центра стенки по перпендикулярной оси (чтобы понять, пересекаются ли они) - // axis: ось самой стенки ('x' или 'y') - const getNearestNeighbors = (targetOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { - let min = 0; - let max = 1; + // Поиск ближайших соседей для расчета размеров + const getNeighborOffsets = (currentOffset: number, crossPos: number, axis: Axis, parts: Partition[]) => { + let minLimit = 0; + let maxLimit = 1; parts.forEach(p => { - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; - - if (axis === 'x') { - // Мы - вертикальная стенка (X). Ищем другие ВЕРТИКАЛЬНЫЕ стенки слева/справа. - if (p.axis === 'x') { - // Они должны перекрываться с нами по высоте (Y) - // Наша "высота" - это точка crossPos (середина). - // Стенка P занимает по Y от pMin до pMax. - if (crossPos > pMin && crossPos < pMax) { - // Стенка P находится слева от нас? - if (p.offset < targetOffset) min = Math.max(min, p.offset); - // Стенка P находится справа от нас? - if (p.offset > targetOffset) max = Math.min(max, p.offset); - } - } - } else { - // Мы - горизонтальная стенка (Y). Ищем другие ГОРИЗОНТАЛЬНЫЕ стенки сверху/снизу. - if (p.axis === 'y') { - // Они должны перекрываться с нами по ширине (X) - // Наша "ширина" - это точка crossPos (середина). - // Стенка P занимает по X от pMin до pMax. - if (crossPos > pMin && crossPos < pMax) { - if (p.offset < targetOffset) min = Math.max(min, p.offset); - if (p.offset > targetOffset) max = Math.min(max, p.offset); - } - } + // Если стенка параллельна нашей, мы ищем, не является ли она барьером + if (p.axis === axis) { + const pMin = p.min ?? 0; + const pMax = p.max ?? 1; + + // Проверяем, пересекаются ли они "в проекции" + // crossPos - это середина нашей стенки. Попадает ли она в диапазон соседки? + if (crossPos > pMin && crossPos < pMax) { + if (p.offset < currentOffset) minLimit = Math.max(minLimit, p.offset); + if (p.offset > currentOffset) maxLimit = Math.min(maxLimit, p.offset); + } } }); - return { min, max }; + return { min: minLimit, max: maxLimit }; }; - // Расчет границ для НОВОЙ линии (T-соединения) + // Поиск границ для НОВОЙ стенки (чтобы обрезать её до T-соединения) const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; @@ -112,11 +93,13 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const pMax = p.max ?? 1; 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); @@ -126,13 +109,16 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; - // -- ACTIONS -- + // --- 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, + axis, + offset, + min, + max, height: config.drawer.height || 80, rounded: false }; @@ -161,7 +147,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // -- MOUSE HANDLER -- + // --- MOUSE HANDLER --- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; const rect = svgRef.current.getBoundingClientRect(); @@ -184,8 +170,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1]; let newOffset = 0; - // Ограничиваем перетаскивание пределами "родительской" зоны - // Для T-соединений это сложнее, но пока ограничим ячейкой (0-1) if (dragging.axis === 'x') { newOffset = (nx - cellX1) / (cellX2 - cellX1); } else { @@ -241,6 +225,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; + // Check Existing Partitions Hover let found = null; const SNAP = 0.05; for (const p of parts) { @@ -255,6 +240,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { + // Calculate Phantom Partition 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; @@ -322,6 +308,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; + // !!! FIX: Проверка y2 if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; @@ -330,21 +317,20 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; - const isSelected = parts.some(p => p.id === selectedPartitionId); + const isAnySelected = parts.some(p => p.id === selectedPartitionId); - // Реальные размеры const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; - // Если перегородок нет - размер по центру + // Label if empty if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; - const textW = Math.max(0, realW - thickness).toFixed(0); - const textD = Math.max(0, realD - thickness).toFixed(0); + 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} ); @@ -354,6 +340,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { elements.push( {isHovered && } + {isAnySelected && mode === 'cells' && } {parts.map(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; @@ -361,21 +348,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let tx, ty; let dist1 = 0, dist2 = 0; - // Используем правильные координаты для поиска соседей - // axis='x' -> offset - это X, center - это Y - // axis='y' -> offset - это Y, center - это X - const neighbors = getNearestNeighbors(p.offset, (pMin + pMax)/2, p.axis, parts); - + // Ищем границы для размеров + const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts); + if (p.axis === 'x') { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax); - // Distances Left/Right - // p.offset is 0..1. neighbor.min is 0..1. - // Distance = (current - neighbor) * width - dist1 = (p.offset - neighbors.min) * realW - thickness; - dist2 = (neighbors.max - p.offset) * realW - thickness; + // Дистанция = (Мой Оффсет - Оффсет Соседа) * Ширину Ячейки - Толщина стенки + dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick; + dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick; tx = px; ty = (ly1 + ly2) / 2; } else { @@ -383,9 +366,8 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { ly1 = py; ly2 = py; lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax); - // Distances Top/Bottom - dist1 = (p.offset - neighbors.min) * realD - thickness; - dist2 = (neighbors.max - p.offset) * realD - thickness; + dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick; + dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick; tx = (lx1 + lx2) / 2; ty = py; } @@ -400,17 +382,17 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { - {/* Размеры (только если есть место) */} - + {/* DIMENSIONS */} + {p.axis === 'x' ? ( <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} ) : ( <> - {Math.max(0, dist1).toFixed(0)} - {Math.max(0, dist2).toFixed(0)} + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} )} @@ -449,51 +431,82 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => {

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

+
- - + +
- + + {/* INFO */}
{mode === 'lines' ? ( -
ЛКМ: ЛинияПКМ: Удалить
+
+ ЛКМ: Линия + ПКМ: Удалить +
) : ( -
ЛКМ в ячейке: СтенкаДраг: Двигать2xЛКМ: Удалить
+
+ ЛКМ в ячейке: Стенка + Драг: Двигать + 2xЛКМ: Удалить +
)}
{/* CANVAS */}
-
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') }} +
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()} + onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} > - + + + + + + {renderCellsAndPartitions()} - {/* Main Grid X */} + + {/* MAIN GRID X */} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} - {/* Main Grid Y */} + + {/* MAIN GRID Y */} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} - {/* Phantoms */} + + {/* PHANTOMS */} {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } @@ -503,7 +516,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {/* SIDEBAR */} {mode === 'cells' && selectedData && (
-

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

+
+

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

+ +
Высота {selectedData.part.height} мм
@@ -513,7 +529,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { 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"/>
- +
Выделите стенку для настройки.
Двойной клик удаляет её.