Layout step
This commit is contained in:
@@ -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<Props> = ({ 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<Props> = ({ config, splits, onChange }) => {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const [mode, setMode] = useState<EditMode>('lines');
|
||||
|
||||
// States
|
||||
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(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<Axis | null>(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<string | null>(null); // Для настройки высоты/скругления
|
||||
|
||||
// Общее состояние перетаскивания
|
||||
const [dragging, setDragging] = useState<DragTarget | null>(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<Props> = ({ 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<Partition>) => {
|
||||
if (!editingCell) return;
|
||||
const key = `${editingCell.i}-${editingCell.j}`;
|
||||
const updatePartition = (key: string, id: string, updates: Partial<Partition>) => {
|
||||
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.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]) {
|
||||
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 (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative">
|
||||
|
||||
@@ -146,17 +296,17 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
</h2>
|
||||
|
||||
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
|
||||
<button onClick={() => { setMode('lines'); setEditingCell(null); }}
|
||||
className={`px-4 py-2 rounded-md text-xs font-bold ${mode === 'lines' ? 'bg-primary text-white' : 'text-gray-400'}`}>
|
||||
Границы
|
||||
<button onClick={() => { setMode('lines'); setSelectedPartitionId(null); }}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white' : 'text-gray-400 hover:text-gray-200'}`}>
|
||||
<Move size={14}/> Границы
|
||||
</button>
|
||||
<button onClick={() => setMode('cells')}
|
||||
className={`px-4 py-2 rounded-md text-xs font-bold ${mode === 'cells' ? 'bg-primary text-white' : 'text-gray-400'}`}>
|
||||
Внутри ячеек
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white' : 'text-gray-400 hover:text-gray-200'}`}>
|
||||
<Grid size={14}/> Внутри ячеек
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1 text-xs text-red-400 border border-slate-700 rounded">
|
||||
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1 text-xs text-red-400 border border-slate-700 rounded hover:bg-slate-800">
|
||||
Сброс
|
||||
</button>
|
||||
</div>
|
||||
@@ -164,11 +314,17 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
<div className="flex flex-col h-full select-none relative">
|
||||
<div className="flex-1 bg-slate-800/30 rounded-lg p-6 flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50">
|
||||
|
||||
<div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[200px] pointer-events-none">
|
||||
{/* Instruction Overlay */}
|
||||
<div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[220px] pointer-events-none">
|
||||
<div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
|
||||
<MousePointer2 size={14} className="text-primary"/> {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
|
||||
<MousePointer2 size={14} className="text-primary"/>
|
||||
{mode === 'lines' ? 'Режим: Основные границы' : 'Режим: Стенки в ячейках'}
|
||||
</div>
|
||||
<p className="text-[10px] text-gray-400">{mode === 'lines' ? 'Клик: создать. Драг: двигать.' : 'Кликни по ячейке для настройки.'}</p>
|
||||
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
|
||||
<li><b className="text-blue-400">Клик:</b> Создать линию</li>
|
||||
<li><b className="text-orange-400">Драг:</b> Переместить</li>
|
||||
<li><b className="text-red-400">Двойной клик:</b> Удалить</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]">
|
||||
@@ -181,10 +337,10 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
</div>
|
||||
|
||||
<div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
|
||||
style={{ width: '100%', maxWidth: '900px', aspectRatio: `${1/aspectRatio}`, cursor: mode === 'lines' ? 'crosshair' : 'default', maxHeight: '75vh' }}
|
||||
style={{ width: '100%', maxWidth: '900px', aspectRatio: `${1/aspectRatio}`, cursor: dragging ? 'grabbing' : 'crosshair', maxHeight: '75vh' }}
|
||||
>
|
||||
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none"
|
||||
onMouseMove={handleGlobalMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
|
||||
onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<defs>
|
||||
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
|
||||
@@ -193,131 +349,162 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#grid)" />
|
||||
|
||||
{/* --- ИСПРАВЛЕННЫЙ БЛОК ОТРИСОВКИ ЯЧЕЕК --- */}
|
||||
{/* --- РЕНДЕР ЯЧЕЕК И ПЕРЕГОРОДОК --- */}
|
||||
{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 (
|
||||
<g key={`cell-${i}-${j}`}>
|
||||
<rect x={cellX} y={cellY} width={cellW} height={cellH}
|
||||
fill={isSelected ? "rgba(59, 130, 246, 0.2)" : "transparent"}
|
||||
stroke={isSelected ? "#3b82f6" : "transparent"} strokeWidth="4"
|
||||
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5" : ""}
|
||||
onClick={(e) => { if (mode === 'cells') { e.stopPropagation(); setEditingCell({ i, j }); } }}
|
||||
/>
|
||||
<g key={`cell-${key}`}>
|
||||
{/* Подсветка ячейки при наведении в режиме Cells */}
|
||||
{isHovered && (
|
||||
<rect x={cellX} y={cellY} width={cellW} height={cellH} fill="rgba(59, 130, 246, 0.05)" stroke="#3b82f6" strokeWidth="2" strokeDasharray="4,4" className="pointer-events-none"/>
|
||||
)}
|
||||
|
||||
{/* Существующие перегородки */}
|
||||
{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 <line key={p.id} x1={px} y1={cellY} x2={px} y2={cellY + cellH} stroke="#a855f7" strokeWidth="4" className="pointer-events-none"/>;
|
||||
lx1 = px; ly1 = cellY; lx2 = px; ly2 = cellY + cellH;
|
||||
} else {
|
||||
const py = cellY + (cellH * p.offset);
|
||||
return <line key={p.id} x1={cellX} y1={py} x2={cellX + cellW} y2={py} stroke="#a855f7" strokeWidth="4" className="pointer-events-none"/>;
|
||||
lx1 = cellX; ly1 = py; lx2 = cellX + cellW; ly2 = py;
|
||||
}
|
||||
|
||||
return (
|
||||
<g key={p.id}
|
||||
onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}
|
||||
className={mode === 'cells' ? "cursor-grab" : ""}
|
||||
>
|
||||
{/* Невидимая зона захвата */}
|
||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="40" />
|
||||
{/* Видимая линия */}
|
||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={strokeColor} strokeWidth={isSelected ? 6 : 4} strokeLinecap="round" />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Фантомная перегородка (только если наведена мышь на эту ячейку и нет перегородки под курсором) */}
|
||||
{isHovered && phantomPartition && !hoveredPartition && (
|
||||
<g className="pointer-events-none opacity-50">
|
||||
{phantomPartition.axis === 'x' ? (
|
||||
<line
|
||||
x1={cellX + (cellW * phantomPartition.offset)} y1={cellY}
|
||||
x2={cellX + (cellW * phantomPartition.offset)} y2={cellY + cellH}
|
||||
stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8"
|
||||
/>
|
||||
) : (
|
||||
<line
|
||||
x1={cellX} y1={cellY + (cellH * phantomPartition.offset)}
|
||||
x2={cellX + cellW} y2={cellY + (cellH * phantomPartition.offset)}
|
||||
stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8"
|
||||
/>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
});
|
||||
})}
|
||||
|
||||
{/* GRID LINES X */}
|
||||
{safeX.map((x, i) => (
|
||||
<g key={`x-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'x', index: i }); setPhantomAxis(null); } }}>
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
|
||||
{mode === 'lines' && hoveredSplit?.axis === 'x' && hoveredSplit.index === i && (
|
||||
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}>
|
||||
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
|
||||
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
))}
|
||||
{/* --- MAIN GRID LINES (Отрисовываем поверх всего) --- */}
|
||||
{safeX.map((x, i) => {
|
||||
const isHovered = hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i;
|
||||
return (
|
||||
<g key={`x-${i}`}
|
||||
onMouseMove={(e) => handleMainSplitHover(e, 'x', i)}
|
||||
onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}
|
||||
>
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* GRID LINES Y */}
|
||||
{safeY.map((y, i) => (
|
||||
<g key={`y-${i}`} onMouseMove={(e) => { if (mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredSplit({ axis: 'y', index: i }); setPhantomAxis(null); } }}>
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-row-resize" : ""} />
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
|
||||
{mode === 'lines' && hoveredSplit?.axis === 'y' && hoveredSplit.index === i && (
|
||||
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}>
|
||||
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
|
||||
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
))}
|
||||
{safeY.map((y, i) => {
|
||||
const isHovered = hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i;
|
||||
return (
|
||||
<g key={`y-${i}`}
|
||||
onMouseMove={(e) => handleMainSplitHover(e, 'y', i)}
|
||||
onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}
|
||||
>
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-row-resize" : ""} />
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
||||
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
||||
{/* Фантомная линия (для Main Grid) */}
|
||||
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
||||
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- EDITOR PANEL --- */}
|
||||
{mode === 'cells' && editingCell && (
|
||||
<div className="absolute top-0 right-0 bottom-0 w-80 bg-slate-900 border-l border-slate-700 p-4 shadow-2xl flex flex-col z-30">
|
||||
{/* --- SIDEBAR FOR SELECTED PARTITION SETTINGS --- */}
|
||||
{mode === 'cells' && selectedData && (
|
||||
<div className="absolute top-0 right-0 bottom-0 w-80 bg-slate-900 border-l border-slate-700 p-4 shadow-2xl flex flex-col z-30 animate-in slide-in-from-right-10">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-sm font-bold text-white uppercase tracking-wider">Редактор ячейки</h3>
|
||||
<button onClick={() => setEditingCell(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
|
||||
<h3 className="text-lg font-bold text-white flex items-center gap-2">
|
||||
<Settings2 size={18} className="text-primary"/> Настройки стенки
|
||||
</h3>
|
||||
<button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 mb-6">
|
||||
<button onClick={() => addPartition('x')} className="flex-1 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-white text-xs py-2 px-3 rounded flex items-center justify-center gap-2">
|
||||
<Plus size={14} className="text-green-400"/> + Верт.
|
||||
</button>
|
||||
<button onClick={() => addPartition('y')} className="flex-1 bg-slate-800 hover:bg-slate-700 border border-slate-600 text-white text-xs py-2 px-3 rounded flex items-center justify-center gap-2">
|
||||
<Plus size={14} className="text-green-400"/> + Гориз.
|
||||
</button>
|
||||
</div>
|
||||
<div className="bg-slate-800 p-4 rounded border border-slate-700">
|
||||
<div className="mb-4">
|
||||
<span className="text-xs font-bold text-purple-300 block mb-2">
|
||||
Выбрана: {selectedData.part.axis === 'x' ? 'Вертикальная' : 'Горизонтальная'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto space-y-4 pr-1">
|
||||
{(safePartitions[`${editingCell.i}-${editingCell.j}`] || []).map((p, idx) => (
|
||||
<div key={p.id} className="bg-slate-800 p-3 rounded border border-slate-700">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-xs font-bold text-purple-300">
|
||||
Стенка #{idx+1} ({p.axis === 'x' ? 'Верт' : 'Гориз'})
|
||||
</span>
|
||||
<button onClick={() => removePartition(p.id)} className="text-red-400 hover:text-red-300"><Trash2 size={14}/></button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<div className="flex justify-between text-[10px] text-gray-400 mb-1">
|
||||
<span>Позиция</span> <span>{(p.offset * 100).toFixed(0)}%</span>
|
||||
</div>
|
||||
<input type="range" min="0.1" max="0.9" step="0.05" value={p.offset}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex justify-between text-[10px] text-gray-400 mb-1">
|
||||
<span>Высота</span> <span>{p.height} мм</span>
|
||||
</div>
|
||||
<input type="range" min="5" max={config.drawer.height || 100} step="1" value={p.height}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input type="checkbox" id={`rounded-${p.id}`} checked={p.rounded}
|
||||
onChange={(e) => updatePartition(p.id, { rounded: e.target.checked })}
|
||||
className="rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0"
|
||||
/>
|
||||
<label htmlFor={`rounded-${p.id}`} className="text-xs text-gray-300">Скругление</label>
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
{/* Высота */}
|
||||
<div>
|
||||
<div className="flex justify-between text-xs text-gray-300 mb-2">
|
||||
<span>Высота</span>
|
||||
<span className="font-mono bg-slate-900 px-1 rounded">{selectedData.part.height} мм</span>
|
||||
</div>
|
||||
<input type="range" min="5" max={config.drawer.height || 100} step="1" value={selectedData.part.height}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Скругление */}
|
||||
<div className="flex items-center justify-between p-2 bg-slate-900 rounded border border-slate-700">
|
||||
<label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label>
|
||||
<input type="checkbox" id="rounded-check" checked={selectedData.part.rounded}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Кнопка удаления */}
|
||||
<button
|
||||
onClick={() => removePartition(selectedData.key, selectedData.part.id)}
|
||||
className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 rounded text-xs flex items-center justify-center gap-2 transition-colors"
|
||||
>
|
||||
<Trash2 size={14}/> Удалить стенку
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto text-[10px] text-gray-500 text-center">
|
||||
Выделите другую стенку или нажмите в пустое место для создания новой.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user