Try repeat

This commit is contained in:
Халимов Рустам
2025-12-27 23:46:13 +03:00
parent ac00068175
commit 929e071ea7
4 changed files with 299 additions and 181 deletions
+9 -3
View File
@@ -19,9 +19,11 @@ const App = () => {
cornerRadius: 4, cornerRadius: 4,
}); });
// ВАЖНО: Инициализируем subdivisions пустым объектом
const [splits, setSplits] = useState<LayoutSplits>({ const [splits, setSplits] = useState<LayoutSplits>({
x: [], x: [],
y: [] y: [],
subdivisions: {}
}); });
// --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ --- // --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ ---
@@ -29,7 +31,11 @@ const App = () => {
const sharedData = parseShareUrl(); const sharedData = parseShareUrl();
if (sharedData) { if (sharedData) {
setConfig(sharedData.config); setConfig(sharedData.config);
setSplits(sharedData.splits); // При восстановлении тоже гарантируем наличие subdivisions
setSplits({
...sharedData.splits,
subdivisions: sharedData.splits.subdivisions || {}
});
setStep(3); setStep(3);
setIsLoadedFromUrl(true); setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname); window.history.replaceState({}, '', window.location.pathname);
@@ -122,7 +128,7 @@ const App = () => {
<button <button
onClick={() => { onClick={() => {
setStep(1); setStep(1);
setSplits({x: [], y: []}); setSplits({x: [], y: [], subdivisions: {}}); // Сброс всего
window.history.replaceState({}, '', window.location.pathname); 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" 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"
+188 -101
View File
@@ -1,6 +1,6 @@
import React, { useRef, useState, useMemo } from 'react'; import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types'; import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react'; import { Grid, MousePointer2, Trash2, RotateCcw, LayoutGrid, X, Plus, Minus, Move, Check } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -8,27 +8,56 @@ interface Props {
onChange: (splits: LayoutSplits) => void; onChange: (splits: LayoutSplits) => void;
} }
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y'; type Axis = 'x' | 'y';
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => { export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null); const svgRef = useRef<SVGSVGElement>(null);
// State // Режимы: двигать линии или настраивать ячейки
const [mode, setMode] = useState<EditMode>('lines');
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null);
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null); const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null); const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);
// FIX: Кнопка удаления не пропадает под курсором
const [isButtonHovered, setIsButtonHovered] = useState(false); const [isButtonHovered, setIsButtonHovered] = useState(false);
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
// ЗАЩИТА: Гарантируем, что массивы и объекты существуют
const safeX = splits?.x || [];
const safeY = splits?.y || [];
const safeSubdivisions = splits?.subdivisions || {};
const viewBoxW = 1000; const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width; const aspectRatio = (config.drawer.depth || 1) / (config.drawer.width || 1);
const viewBoxH = viewBoxW * aspectRatio; const viewBoxH = viewBoxW * aspectRatio;
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]); const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- Функции для ячеек ---
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) => { const handleGlobalMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return; if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect(); const rect = svgRef.current.getBoundingClientRect();
@@ -37,8 +66,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setMousePos({ x: nx, y: ny }); setMousePos({ x: nx, y: ny });
if (mode === 'lines') {
if (dragging) { if (dragging) {
const newSplits = { ...splits, x: [...splits.x], y: [...splits.y] }; const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
const val = dragging.axis === 'x' ? nx : ny; const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val; newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits); onChange(newSplits);
@@ -50,8 +80,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setHoveredSplit(null); setHoveredSplit(null);
const SNAP = 0.02; const SNAP = 0.02;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP); const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP); const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP || nx > (1 - SNAP); const closeToEdgeX = nx < SNAP || nx > (1 - SNAP);
const closeToEdgeY = ny < SNAP || ny > (1 - SNAP); const closeToEdgeY = ny < SNAP || ny > (1 - SNAP);
@@ -63,30 +93,35 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
} else { } else {
setPhantomAxis(null); setPhantomAxis(null);
} }
}
}; };
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => { const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
if (dragging) return; if (mode !== 'lines' || dragging) return;
e.stopPropagation(); e.stopPropagation();
setHoveredSplit({ axis, index }); setHoveredSplit({ axis, index });
setPhantomAxis(null); setPhantomAxis(null);
}; };
const handleMouseDown = (e: React.MouseEvent) => { const handleMouseDown = (e: React.MouseEvent) => {
if (mode === 'lines') {
if (hoveredSplit && !isButtonHovered) { if (hoveredSplit && !isButtonHovered) {
if (e.button === 0) setDragging(hoveredSplit); if (e.button === 0) setDragging(hoveredSplit);
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index); else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (phantomAxis && !isButtonHovered) { } else if (phantomAxis && !isButtonHovered) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y; const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits }; const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[phantomAxis] = [...newSplits[phantomAxis], val]; newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
onChange(newSplits); onChange(newSplits);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
} }
} else {
if (e.target === svgRef.current) setSelectedCell(null);
}
}; };
const removeSplit = (axis: Axis, index: number) => { const removeSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits }; const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index); newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits); onChange(newSplits);
setHoveredSplit(null); setHoveredSplit(null);
@@ -95,33 +130,62 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}; };
return ( return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col"> <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">
{/* 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"> <h2 className="text-xl font-bold flex items-center gap-2 text-primary">
<Grid size={24} /> 2. Редактор макета <Grid size={24} /> 2. Редактор макета
</h2> </h2>
{/* Toggle Mode */}
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
<button <button
onClick={() => onChange({ x: [], y: [] })} onClick={() => { setMode('lines'); setSelectedCell(null); }}
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" 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'}`}
> >
<RotateCcw size={14} /> Сбросить сетку <Move size={14} /> Линии (Границы)
</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={14} /> Ячейки (Стенки)
</button> </button>
</div> </div>
<div className="flex flex-col h-full select-none"> <button
onClick={() => onChange({ x: [], y: [], subdivisions: {} })}
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} /> Сбросить
</button>
</div>
<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="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="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"> <div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
<MousePointer2 size={14} className="text-primary"/> Инструкция <MousePointer2 size={14} className="text-primary"/>
{mode === 'lines' ? 'Режим: Линии' : 'Режим: Ячейки'}
</div> </div>
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight"> {mode === 'lines' ? (
<li><b className="text-blue-400">Клик у края:</b> Новая линия</li> <ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-orange-400">Перетаскивание:</b> Изменить размер</li> <li><b className="text-blue-400">Клик:</b> Новая линия</li>
<li><b className="text-red-400">Двойной клик/ПКМ:</b> Удалить</li> <li><b className="text-orange-400">Драг:</b> Двигать линию</li>
<li><b className="text-red-400">ПКМ:</b> Удалить линию</li>
</ul> </ul>
) : (
<ul className="space-y-1 text-[10px] text-gray-400 leading-tight">
<li><b className="text-green-400">Клик по ячейке:</b> Настройка</li>
<li>Добавляй ряды и колонки внутри</li>
</ul>
)}
</div> </div>
{/* Rulers */}
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]"> <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">0</span>
<span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span> <span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
@@ -134,12 +198,12 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
<div <div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden" className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden group"
style={{ style={{
width: '100%', width: '100%',
maxWidth: '900px', maxWidth: '900px',
aspectRatio: `${1/aspectRatio}`, aspectRatio: `${1/aspectRatio}`,
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair', cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair') : 'default',
maxHeight: '75vh' maxHeight: '75vh'
}} }}
> >
@@ -159,111 +223,134 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs> </defs>
<rect width="100%" height="100%" fill="url(#grid)" /> <rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Labels --- */} {/* --- Рендеринг ячеек --- */}
{sortedX.slice(0, -1).map((x1, i) => { {sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1]; const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => { return sortedY.slice(0, -1).map((y1, j) => {
const y2 = sortedY[j + 1]; const cellX = x1 * viewBoxW;
const width = (x2 - x1) * config.drawer.width; const cellY = y1 * viewBoxH;
const depth = (y2 - y1) * config.drawer.depth; const cellW = (x2 - x1) * viewBoxW;
const centerX = ((x1 + x2) / 2) * viewBoxW; const cellH = (y2 - y1) * viewBoxH;
const centerY = ((y1 + y2) / 2) * viewBoxH;
const cellWidthSVG = (x2 - x1) * viewBoxW; const isSelected = selectedCell?.i === i && selectedCell?.j === j;
const cellHeightSVG = (y2 - y1) * viewBoxH; const subdiv = getSubdivision(i, j);
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
if (fontSize < 10) return null;
return ( return (
<text <g key={`cell-${i}-${j}`}>
key={`label-${i}-${j}`} {/* Прямоугольник ячейки */}
x={centerX} <rect
y={centerY} x={cellX} y={cellY} width={cellW} height={cellH}
textAnchor="middle" fill={isSelected ? "rgba(59, 130, 246, 0.15)" : "transparent"}
dominantBaseline="middle" stroke={isSelected ? "#3b82f6" : "transparent"}
className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200" strokeWidth="4"
style={{ className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-all" : ""}
fontSize: `${fontSize}px`, onClick={(e) => {
textShadow: '1px 1px 3px rgba(0,0,0,0.8)' 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-60"/>;
})}
{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-60"/>;
})}
{/* Размеры (если не разбито) */}
{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-40"
style={{ textShadow: '1px 1px 2px black' }}
> >
{width.toFixed(0)} × {depth.toFixed(0)} {((x2 - x1) * config.drawer.width).toFixed(0)}×{((y2 - y1) * config.drawer.depth).toFixed(0)}
</text> </text>
)}
</g>
); );
}); });
})} })}
{/* --- X Lines (Vertical) --- */} {/* --- Линии границ (X) --- */}
{splits.x.map((x, i) => { {safeX.map((x, i) => (
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i; <g key={`x-${i}`} onMouseMove={(e) => handleSplitHover(e, 'x', i)}>
const isDragging = dragging?.axis === 'x' && dragging.index === i; <line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-col-resize" : ""} />
const color = isHovered || isDragging ? '#f59e0b' : '#64748b'; <line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
const width = isHovered || isDragging ? 8 : 4; {mode === 'lines' && hoveredSplit?.axis === 'x' && hoveredSplit.index === i && (
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); }} <g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
> >
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/> <circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/> <Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g> </g>
)} )}
</g> </g>
); ))}
})}
{/* --- Y Lines (Horizontal) --- */} {/* --- Линии границ (Y) --- */}
{splits.y.map((y, i) => { {safeY.map((y, i) => (
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i; <g key={`y-${i}`} onMouseMove={(e) => handleSplitHover(e, 'y', i)}>
const isDragging = dragging?.axis === 'y' && dragging.index === i; <line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="60" className={mode === 'lines' ? "cursor-row-resize" : ""} />
const color = isHovered || isDragging ? '#f59e0b' : '#64748b'; <line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="#f59e0b" strokeWidth="4" className="pointer-events-none" />
const width = isHovered || isDragging ? 8 : 4; {mode === 'lines' && hoveredSplit?.axis === 'y' && hoveredSplit.index === i && (
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); }} <g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)} onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
> >
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/> <circle r="14" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/> <Trash2 size={14} color="white" x={-7} y={-7} className="pointer-events-none"/>
</g> </g>
)} )}
</g> </g>
); ))}
})}
{/* --- Phantom Lines --- */} {/* --- Фантомные линии --- */}
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'x' && ( {mode === 'lines' && !hoveredSplit && !dragging && 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="8,8" className="pointer-events-none opacity-50"/>
<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>
)} )}
{!hoveredSplit && !dragging && !isButtonHovered && phantomAxis === 'y' && ( {mode === 'lines' && !hoveredSplit && !dragging && 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="8,8" className="pointer-events-none opacity-50"/>
<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> </svg>
{/* --- Панель управления выбранной ячейкой (HTML) --- */}
{mode === 'cells' && selectedCell && (
<div
className="absolute flex flex-col gap-2 p-2 bg-slate-800/95 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 text-xs">
<div className="w-4 flex justify-center text-blue-400 font-bold">X</div>
<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 text-xs">
<div className="w-4 flex justify-center text-blue-400 font-bold">Y</div>
<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 flex items-center justify-center gap-1">
<Check size={10} /> Готово
</button>
</div>
)}
</div> </div>
</div> </div>
</div> </div>
+41 -24
View File
@@ -8,31 +8,54 @@ export const calculateParts = (
): GeneratedPart[] => { ): GeneratedPart[] => {
const parts: GeneratedPart[] = []; const parts: GeneratedPart[] = [];
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1]; // Безопасное чтение данных
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1]; const safeX = splits?.x || [];
const safeY = splits?.y || [];
const safeSub = splits?.subdivisions || {};
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
let partCounter = 1; let partCounter = 1;
for (let i = 0; i < xPoints.length - 1; i++) { for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) { for (let j = 0; j < yPoints.length - 1; j++) {
const segmentX = xPoints[i] * config.drawer.width; const rawX = xPoints[i] * config.drawer.width;
const segmentY = yPoints[j] * config.drawer.depth; const rawY = yPoints[j] * config.drawer.depth;
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const realWidth = segmentW - config.printerTolerance; // Получаем настройки деления
const realDepth = segmentD - config.printerTolerance; const subdiv = safeSub[`${i}-${j}`] || { rows: 1, cols: 1 };
const realX = segmentX + (config.printerTolerance / 2);
const realY = segmentY + (config.printerTolerance / 2);
if (realWidth < 5 || realDepth < 5) { // Размеры под-ячейки
continue; const subCellWidth = rawW / subdiv.cols;
const subCellDepth = rawD / subdiv.rows;
// Генерируем под-ячейки
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;
// Имя: если деление, добавляем суффикс
let partName = `Ячейка ${i+1}-${j+1}`;
if (subdiv.rows > 1 || subdiv.cols > 1) {
partName += ` (${r+1}-${c+1})`;
} }
parts.push({ parts.push({
id: `part-${partCounter}`, id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}`, name: partName,
width: realWidth, width: realWidth,
depth: realDepth, depth: realDepth,
height: config.drawer.height, height: config.drawer.height,
@@ -43,14 +66,13 @@ export const calculateParts = (
partCounter++; partCounter++;
} }
} }
}
}
return parts; return parts;
}; };
// ... Вспомогательные функции (createRoundedRectShape, createBinGeometry) остаются ТЕМИ ЖЕ, // ... Остальной код (createRoundedRectShape, createBinGeometry) как в работающей версии ...
// что и в прошлой работающей версии (со скруглениями и Extrude).
// Они не менялись при внедрении subdivisions, но для целостности я их продублирую.
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
const x = -width / 2; const x = -width / 2;
@@ -84,12 +106,9 @@ export const createBinGeometry = (
thickness: number, thickness: number,
radius: number = 0 radius: number = 0
): THREE.BufferGeometry => { ): THREE.BufferGeometry => {
const floorShape = createRoundedRectShape(width, depth, radius); const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
depth: thickness, depth: thickness, bevelEnabled: false, curveSegments: 16
bevelEnabled: false,
curveSegments: 16
}); });
floorGeo.rotateX(-Math.PI / 2); floorGeo.rotateX(-Math.PI / 2);
@@ -105,9 +124,7 @@ export const createBinGeometry = (
const wallHeight = height - thickness; const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: wallHeight, depth: wallHeight, bevelEnabled: false, curveSegments: 16
bevelEnabled: false,
curveSegments: 16
}); });
wallGeo.rotateX(-Math.PI / 2); wallGeo.rotateX(-Math.PI / 2);
+8
View File
@@ -11,9 +11,17 @@ export interface AppConfig {
cornerRadius: number; cornerRadius: number;
} }
// Новая структура: настройки деления внутри одной ячейки
export interface CellSubdivision {
rows: number; // горизонтальные ряды
cols: number; // вертикальные колонки
}
export interface LayoutSplits { export interface LayoutSplits {
x: number[]; x: number[];
y: number[]; y: number[];
// Ключ: "indexX-indexY" (например "0-0"), Значение: {rows: 2, cols: 1}
subdivisions: Record<string, CellSubdivision>;
} }
export interface GeneratedPart { export interface GeneratedPart {