Добавление перегородок в ячейки и их скругления #6

Merged
rust merged 32 commits from test into main 2026-01-10 23:56:10 +03:00
3 changed files with 296 additions and 226 deletions
Showing only changes of commit 8999d1f06a - Show all commits
+242 -158
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 } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -9,24 +9,53 @@ interface Props {
} }
type Axis = 'x' | 'y'; type Axis = 'x' | 'y';
type EditMode = 'lines' | 'cells';
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 // 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);
const [isButtonHovered, setIsButtonHovered] = useState(false);
// New State for Cells
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
const viewBoxW = 1000; const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width; const aspectRatio = config.drawer.depth / config.drawer.width;
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, ...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 sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
// --- Глобальный обработчик (для пустого места и перетаскивания) --- // --- Helpers for Subdivision ---
const updateSubdivision = (i: number, j: number, field: 'rows' | 'cols', delta: number) => {
const key = `${i}-${j}`;
const current = splits.subdivisions?.[key] || { rows: 1, cols: 1 };
const newVal = Math.max(1, Math.min(10, current[field] + delta));
// Если 1x1, удаляем запись, чтобы не засорять
const newSubdivisions = { ...splits.subdivisions };
if (newVal === 1 && (field === 'rows' ? current.cols : current.rows) === 1) {
delete newSubdivisions[key];
} else {
newSubdivisions[key] = { ...current, [field]: newVal };
}
onChange({ ...splits, subdivisions: newSubdivisions });
};
const getSubdivision = (i: number, j: number) => {
return splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
};
// --- Handlers ---
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();
@@ -35,92 +64,70 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
setMousePos({ x: nx, y: ny }); setMousePos({ x: nx, y: ny });
// 1. Если тащим - обновляем позицию if (mode === 'lines') {
if (dragging) { if (dragging) {
const newSplits = { const newSplits = { ...splits, x: [...splits.x], y: [...splits.y] };
x: [...splits.x], const val = dragging.axis === 'x' ? nx : ny;
y: [...splits.y] newSplits[dragging.axis][dragging.index] = val;
}; onChange(newSplits);
const val = dragging.axis === 'x' ? nx : ny; return;
newSplits[dragging.axis][dragging.index] = val; }
onChange(newSplits);
return;
}
// 2. Если мы здесь, значит мышка НЕ на существующей линии setHoveredSplit(null);
// (иначе событие было бы перехвачено в handleSplitHover)
setHoveredSplit(null);
// 3. Логика Фантомной линии (создание новой) // Phantom Logic (Creation)
const SNAP_THRESHOLD = 0.02; const SNAP_THRESHOLD = 0.02;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
// Проверяем, не слишком ли мы близко к краям или другим линиям (чтобы не спамить) const distLeft = nx; const distRight = 1 - nx;
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD); const distTop = ny; const distBottom = 1 - ny;
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD); const minXDist = Math.min(distLeft, distRight);
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD); const minYDist = Math.min(distTop, distBottom);
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
const distLeft = nx; let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
const distRight = 1 - nx;
const distTop = ny;
const distBottom = 1 - ny;
const minXDist = Math.min(distLeft, distRight); let valid = true;
const minYDist = Math.min(distTop, distBottom); if (potentialAxis === 'x') { if (closeToX || closeToEdgeX) valid = false; }
else { if (closeToY || closeToEdgeY) valid = false; }
// Определяем ось по близости к краю if (valid) setPhantomAxis(potentialAxis);
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x'; else setPhantomAxis(null);
let valid = true;
if (potentialAxis === 'x') {
if (closeToX || closeToEdgeX) valid = false;
} else {
if (closeToY || closeToEdgeY) valid = false;
}
if (valid) {
setPhantomAxis(potentialAxis);
} else {
setPhantomAxis(null);
} }
}; };
// --- Обработчик наведения на КОНКРЕТНУЮ линию ---
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => { const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
// Если мы тащим линию, позволяем событию всплыть до глобального обработчика, if (mode !== 'lines') return;
// чтобы он посчитал координаты.
if (dragging) return; if (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) => {
// Клик по существующей линии (hoveredSplit уже установлен через onMouseMove линии) if (mode === 'lines') {
if (hoveredSplit) { if (hoveredSplit) {
if (e.button === 0) { if (e.button === 0) setDragging(hoveredSplit);
setDragging(hoveredSplit); else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
} else if (e.button === 2) { } else if (phantomAxis) {
removeSplit(hoveredSplit.axis, hoveredSplit.index); const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
} const newSplits = { ...splits };
} newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
// Клик по пустому месту (создание) onChange(newSplits);
else if (phantomAxis) { setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y; }
const newSplits = { ...splits }; } else {
newSplits[phantomAxis] = [...newSplits[phantomAxis], val]; // Mode === 'cells'
onChange(newSplits); // Клик обрабатывается в самом rect ячейки, а здесь можно сбрасывать выделение
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); if (e.target === svgRef.current) {
setSelectedCell(null);
}
} }
}; };
const handleMouseUp = () => { const handleMouseUp = () => setDragging(null);
setDragging(null);
};
const removeSplit = (axis: Axis, index: number) => { const removeSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits }; const newSplits = { ...splits };
@@ -128,34 +135,101 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
onChange(newSplits); onChange(newSplits);
setHoveredSplit(null); setHoveredSplit(null);
setDragging(null); setDragging(null);
setIsButtonHovered(false);
}; };
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"> <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
onClick={() => { setMode('lines'); setSelectedCell(null); }}
className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}
>
<Grid size={14} /> Границы
</button>
<button
onClick={() => setMode('cells')}
className={`flex items-center gap-2 px-3 py-1.5 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>
</div>
<button <button
onClick={() => onChange({ x: [], y: [] })} 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" 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> </button>
</div> </div>
<div className="flex flex-col h-full select-none"> <div className="flex flex-col h-full select-none relative">
{/* Панель настроек выбранной ячейки (Появляется только в режиме Cells) */}
{mode === 'cells' && selectedCell && (
<div className="absolute top-4 right-4 z-30 bg-slate-800/90 backdrop-blur p-4 rounded-xl border border-slate-600 shadow-2xl animate-in slide-in-from-top-2 fade-in">
<div className="flex justify-between items-start mb-3">
<span className="text-xs font-bold text-gray-400 uppercase tracking-wide">Настройка ячейки</span>
<button onClick={() => setSelectedCell(null)} className="text-gray-500 hover:text-white"><X size={14}/></button>
</div>
<div className="flex gap-4">
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-500 mb-1">КОЛОНКИ (X)</span>
<div className="flex items-center bg-slate-900 rounded border border-slate-700">
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', -1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-r border-slate-700"
>-</button>
<span className="w-8 text-center font-mono font-bold">{getSubdivision(selectedCell.i, selectedCell.j).cols}</span>
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'cols', 1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-l border-slate-700"
>+</button>
</div>
</div>
<div className="flex flex-col items-center">
<span className="text-[10px] text-gray-500 mb-1">РЯДЫ (Y)</span>
<div className="flex items-center bg-slate-900 rounded border border-slate-700">
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', -1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-r border-slate-700"
>-</button>
<span className="w-8 text-center font-mono font-bold">{getSubdivision(selectedCell.i, selectedCell.j).rows}</span>
<button
onClick={() => updateSubdivision(selectedCell.i, selectedCell.j, 'rows', 1)}
className="w-8 h-8 flex items-center justify-center hover:bg-slate-700 text-gray-300 border-l border-slate-700"
>+</button>
</div>
</div>
</div>
</div>
)}
<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 Box */}
<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"/> Инструкция
</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.5 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>
</ul> <li><b className="text-red-400">ПКМ:</b> Удалить</li>
</ul>
) : (
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight">
<li><b className="text-green-400">Клик по ячейке:</b> Выбрать</li>
<li>Настрой деление в панели</li>
</ul>
)}
</div> </div>
<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]">
@@ -175,7 +249,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
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'
}} }}
> >
@@ -196,7 +270,8 @@ 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 --- */} {/* --- CELLS & SUBDIVISIONS --- */}
{/* Рисуем ячейки ПЕРЕД линиями, чтобы ловить клики в режиме Cells */}
{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) => {
@@ -206,34 +281,76 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const centerX = ((x1 + x2) / 2) * viewBoxW; const centerX = ((x1 + x2) / 2) * viewBoxW;
const centerY = ((y1 + y2) / 2) * viewBoxH; const centerY = ((y1 + y2) / 2) * viewBoxH;
const cellWidthSVG = (x2 - x1) * viewBoxW; const cellX = x1 * viewBoxW;
const cellHeightSVG = (y2 - y1) * viewBoxH; const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW;
const cellH = (y2 - y1) * viewBoxH;
let fontSize = Math.min(36, cellHeightSVG * 0.6); const isSelected = selectedCell?.i === i && selectedCell?.j === j;
fontSize = Math.min(fontSize, cellWidthSVG * 0.25); const subdiv = getSubdivision(i, j);
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.2)" : "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="2"
style={{ className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-colors" : ""}
fontSize: `${fontSize}px`, onClick={(e) => {
textShadow: '1px 1px 3px rgba(0,0,0,0.8)' if (mode === 'cells') {
}} e.stopPropagation();
> setSelectedCell({ i, j });
{width.toFixed(0)} × {depth.toFixed(0)} }
</text> }}
/>
{/* Отрисовка внутренних разделителей (Визуализация) */}
{subdiv.cols > 1 && Array.from({ length: subdiv.cols - 1 }).map((_, cI) => {
const splitX = cellX + (cellW / subdiv.cols) * (cI + 1);
return (
<line
key={`sub-c-${cI}`}
x1={splitX} y1={cellY} x2={splitX} y2={cellY + cellH}
stroke="rgba(255,255,255,0.3)" strokeWidth="1" strokeDasharray="4,2"
className="pointer-events-none"
/>
);
})}
{subdiv.rows > 1 && Array.from({ length: subdiv.rows - 1 }).map((_, rI) => {
const splitY = cellY + (cellH / subdiv.rows) * (rI + 1);
return (
<line
key={`sub-r-${rI}`}
x1={cellX} y1={splitY} x2={cellX + cellW} y2={splitY}
stroke="rgba(255,255,255,0.3)" strokeWidth="1" strokeDasharray="4,2"
className="pointer-events-none"
/>
);
})}
{/* Текст размеров (Скрываем если ячейка разбита или слишком мелкая) */}
{subdiv.rows === 1 && subdiv.cols === 1 && (
<text
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: `${Math.min(36, cellH * 0.6, cellW * 0.25)}px`,
textShadow: '1px 1px 3px rgba(0,0,0,0.8)',
opacity: Math.min(36, cellH * 0.6, cellW * 0.25) < 10 ? 0 : 1
}}
>
{width.toFixed(0)} × {depth.toFixed(0)}
</text>
)}
</g>
); );
}); });
})} })}
{/* --- X Lines (Vertical) --- */} {/* --- Main Grid Lines (X) --- */}
{splits.x.map((x, i) => { {splits.x.map((x, i) => {
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i; const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'x' && dragging.index === i; const isDragging = dragging?.axis === 'x' && dragging.index === i;
@@ -244,26 +361,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<g <g
key={`x-${i}`} key={`x-${i}`}
onDoubleClick={() => removeSplit('x', i)} onDoubleClick={() => removeSplit('x', i)}
// ВАЖНО: Событие вешаем на группу
onMouseMove={(e) => handleSplitHover(e, 'x', i)} onMouseMove={(e) => handleSplitHover(e, 'x', i)}
className={mode === 'lines' ? "cursor-col-resize" : ""}
> >
{/* Невидимая широкая зона захвата (80 единиц!) */} <line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="80" />
<line <line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
x1={x * viewBoxW} y1={0} {mode === 'lines' && (isHovered || isDragging) && (
x2={x * viewBoxW} y2={viewBoxH} <g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}
stroke="transparent" strokeWidth="80" onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
className="cursor-col-resize" >
/> <circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
{/* Видимая линия */}
<line
x1={x * viewBoxW} y1={0}
x2={x * viewBoxW} y2={viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150 pointer-events-none"
/>
{(isHovered || isDragging) && (
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/> <Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g> </g>
)} )}
@@ -271,7 +378,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
); );
})} })}
{/* --- Y Lines (Horizontal) --- */} {/* --- Main Grid Lines (Y) --- */}
{splits.y.map((y, i) => { {splits.y.map((y, i) => {
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i; const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'y' && dragging.index === i; const isDragging = dragging?.axis === 'y' && dragging.index === i;
@@ -283,22 +390,15 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
key={`y-${i}`} key={`y-${i}`}
onDoubleClick={() => removeSplit('y', i)} onDoubleClick={() => removeSplit('y', i)}
onMouseMove={(e) => handleSplitHover(e, 'y', i)} onMouseMove={(e) => handleSplitHover(e, 'y', i)}
className={mode === 'lines' ? "cursor-row-resize" : ""}
> >
<line <line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="80" />
x1={0} y1={y * viewBoxH} <line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
x2={viewBoxW} y2={y * viewBoxH} {mode === 'lines' && (isHovered || isDragging) && (
stroke="transparent" strokeWidth="80" <g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}
className="cursor-row-resize" onMouseEnter={() => setIsButtonHovered(true)} onMouseLeave={() => setIsButtonHovered(false)}
/> >
<line <circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 shadow-lg"/>
x1={0} y1={y * viewBoxH}
x2={viewBoxW} y2={y * viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150 pointer-events-none"
/>
{(isHovered || isDragging) && (
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}>
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/> <Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g> </g>
)} )}
@@ -307,30 +407,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
})} })}
{/* --- Phantom Lines --- */} {/* --- Phantom Lines --- */}
{!hoveredSplit && !dragging && phantomAxis === 'x' && ( {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && (
<g className="pointer-events-none"> <g className="pointer-events-none opacity-60">
<line <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
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> </g>
)} )}
{!hoveredSplit && !dragging && phantomAxis === 'y' && ( {mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && (
<g className="pointer-events-none"> <g className="pointer-events-none opacity-60">
<line <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
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> </g>
)} )}
</svg> </svg>
+44 -66
View File
@@ -2,16 +2,12 @@ import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart } from '../types'; import { AppConfig, LayoutSplits, GeneratedPart } from '../types';
/**
* Calculates the final list of bins based on layout.
*/
export const calculateParts = ( export const calculateParts = (
config: AppConfig, config: AppConfig,
splits: LayoutSplits splits: LayoutSplits
): GeneratedPart[] => { ): GeneratedPart[] => {
const parts: GeneratedPart[] = []; const parts: GeneratedPart[] = [];
// Сортируем линии разреза
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1]; const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1]; const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
@@ -20,59 +16,69 @@ export const calculateParts = (
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 segmentY = yPoints[j] * config.drawer.depth; const rawX = xPoints[i] * config.drawer.width;
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawY = yPoints[j] * config.drawer.depth;
const segmentD = (yPoints[j + 1] - 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;
// Применяем зазор (Tolerance) // Проверяем, есть ли разделение для этой ячейки
const realWidth = segmentW - config.printerTolerance; const subdiv = splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
const realDepth = segmentD - config.printerTolerance;
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);
// Применяем Tolerance (зазор) к каждой микро-ячейке
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;
parts.push({
id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}` + (subdiv.rows > 1 || subdiv.cols > 1 ? ` (${r+1}x${c+1})` : ''),
width: realWidth,
depth: realDepth,
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
});
partCounter++;
}
} }
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; return parts;
}; };
/** // ... Остальной код (createBinGeometry, exportSTL) остается без изменений ...
* Создает 2D форму прямоугольника со скругленными краями // (Копируй функции createRoundedRectShape, createBinGeometry и прочие из предыдущего файла, они не менялись)
*/
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;
const y = -height / 2; const y = -height / 2;
// Ограничиваем радиус, чтобы он не сломал геометрию (не больше половины стороны)
const r = Math.min(radius, width / 2, height / 2); const r = Math.min(radius, width / 2, height / 2);
if (r <= 0.1) { if (r <= 0.1) {
// Обычный прямоугольник (если радиус 0)
shape.moveTo(x, y); shape.moveTo(x, y);
shape.lineTo(x + width, y); shape.lineTo(x + width, y);
shape.lineTo(x + width, y + height); shape.lineTo(x + width, y + height);
shape.lineTo(x, y + height); shape.lineTo(x, y + height);
shape.lineTo(x, y); shape.lineTo(x, y);
} else { } else {
// Прямоугольник со скруглениями
shape.moveTo(x, y + r); shape.moveTo(x, y + r);
shape.lineTo(x, y + height - r); shape.lineTo(x, y + height - r);
shape.quadraticCurveTo(x, y + height, x + r, y + height); shape.quadraticCurveTo(x, y + height, x + r, y + height);
@@ -83,13 +89,9 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
shape.lineTo(x + r, y); shape.lineTo(x + r, y);
shape.quadraticCurveTo(x, y, x, y + r); shape.quadraticCurveTo(x, y, x, y + r);
} }
return shape; return shape;
} }
/**
* Генерирует 3D геометрию ящика
*/
export const createBinGeometry = ( export const createBinGeometry = (
width: number, width: number,
depth: number, depth: number,
@@ -97,25 +99,15 @@ export const createBinGeometry = (
thickness: number, thickness: number,
radius: number = 0 radius: number = 0
): THREE.BufferGeometry => { ): THREE.BufferGeometry => {
// 1. ГЕОМЕТРИЯ ДНА (Сплошная)
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, bevelEnabled: false,
curveSegments: 16 // Количество сегментов на скруглениях curveSegments: 16
}); });
// Extrude выдавливает по оси Z. Нам нужно повернуть, чтобы "глубина" стала "высотой" (Y).
// Поворот на -90 градусов вокруг X кладет Z на Y.
floorGeo.rotateX(-Math.PI / 2); floorGeo.rotateX(-Math.PI / 2);
// Теперь дно занимает пространство от Y=0 до Y=thickness.
// 2. ГЕОМЕТРИЯ СТЕНОК (С дыркой)
const outerShape = createRoundedRectShape(width, depth, radius); const outerShape = createRoundedRectShape(width, depth, radius);
// Вырезаем внутреннюю часть
const innerRadius = Math.max(0, radius - thickness); const innerRadius = Math.max(0, radius - thickness);
const innerWidth = width - (2 * thickness); const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness); const innerDepth = depth - (2 * thickness);
@@ -125,32 +117,18 @@ export const createBinGeometry = (
outerShape.holes.push(innerHole); outerShape.holes.push(innerHole);
} }
// Высота стенок = общая высота минус толщина дна
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, bevelEnabled: false,
curveSegments: 16 curveSegments: 16
}); });
// Поворачиваем стенки так же, как дно
wallGeo.rotateX(-Math.PI / 2); wallGeo.rotateX(-Math.PI / 2);
// Сейчас стенки тоже начинаются с Y=0.
// Нам нужно поднять их НАД дном.
wallGeo.translate(0, thickness, 0); wallGeo.translate(0, thickness, 0);
// Теперь стенки занимают пространство от Y=thickness до Y=height.
// 3. ОБЪЕДИНЕНИЕ
// Сливаем две геометрии в одну. Слайсеры поймут это как единый объект,
// так как поверхности идеально соприкасаются.
const merged = mergeBufferGeometries([floorGeo, wallGeo]); const merged = mergeBufferGeometries([floorGeo, wallGeo]);
if (merged) merged.computeVertexNormals();
// Центрирование не нужно, так как createRoundedRectShape строит форму вокруг (0,0) по X и Z.
// А по Y мы выстроили от 0 вверх.
// Pivot point (опорная точка) осталась внизу в центре (0,0,0), что идеально для позиционирования.
return merged || new THREE.BoxGeometry(1, 1, 1); return merged || new THREE.BoxGeometry(1, 1, 1);
}; };
+9 -1
View File
@@ -8,12 +8,20 @@ export interface AppConfig {
drawer: DrawerDimensions; drawer: DrawerDimensions;
wallThickness: number; wallThickness: number;
printerTolerance: number; printerTolerance: number;
cornerRadius: number; // <--- Новое свойство cornerRadius: number;
}
// Конфигурация разделения одной ячейки
export interface CellSubdivision {
rows: number; // По умолчанию 1
cols: number; // По умолчанию 1
} }
export interface LayoutSplits { export interface LayoutSplits {
x: number[]; x: number[];
y: number[]; y: number[];
// Ключ: "xIndex-yIndex" (например "0-0" для первой ячейки)
subdivisions: Record<string, CellSubdivision>;
} }
export interface GeneratedPart { export interface GeneratedPart {