This commit is contained in:
Халимов Рустам
2025-12-27 23:33:57 +03:00
parent 492585a2be
commit ac00068175
4 changed files with 179 additions and 277 deletions

View File

@@ -19,11 +19,9 @@ const App = () => {
cornerRadius: 4,
});
// ИСПРАВЛЕНИЕ: Добавлено поле subdivisions
const [splits, setSplits] = useState<LayoutSplits>({
x: [],
y: [],
subdivisions: {}
y: []
});
// --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ ---
@@ -31,11 +29,7 @@ const App = () => {
const sharedData = parseShareUrl();
if (sharedData) {
setConfig(sharedData.config);
// Если в старой ссылке нет subdivisions, добавляем пустое
setSplits({
...sharedData.splits,
subdivisions: sharedData.splits.subdivisions || {}
});
setSplits(sharedData.splits);
setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname);
@@ -128,7 +122,7 @@ const App = () => {
<button
onClick={() => {
setStep(1);
setSplits({x: [], y: [], subdivisions: {}});
setSplits({x: [], y: []});
window.history.replaceState({}, '', window.location.pathname);
}}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700"

View File

@@ -1,7 +1,6 @@
import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
// Заменили иконки на Columns/Rows (они есть везде)
import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Minus, Columns, Rows } from 'lucide-react';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -9,54 +8,27 @@ interface Props {
onChange: (splits: LayoutSplits) => void;
}
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
const [mode, setMode] = useState<EditMode>('lines');
// State
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);
// FIX: Кнопка удаления не пропадает под курсором
const [isButtonHovered, setIsButtonHovered] = useState(false);
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
// --- ЗАЩИТА ОТ СБОЕВ ---
// Если splits или массивы не инициализированы, используем пустые значения
const safeX = splits?.x || [];
const safeY = splits?.y || [];
const safeSubdivisions = splits?.subdivisions || {};
const viewBoxW = 1000;
// Защита от деления на ноль
const aspectRatio = (config.drawer.depth || 1) / (config.drawer.width || 1);
const aspectRatio = config.drawer.depth / config.drawer.width;
const viewBoxH = viewBoxW * aspectRatio;
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 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]);
const getSubdivision = (i: number, j: number) => {
return safeSubdivisions[`${i}-${j}`] || { rows: 1, cols: 1 };
};
const updateSubdivision = (i: number, j: number, type: 'rows' | 'cols', delta: number) => {
const key = `${i}-${j}`;
const current = getSubdivision(i, j);
const newVal = Math.max(1, Math.min(10, current[type] + delta));
const newSubdivisions = { ...safeSubdivisions };
if (newVal === 1 && (type === 'rows' ? current.cols : current.rows) === 1) {
delete newSubdivisions[key];
} else {
newSubdivisions[key] = { ...current, [type]: newVal };
}
onChange({ ...splits, subdivisions: newSubdivisions });
};
const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
@@ -65,62 +37,56 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setMousePos({ x: nx, y: ny });
if (mode === 'lines') {
if (dragging) {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
return;
}
if (isButtonHovered) return;
if (dragging) {
const newSplits = { ...splits, x: [...splits.x], y: [...splits.y] };
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
return;
}
setHoveredSplit(null);
if (isButtonHovered) return;
const SNAP = 0.02;
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
setHoveredSplit(null);
if (!closeToX && !closeToY && !closeToEdgeX && !closeToEdgeY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
const minXDist = Math.min(nx, distRight);
const minYDist = Math.min(ny, distBottom);
setPhantomAxis(minXDist < minYDist ? 'y' : 'x');
} else {
setPhantomAxis(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);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
if (!closeToX && !closeToY && !closeToEdgeX && !closeToEdgeY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
const minXDist = Math.min(nx, distRight);
const minYDist = Math.min(ny, distBottom);
setPhantomAxis(minXDist < minYDist ? 'y' : 'x');
} else {
setPhantomAxis(null);
}
};
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
if (mode !== 'lines' || dragging) return;
if (dragging) return;
e.stopPropagation();
setHoveredSplit({ axis, index });
setPhantomAxis(null);
};
const handleMouseDown = (e: React.MouseEvent) => {
if (mode === 'lines') {
if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
} else {
if (e.target === svgRef.current) setSelectedCell(null);
if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
}
};
const removeSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
const newSplits = { ...splits };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits);
setHoveredSplit(null);
@@ -129,54 +95,31 @@ 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">
<div className="flex justify-between items-center mb-4 z-20">
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col">
<div className="flex justify-between items-center mb-4">
<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'); setSelectedCell(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 shadow' : 'text-gray-400 hover:text-gray-200'}`}
>
<Grid size={16} /> Основные границы
</button>
<button
onClick={() => setMode('cells')}
className={`flex items-center gap-2 px-4 py-2 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}
>
<LayoutGrid size={16} /> Деление ячеек
</button>
</div>
<button
onClick={() => onChange({ x: [], y: [], subdivisions: {} })}
onClick={() => onChange({ x: [], y: [] })}
className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
>
<RotateCcw size={14} /> Сбросить всё
<RotateCcw size={14} /> Сбросить сетку
</button>
</div>
<div className="flex flex-col h-full select-none relative">
<div className="flex flex-col h-full select-none">
<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">
<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"/> Инструкция
</div>
{mode === 'lines' ? (
<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>
) : (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-green-400">Клик по ячейке:</b> Выбрать</li>
<li>Используй меню для деления внутри</li>
</ul>
)}
<ul className="space-y-1.5 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]">
@@ -191,12 +134,12 @@ 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 group"
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' ? (dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair') : 'default',
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
maxHeight: '75vh'
}}
>
@@ -216,128 +159,111 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Labels --- */}
{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 width = (x2 - x1) * config.drawer.width;
const depth = (y2 - y1) * config.drawer.depth;
const centerX = ((x1 + x2) / 2) * viewBoxW;
const centerY = ((y1 + y2) / 2) * viewBoxH;
const isSelected = selectedCell?.i === i && selectedCell?.j === j;
const subdiv = getSubdivision(i, j);
const cellWidthSVG = (x2 - x1) * viewBoxW;
const cellHeightSVG = (y2 - y1) * viewBoxH;
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
if (fontSize < 10) return null;
return (
<g key={`cell-${i}-${j}`}>
<rect
x={cellX} y={cellY} width={cellW} height={cellH}
fill={isSelected ? "rgba(59, 130, 246, 0.15)" : "transparent"}
stroke={isSelected ? "#3b82f6" : "transparent"}
strokeWidth="3"
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""}
onClick={(e) => {
if (mode === 'cells') {
e.stopPropagation();
setSelectedCell({ i, j });
}
}}
/>
{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"/>;
})}
{subdiv.rows > 1 && Array.from({ length: subdiv.rows - 1 }).map((_, rI) => {
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}
textAnchor="middle" dominantBaseline="middle"
className="pointer-events-none select-none fill-slate-300 font-bold font-mono text-[24px] opacity-50"
style={{ textShadow: '1px 1px 2px black' }}
>
{((x2 - x1) * config.drawer.width).toFixed(0)}×{((y2 - y1) * config.drawer.depth).toFixed(0)}
</text>
)}
</g>
<text
key={`label-${i}-${j}`}
x={centerX}
y={centerY}
textAnchor="middle"
dominantBaseline="middle"
className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200"
style={{
fontSize: `${fontSize}px`,
textShadow: '1px 1px 3px rgba(0,0,0,0.8)'
}}
>
{width.toFixed(0)} × {depth.toFixed(0)}
</text>
);
});
})}
{/* --- X Lines (Vertical) --- */}
{splits.x.map((x, i) => {
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'x' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
{safeX.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" : ""} />
<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(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<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>
))}
return (
<g
key={`x-${i}`}
onDoubleClick={() => removeSplit('x', i)}
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
>
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="80" className="cursor-col-resize" />
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{(isHovered || isDragging) && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{safeY.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => handleSplitHover(e, '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="#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(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<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>
))}
{/* --- Y Lines (Horizontal) --- */}
{splits.y.map((y, i) => {
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'y' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
{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"
/>
return (
<g
key={`y-${i}`}
onDoubleClick={() => removeSplit('y', i)}
onMouseMove={(e) => handleSplitHover(e, 'y', i)}
>
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="80" className="cursor-row-resize" />
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
{(isHovered || isDragging) && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- Phantom Lines --- */}
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'x' && (
<g className="pointer-events-none">
<line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8" className="opacity-60"/>
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}> <circle r="3" fill="#3b82f6" /> </g>
</g>
)}
{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"
/>
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'y' && (
<g className="pointer-events-none">
<line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8" className="opacity-60"/>
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}> <circle r="3" fill="#3b82f6" /> </g>
</g>
)}
</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()}
>
<div className="flex items-center gap-2">
<Columns 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">
<Rows 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>
</div>
)}
</div>
</div>
</div>

View File

@@ -16,57 +16,41 @@ export const calculateParts = (
for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) {
const rawX = xPoints[i] * config.drawer.width;
const rawY = yPoints[j] * config.drawer.depth;
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const segmentX = xPoints[i] * config.drawer.width;
const segmentY = yPoints[j] * config.drawer.depth;
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
// Получаем настройки деления для этой ячейки
const subdiv = splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
const subCellWidth = rawW / subdiv.cols;
const subCellDepth = rawD / subdiv.rows;
const realWidth = segmentW - config.printerTolerance;
const realDepth = segmentD - config.printerTolerance;
const realX = segmentX + (config.printerTolerance / 2);
const realY = segmentY + (config.printerTolerance / 2);
// Генерируем под-ячейки
for (let r = 0; r < subdiv.rows; r++) {
for (let c = 0; c < subdiv.cols; c++) {
const subX = rawX + (c * subCellWidth);
const subY = rawY + (r * subCellDepth);
const realWidth = subCellWidth - config.printerTolerance;
const realDepth = subCellDepth - config.printerTolerance;
const realX = subX + (config.printerTolerance / 2);
const realY = subY + (config.printerTolerance / 2);
if (realWidth < 5 || realDepth < 5) continue;
// Формируем имя: если ячейка поделена, добавляем индексы (1-1, 1-2...)
let partName = `Ячейка ${i+1}-${j+1}`;
if (subdiv.rows > 1 || subdiv.cols > 1) {
partName += ` (${r+1}-${c+1})`;
}
parts.push({
id: `part-${partCounter}`,
name: partName,
width: realWidth,
depth: realDepth,
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
});
partCounter++;
}
if (realWidth < 5 || realDepth < 5) {
continue;
}
parts.push({
id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}`,
width: realWidth,
depth: realDepth,
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
});
partCounter++;
}
}
return parts;
};
// ... Вспомогательные функции генерации геометрии (без изменений) ...
// ... Вспомогательные функции (createRoundedRectShape, createBinGeometry) остаются ТЕМИ ЖЕ,
// что и в прошлой работающей версии (со скруглениями и Extrude).
// Они не менялись при внедрении subdivisions, но для целостности я их продублирую.
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape();
const x = -width / 2;
@@ -100,9 +84,12 @@ export const createBinGeometry = (
thickness: number,
radius: number = 0
): THREE.BufferGeometry => {
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
depth: thickness, bevelEnabled: false, curveSegments: 16
depth: thickness,
bevelEnabled: false,
curveSegments: 16
});
floorGeo.rotateX(-Math.PI / 2);
@@ -118,7 +105,9 @@ export const createBinGeometry = (
const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: wallHeight, bevelEnabled: false, curveSegments: 16
depth: wallHeight,
bevelEnabled: false,
curveSegments: 16
});
wallGeo.rotateX(-Math.PI / 2);

View File

@@ -11,16 +11,9 @@ export interface AppConfig {
cornerRadius: number;
}
export interface CellSubdivision {
rows: number;
cols: number;
}
export interface LayoutSplits {
x: number[];
y: number[];
// Добавляем обязательное поле, но разрешаем ему быть пустым
subdivisions: Record<string, CellSubdivision>;
}
export interface GeneratedPart {