Added split in to cell
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import React, { useRef, useState, useMemo } from 'react';
|
||||
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 {
|
||||
config: AppConfig;
|
||||
@@ -9,24 +9,53 @@ interface Props {
|
||||
}
|
||||
|
||||
type Axis = 'x' | 'y';
|
||||
type EditMode = 'lines' | 'cells';
|
||||
|
||||
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
|
||||
// State
|
||||
const [mode, setMode] = useState<EditMode>('lines');
|
||||
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null);
|
||||
const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
|
||||
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
|
||||
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);
|
||||
const [isButtonHovered, setIsButtonHovered] = useState(false);
|
||||
|
||||
// New State for Cells
|
||||
const [selectedCell, setSelectedCell] = useState<{ i: number, j: number } | null>(null);
|
||||
|
||||
const viewBoxW = 1000;
|
||||
const aspectRatio = config.drawer.depth / config.drawer.width;
|
||||
const viewBoxH = viewBoxW * aspectRatio;
|
||||
|
||||
// Сортируем линии, чтобы понимать границы ячеек
|
||||
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]);
|
||||
|
||||
// --- Глобальный обработчик (для пустого места и перетаскивания) ---
|
||||
// --- 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) => {
|
||||
if (!svgRef.current) return;
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
@@ -35,92 +64,70 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
|
||||
setMousePos({ x: nx, y: ny });
|
||||
|
||||
// 1. Если тащим - обновляем позицию
|
||||
if (dragging) {
|
||||
const newSplits = {
|
||||
x: [...splits.x],
|
||||
y: [...splits.y]
|
||||
};
|
||||
const val = dragging.axis === 'x' ? nx : ny;
|
||||
newSplits[dragging.axis][dragging.index] = val;
|
||||
onChange(newSplits);
|
||||
return;
|
||||
}
|
||||
if (mode === 'lines') {
|
||||
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;
|
||||
}
|
||||
|
||||
// 2. Если мы здесь, значит мышка НЕ на существующей линии
|
||||
// (иначе событие было бы перехвачено в handleSplitHover)
|
||||
setHoveredSplit(null);
|
||||
setHoveredSplit(null);
|
||||
|
||||
// 3. Логика Фантомной линии (создание новой)
|
||||
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);
|
||||
// Phantom Logic (Creation)
|
||||
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 distTop = ny;
|
||||
const distBottom = 1 - ny;
|
||||
const distLeft = nx; const distRight = 1 - nx;
|
||||
const distTop = ny; const distBottom = 1 - ny;
|
||||
const minXDist = Math.min(distLeft, distRight);
|
||||
const minYDist = Math.min(distTop, distBottom);
|
||||
|
||||
const minXDist = Math.min(distLeft, distRight);
|
||||
const minYDist = Math.min(distTop, distBottom);
|
||||
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
|
||||
|
||||
let valid = true;
|
||||
if (potentialAxis === 'x') { if (closeToX || closeToEdgeX) valid = false; }
|
||||
else { if (closeToY || closeToEdgeY) valid = false; }
|
||||
|
||||
// Определяем ось по близости к краю
|
||||
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
|
||||
|
||||
let valid = true;
|
||||
if (potentialAxis === 'x') {
|
||||
if (closeToX || closeToEdgeX) valid = false;
|
||||
} else {
|
||||
if (closeToY || closeToEdgeY) valid = false;
|
||||
}
|
||||
|
||||
if (valid) {
|
||||
setPhantomAxis(potentialAxis);
|
||||
} else {
|
||||
setPhantomAxis(null);
|
||||
if (valid) setPhantomAxis(potentialAxis);
|
||||
else setPhantomAxis(null);
|
||||
}
|
||||
};
|
||||
|
||||
// --- Обработчик наведения на КОНКРЕТНУЮ линию ---
|
||||
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
|
||||
// Если мы тащим линию, позволяем событию всплыть до глобального обработчика,
|
||||
// чтобы он посчитал координаты.
|
||||
if (mode !== 'lines') return;
|
||||
if (dragging) return;
|
||||
|
||||
// Если просто водим мышкой - блокируем всплытие,
|
||||
// чтобы глобальный обработчик не думал, что мы в пустоте.
|
||||
e.stopPropagation();
|
||||
|
||||
setHoveredSplit({ axis, index });
|
||||
setPhantomAxis(null); // Убираем фантом, раз мы на линии
|
||||
setPhantomAxis(null);
|
||||
};
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
// Клик по существующей линии (hoveredSplit уже установлен через onMouseMove линии)
|
||||
if (hoveredSplit) {
|
||||
if (e.button === 0) {
|
||||
setDragging(hoveredSplit);
|
||||
} else if (e.button === 2) {
|
||||
removeSplit(hoveredSplit.axis, hoveredSplit.index);
|
||||
}
|
||||
}
|
||||
// Клик по пустому месту (создание)
|
||||
else if (phantomAxis) {
|
||||
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 });
|
||||
if (mode === 'lines') {
|
||||
if (hoveredSplit) {
|
||||
if (e.button === 0) setDragging(hoveredSplit);
|
||||
else if (e.button === 2) removeSplit(hoveredSplit.axis, hoveredSplit.index);
|
||||
} else if (phantomAxis) {
|
||||
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 });
|
||||
}
|
||||
} else {
|
||||
// Mode === 'cells'
|
||||
// Клик обрабатывается в самом rect ячейки, а здесь можно сбрасывать выделение
|
||||
if (e.target === svgRef.current) {
|
||||
setSelectedCell(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setDragging(null);
|
||||
};
|
||||
const handleMouseUp = () => setDragging(null);
|
||||
|
||||
const removeSplit = (axis: Axis, index: number) => {
|
||||
const newSplits = { ...splits };
|
||||
@@ -128,34 +135,101 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
onChange(newSplits);
|
||||
setHoveredSplit(null);
|
||||
setDragging(null);
|
||||
setIsButtonHovered(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<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">
|
||||
<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">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Grid size={24} /> 2. Редактор макета
|
||||
</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
|
||||
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"
|
||||
>
|
||||
<RotateCcw size={14} /> Сбросить сетку
|
||||
<RotateCcw size={14} /> Сбросить
|
||||
</button>
|
||||
</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">
|
||||
|
||||
{/* 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="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
|
||||
<MousePointer2 size={14} className="text-primary"/> Инструкция
|
||||
</div>
|
||||
<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>
|
||||
{mode === 'lines' ? (
|
||||
<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>
|
||||
) : (
|
||||
<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 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%',
|
||||
maxWidth: '900px',
|
||||
aspectRatio: `${1/aspectRatio}`,
|
||||
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
|
||||
cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair') : 'default',
|
||||
maxHeight: '75vh'
|
||||
}}
|
||||
>
|
||||
@@ -196,7 +270,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#grid)" />
|
||||
|
||||
{/* --- Labels --- */}
|
||||
{/* --- CELLS & SUBDIVISIONS --- */}
|
||||
{/* Рисуем ячейки ПЕРЕД линиями, чтобы ловить клики в режиме Cells */}
|
||||
{sortedX.slice(0, -1).map((x1, i) => {
|
||||
const x2 = sortedX[i + 1];
|
||||
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 centerY = ((y1 + y2) / 2) * viewBoxH;
|
||||
|
||||
const cellWidthSVG = (x2 - x1) * viewBoxW;
|
||||
const cellHeightSVG = (y2 - y1) * viewBoxH;
|
||||
const cellX = x1 * viewBoxW;
|
||||
const cellY = y1 * viewBoxH;
|
||||
const cellW = (x2 - x1) * viewBoxW;
|
||||
const cellH = (y2 - y1) * viewBoxH;
|
||||
|
||||
let fontSize = Math.min(36, cellHeightSVG * 0.6);
|
||||
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
|
||||
|
||||
if (fontSize < 10) return null;
|
||||
const isSelected = selectedCell?.i === i && selectedCell?.j === j;
|
||||
const subdiv = getSubdivision(i, j);
|
||||
|
||||
return (
|
||||
<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>
|
||||
<g key={`cell-${i}-${j}`}>
|
||||
{/* Интерактивный прямоугольник ячейки */}
|
||||
<rect
|
||||
x={cellX} y={cellY} width={cellW} height={cellH}
|
||||
fill={isSelected ? "rgba(59, 130, 246, 0.2)" : "transparent"}
|
||||
stroke={isSelected ? "#3b82f6" : "transparent"}
|
||||
strokeWidth="2"
|
||||
className={mode === 'cells' ? "cursor-pointer hover:fill-white/5 transition-colors" : ""}
|
||||
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={`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) => {
|
||||
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
|
||||
const isDragging = dragging?.axis === 'x' && dragging.index === i;
|
||||
@@ -244,26 +361,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
<g
|
||||
key={`x-${i}`}
|
||||
onDoubleClick={() => removeSplit('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"
|
||||
className="cursor-col-resize"
|
||||
/>
|
||||
{/* Видимая линия */}
|
||||
<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"/>
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke="transparent" strokeWidth="80" />
|
||||
<line x1={x * viewBoxW} y1={0} x2={x * viewBoxW} y2={viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
|
||||
{mode === 'lines' && (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>
|
||||
)}
|
||||
@@ -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) => {
|
||||
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.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}`}
|
||||
onDoubleClick={() => removeSplit('y', i)}
|
||||
onMouseMove={(e) => handleSplitHover(e, 'y', i)}
|
||||
className={mode === 'lines' ? "cursor-row-resize" : ""}
|
||||
>
|
||||
<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="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"/>
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke="transparent" strokeWidth="80" />
|
||||
<line x1={0} y1={y * viewBoxH} x2={viewBoxW} y2={y * viewBoxH} stroke={color} strokeWidth={width} className="pointer-events-none" />
|
||||
{mode === 'lines' && (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>
|
||||
)}
|
||||
@@ -307,30 +407,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
})}
|
||||
|
||||
{/* --- Phantom 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="12,8"
|
||||
className="opacity-60"
|
||||
/>
|
||||
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'x' && (
|
||||
<g className="pointer-events-none opacity-60">
|
||||
<line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
|
||||
</g>
|
||||
)}
|
||||
{!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="12,8"
|
||||
className="opacity-60"
|
||||
/>
|
||||
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
{mode === 'lines' && !hoveredSplit && !dragging && phantomAxis === 'y' && (
|
||||
<g className="pointer-events-none opacity-60">
|
||||
<line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8"/>
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
@@ -2,16 +2,12 @@ import * as THREE from 'three';
|
||||
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart } from '../types';
|
||||
|
||||
/**
|
||||
* Calculates the final list of bins based on layout.
|
||||
*/
|
||||
export const calculateParts = (
|
||||
config: AppConfig,
|
||||
splits: LayoutSplits
|
||||
): 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];
|
||||
|
||||
@@ -20,59 +16,69 @@ export const calculateParts = (
|
||||
for (let i = 0; i < xPoints.length - 1; i++) {
|
||||
for (let j = 0; j < yPoints.length - 1; j++) {
|
||||
|
||||
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 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;
|
||||
|
||||
// Применяем зазор (Tolerance)
|
||||
const realWidth = segmentW - config.printerTolerance;
|
||||
const realDepth = segmentD - config.printerTolerance;
|
||||
const realX = segmentX + (config.printerTolerance / 2);
|
||||
const realY = segmentY + (config.printerTolerance / 2);
|
||||
// Проверяем, есть ли разделение для этой ячейки
|
||||
const subdiv = splits.subdivisions?.[`${i}-${j}`] || { rows: 1, cols: 1 };
|
||||
|
||||
// Вычисляем размер одной "под-ячейки"
|
||||
// Делим общую ширину на кол-во колонок
|
||||
const subCellWidth = rawW / subdiv.cols;
|
||||
const subCellDepth = rawD / subdiv.rows;
|
||||
|
||||
// Игнорируем слишком мелкие детали
|
||||
if (realWidth < 5 || realDepth < 5) {
|
||||
continue;
|
||||
// Генерируем под-ячейки
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Создает 2D форму прямоугольника со скругленными краями
|
||||
*/
|
||||
// ... Остальной код (createBinGeometry, exportSTL) остается без изменений ...
|
||||
// (Копируй функции createRoundedRectShape, createBinGeometry и прочие из предыдущего файла, они не менялись)
|
||||
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
|
||||
const shape = new THREE.Shape();
|
||||
const x = -width / 2;
|
||||
const y = -height / 2;
|
||||
|
||||
// Ограничиваем радиус, чтобы он не сломал геометрию (не больше половины стороны)
|
||||
const r = Math.min(radius, width / 2, height / 2);
|
||||
|
||||
if (r <= 0.1) {
|
||||
// Обычный прямоугольник (если радиус 0)
|
||||
shape.moveTo(x, y);
|
||||
shape.lineTo(x + width, y);
|
||||
shape.lineTo(x + width, y + height);
|
||||
shape.lineTo(x, y + height);
|
||||
shape.lineTo(x, y);
|
||||
} else {
|
||||
// Прямоугольник со скруглениями
|
||||
shape.moveTo(x, y + r);
|
||||
shape.lineTo(x, y + height - r);
|
||||
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.quadraticCurveTo(x, y, x, y + r);
|
||||
}
|
||||
|
||||
return shape;
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует 3D геометрию ящика
|
||||
*/
|
||||
export const createBinGeometry = (
|
||||
width: number,
|
||||
depth: number,
|
||||
@@ -97,25 +99,15 @@ export const createBinGeometry = (
|
||||
thickness: number,
|
||||
radius: number = 0
|
||||
): THREE.BufferGeometry => {
|
||||
|
||||
// 1. ГЕОМЕТРИЯ ДНА (Сплошная)
|
||||
const floorShape = createRoundedRectShape(width, depth, radius);
|
||||
|
||||
const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
|
||||
depth: thickness, // Выдавливаем на толщину дна
|
||||
depth: thickness,
|
||||
bevelEnabled: false,
|
||||
curveSegments: 16 // Количество сегментов на скруглениях
|
||||
curveSegments: 16
|
||||
});
|
||||
|
||||
// Extrude выдавливает по оси Z. Нам нужно повернуть, чтобы "глубина" стала "высотой" (Y).
|
||||
// Поворот на -90 градусов вокруг X кладет Z на Y.
|
||||
floorGeo.rotateX(-Math.PI / 2);
|
||||
// Теперь дно занимает пространство от Y=0 до Y=thickness.
|
||||
|
||||
// 2. ГЕОМЕТРИЯ СТЕНОК (С дыркой)
|
||||
const outerShape = createRoundedRectShape(width, depth, radius);
|
||||
|
||||
// Вырезаем внутреннюю часть
|
||||
const innerRadius = Math.max(0, radius - thickness);
|
||||
const innerWidth = width - (2 * thickness);
|
||||
const innerDepth = depth - (2 * thickness);
|
||||
@@ -125,32 +117,18 @@ export const createBinGeometry = (
|
||||
outerShape.holes.push(innerHole);
|
||||
}
|
||||
|
||||
// Высота стенок = общая высота минус толщина дна
|
||||
const wallHeight = height - thickness;
|
||||
|
||||
const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
|
||||
depth: wallHeight,
|
||||
bevelEnabled: false,
|
||||
curveSegments: 16
|
||||
});
|
||||
|
||||
// Поворачиваем стенки так же, как дно
|
||||
wallGeo.rotateX(-Math.PI / 2);
|
||||
|
||||
// Сейчас стенки тоже начинаются с Y=0.
|
||||
// Нам нужно поднять их НАД дном.
|
||||
wallGeo.translate(0, thickness, 0);
|
||||
|
||||
// Теперь стенки занимают пространство от Y=thickness до Y=height.
|
||||
|
||||
// 3. ОБЪЕДИНЕНИЕ
|
||||
// Сливаем две геометрии в одну. Слайсеры поймут это как единый объект,
|
||||
// так как поверхности идеально соприкасаются.
|
||||
const merged = mergeBufferGeometries([floorGeo, wallGeo]);
|
||||
|
||||
// Центрирование не нужно, так как createRoundedRectShape строит форму вокруг (0,0) по X и Z.
|
||||
// А по Y мы выстроили от 0 вверх.
|
||||
// Pivot point (опорная точка) осталась внизу в центре (0,0,0), что идеально для позиционирования.
|
||||
if (merged) merged.computeVertexNormals();
|
||||
|
||||
return merged || new THREE.BoxGeometry(1, 1, 1);
|
||||
};
|
||||
|
||||
10
src/types.ts
10
src/types.ts
@@ -8,12 +8,20 @@ export interface AppConfig {
|
||||
drawer: DrawerDimensions;
|
||||
wallThickness: number;
|
||||
printerTolerance: number;
|
||||
cornerRadius: number; // <--- Новое свойство
|
||||
cornerRadius: number;
|
||||
}
|
||||
|
||||
// Конфигурация разделения одной ячейки
|
||||
export interface CellSubdivision {
|
||||
rows: number; // По умолчанию 1
|
||||
cols: number; // По умолчанию 1
|
||||
}
|
||||
|
||||
export interface LayoutSplits {
|
||||
x: number[];
|
||||
y: number[];
|
||||
// Ключ: "xIndex-yIndex" (например "0-0" для первой ячейки)
|
||||
subdivisions: Record<string, CellSubdivision>;
|
||||
}
|
||||
|
||||
export interface GeneratedPart {
|
||||
|
||||
Reference in New Issue
Block a user