Fix layout

This commit is contained in:
Халимов Рустам
2026-01-10 17:31:22 +03:00
parent cf09961807
commit 5e11d7a194

View File

@@ -12,25 +12,23 @@ type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
// DEBUG LOGGING
console.log("LayoutStep Render. Config:", config, "Splits:", splits);
// Логируем рендер для отладки
console.log("LayoutStep Render");
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 [isButtonHovered, setIsButtonHovered] = useState(false);
// Editor State
const [editingCell, setEditingCell] = useState<{ i: number, j: number } | null>(null);
// DATA SAFETY CHECKS
if (!config || !config.drawer) {
console.error("LayoutStep: Config is missing!");
return <div className="text-red-500">Config Error: Missing configuration</div>;
}
// --- ЗАЩИТА ДАННЫХ ---
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {};
@@ -42,23 +40,20 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const aspectRatio = depth / width;
const viewBoxH = viewBoxW * aspectRatio;
// LOG CALCULATIONS
if (isNaN(viewBoxH) || !isFinite(viewBoxH)) {
console.error("LayoutStep: Invalid Dimensions", { width, depth, aspectRatio });
return <div className="text-red-500">Error: Invalid Dimensions ({width}x{depth})</div>;
}
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// Handlers
// --- ЛОГИКА ---
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: 0.5, height: config.drawer.height || 80, rounded: false
axis,
offset: 0.5,
height: config.drawer.height || 80,
rounded: false
};
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
};
@@ -78,6 +73,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onChange({ ...splits, partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) } });
};
// --- MOUSE HANDLERS ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
@@ -85,6 +81,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
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') {
@@ -97,15 +94,18 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}
if (isButtonHovered) return;
setHoveredSplit(null);
const SNAP = 0.02;
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); }
} else {
setPhantomAxis(null);
}
}
}
};
@@ -138,15 +138,27 @@ 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 */}
<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. Макет
</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>
<button onClick={() => setMode('cells')} className={`px-4 py-2 rounded-md text-xs font-bold ${mode === 'cells' ? 'bg-primary text-white' : 'text-gray-400'}`}>Ячейки</button>
<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>
<button onClick={() => setMode('cells')}
className={`px-4 py-2 rounded-md text-xs font-bold ${mode === 'cells' ? 'bg-primary text-white' : 'text-gray-400'}`}>
Внутри ячеек
</button>
</div>
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1 text-xs text-red-400 border border-slate-700 rounded">Сброс</button>
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1 text-xs text-red-400 border border-slate-700 rounded">
Сброс
</button>
</div>
<div className="flex flex-col h-full select-none relative">
@@ -154,7 +166,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<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' ? 'Границы' : 'Ячейки'}
<MousePointer2 size={14} className="text-primary"/> {mode === 'lines' ? 'Режим: Границы' : 'Режим: Ячейки'}
</div>
<p className="text-[10px] text-gray-400">{mode === 'lines' ? 'Клик: создать. Драг: двигать.' : 'Кликни по ячейке для настройки.'}</p>
</div>
@@ -181,11 +193,17 @@ 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 cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH;
const y2 = sortedY[j + 1]; // <--- ВОТ ЭТОЙ СТРОКИ НЕ ХВАТАЛО!
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}`] || [];
@@ -211,6 +229,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
});
})}
{/* 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" : ""} />
@@ -224,6 +243,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</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" : ""} />
@@ -243,34 +263,56 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</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">
<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>
</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>
<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="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>
<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 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 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"/>
<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>