This commit is contained in:
Халимов Рустам
2025-12-27 23:10:24 +03:00
parent 6c6c859a3b
commit 19754baaae
3 changed files with 37 additions and 52 deletions

View File

@@ -1,6 +1,7 @@
import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Minus, SplitSquareVertical, SplitSquareHorizontal } from 'lucide-react';
// ИСПРАВЛЕНИЕ: Используем безопасные иконки
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Minus, RectangleHorizontal, RectangleVertical } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -14,17 +15,12 @@ type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
// Режимы: 'lines' (двигать линии) или 'cells' (дробить ячейки)
const [mode, setMode] = useState<EditMode>('lines');
// Состояния для линий
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 [isButtonHovered, setIsButtonHovered] = useState(false);
// Состояние для ячеек
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
const viewBoxW = 1000;
@@ -34,9 +30,11 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]);
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
// --- Логика разделения ячеек ---
// ИСПРАВЛЕНИЕ: Безопасное получение subdivisions (если вдруг undefined)
const safeSubdivisions = splits.subdivisions || {};
const getSubdivision = (i: number, j: number) => {
return splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
return safeSubdivisions[`${i}-${j}`] || { rows: 1, cols: 1 };
};
const updateSubdivision = (i: number, j: number, type: 'rows' | 'cols', delta: number) => {
@@ -44,9 +42,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const current = getSubdivision(i, j);
const newVal = Math.max(1, Math.min(10, current[type] + delta));
const newSubdivisions = { ...splits.subdivisions };
const newSubdivisions = { ...safeSubdivisions };
// Если вернулись к 1x1, удаляем запись для чистоты
if (newVal === 1 && (type === 'rows' ? current.cols : current.rows) === 1) {
delete newSubdivisions[key];
} else {
@@ -56,7 +53,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onChange({ ...splits, subdivisions: newSubdivisions });
};
// --- Обработчики мыши ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
@@ -78,7 +74,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setHoveredSplit(null);
// Фантомная линия (только если не рядом с существующей)
const SNAP = 0.02;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP);
@@ -116,7 +111,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
} else {
// В режиме ячеек сбрасываем выделение при клике в пустоту
if (e.target === svgRef.current) setSelectedCell(null);
}
};
@@ -132,8 +126,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative">
{/* --- HEADER CONTROLS --- */}
<div className="flex justify-between items-center mb-4 z-20">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
<Grid size={24} /> 2. Редактор макета
@@ -165,7 +157,6 @@ 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">
{/* 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-[200px] 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' ? 'Границы' : 'Ячейки'}
@@ -184,7 +175,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
)}
</div>
{/* Rulers */}
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]">
<span className="text-xs text-slate-500 font-mono">0</span>
<span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
@@ -196,7 +186,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
</div>
{/* SVG Container */}
<div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group"
style={{
@@ -223,7 +212,6 @@ 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) => {
@@ -237,7 +225,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return (
<g key={`cell-${i}-${j}`}>
{/* Прямоугольник ячейки */}
<rect
x={cellX} y={cellY} width={cellW} height={cellH}
fill={isSelected ? "rgba(59, 130, 246, 0.15)" : "transparent"}
@@ -251,8 +238,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}
}}
/>
{/* Внутренние пунктирные линии */}
{subdiv.cols > 1 && Array.from({ length: subdiv.cols - 1 }).map((_, cI) => {
const splitX = cellX + (cellW / subdiv.cols) * (cI + 1);
return <line key={`sc-${cI}`} x1={splitX} y1={cellY} x2={splitX} y2={cellY + cellH} stroke="#3b82f6" strokeWidth="2" strokeDasharray="5,5" className="pointer-events-none opacity-70"/>;
@@ -261,8 +246,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const splitY = cellY + (cellH / subdiv.rows) * (rI + 1);
return <line key={`sr-${rI}`} x1={cellX} y1={splitY} x2={cellX + cellW} y2={splitY} stroke="#3b82f6" strokeWidth="2" strokeDasharray="5,5" className="pointer-events-none opacity-70"/>;
})}
{/* РАЗМЕРЫ: показываем только если ячейка не разбита */}
{subdiv.rows === 1 && subdiv.cols === 1 && (
<text
x={cellX + cellW/2} y={cellY + cellH/2}
@@ -278,7 +261,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
});
})}
{/* --- ЛИНИИ СЕТКИ (Поверх ячеек) --- */}
{splits.x.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => handleSplitHover(e, 'x', i)}>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
@@ -287,7 +269,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
<circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
@@ -302,56 +284,54 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="14" fill="#ef4444" className="cursor-pointer"/>
<circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g>
)}
</g>
))}
{/* Фантомная линия */}
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis && (
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && (
<line
x1={phantomAxis === 'x' ? mousePos.x * viewBoxW : 0}
y1={phantomAxis === 'x' ? 0 : mousePos.y * viewBoxH}
x2={phantomAxis === 'x' ? mousePos.x * viewBoxW : viewBoxW}
y2={phantomAxis === 'x' ? viewBoxH : mousePos.y * viewBoxH}
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"
/>
)}
</svg>
{/* --- КОНТРОЛЫ ЯЧЕЙКИ (Поверх SVG) --- */}
{/* --- МЕНЮ ДЛЯ ЯЧЕЙКИ (С ИСПРАВЛЕННЫМИ ИКОНКАМИ) --- */}
{mode === 'cells' && selectedCell && (
<div
className="absolute flex flex-col gap-2 p-2 bg-slate-800/90 backdrop-blur rounded-lg border border-blue-500 shadow-2xl transform -translate-x-1/2 -translate-y-1/2"
style={{
// Позиционируем прямо по центру выбранной ячейки
left: `${((sortedX[selectedCell.i] + sortedX[selectedCell.i+1])/2) * 100}%`,
top: `${((sortedY[selectedCell.j] + sortedY[selectedCell.j+1])/2) * 100}%`,
}}
onMouseDown={(e) => e.stopPropagation()} // Чтобы клик не снимал выделение
onMouseDown={(e) => e.stopPropagation()}
>
{/* Ряды (Горизонтально) */}
{/* Ряды */}
<div className="flex items-center gap-2">
<SplitSquareVertical size={16} className="text-blue-400" />
<RectangleVertical size={16} className="text-blue-400" />
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', -1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Minus size={12}/></button>
<span className="font-mono font-bold w-4 text-center">{getSubdivision(selectedCell.i, selectedCell.j).cols}</span>
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', 1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Plus size={12}/></button>
</div>
{/* Колонки (Вертикально) */}
{/* Колонки */}
<div className="flex items-center gap-2">
<SplitSquareHorizontal size={16} className="text-blue-400" />
<RectangleHorizontal size={16} className="text-blue-400" />
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', -1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Minus size={12}/></button>
<span className="font-mono font-bold w-4 text-center">{getSubdivision(selectedCell.i, selectedCell.j).rows}</span>
<button onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', 1)} className="w-6 h-6 bg-slate-700 hover:bg-slate-600 rounded flex items-center justify-center"><Plus size={12}/></button>
</div>
<button
onClick={() => setSelectedCell(null)}
className="mt-1 text-[10px] text-gray-400 hover:text-white text-center bg-slate-700/50 rounded py-1"
>
<button onClick={() => setSelectedCell(null)} className="mt-1 text-[10px] text-gray-400 hover:text-white text-center bg-slate-700/50 rounded py-1">
Готово
</button>
</div>