Merge pull request 'Добавление перегородок в ячейки и их скругления' (#6) from test into main

Reviewed-on: #6
This commit was merged in pull request #6.
This commit is contained in:
2026-01-10 23:56:09 +03:00
5 changed files with 713 additions and 448 deletions

View File

@@ -5,130 +5,120 @@ import { ConfigStep } from './components/ConfigStep';
import { LayoutStep } from './components/LayoutStep';
import { PreviewStep } from './components/PreviewStep';
import { parseShareUrl } from './utils/share';
import { ChevronRight, ChevronLeft, Box } from 'lucide-react';
import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
// ВАЖНО: ErrorBoundary должен быть ЗДЕСЬ, снаружи компонента App
class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean}> {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
if (this.state.hasError) return (
<div className="h-full flex flex-col items-center justify-center text-red-400">
<AlertTriangle size={32} className="mb-2"/>
<p>Ошибка отрисовки интерфейса.</p>
<button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 bg-slate-800 rounded hover:bg-slate-700 transition-colors">
Перезагрузить
</button>
</div>
);
return this.props.children;
}
}
const App = () => {
const [step, setStep] = useState(1);
const [isLoadedFromUrl, setIsLoadedFromUrl] = useState(false);
// State
const [config, setConfig] = useState<AppConfig>({
drawer: { width: 300, depth: 400, height: 80 },
wallThickness: 1.2,
printerTolerance: 0.5,
cornerRadius: 4, // <--- Дефолтное скругление (4мм)
cornerRadius: 4,
});
const [splits, setSplits] = useState<LayoutSplits>({
x: [],
y: []
y: [],
partitions: {}
});
// --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ ---
useEffect(() => {
const sharedData = parseShareUrl();
if (sharedData) {
setConfig(sharedData.config);
setSplits(sharedData.splits);
setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname);
try {
const sharedData = parseShareUrl();
if (sharedData) {
setConfig(sharedData.config);
setSplits({
x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
y: Array.isArray(sharedData.splits.y) ? sharedData.splits.y : [],
partitions: sharedData.splits.partitions || {}
});
setStep(3);
window.history.replaceState({}, '', window.location.pathname);
}
} catch (e) {
console.error("URL load error", e);
}
}, []);
// Derived State: Parts
const parts: GeneratedPart[] = useMemo(() => {
return calculateParts(config, splits);
try {
return calculateParts(config, splits);
} catch (e) {
return [];
}
}, [config, splits]);
return (
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950">
<div className="h-screen flex flex-col font-sans text-gray-100 bg-slate-950 overflow-hidden">
{/* Header */}
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md sticky top-0 z-50">
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md shrink-0 z-50">
<div className="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="bg-primary p-2 rounded-lg">
<Box className="text-white" size={20} />
</div>
<div>
<h1 className="text-xl font-bold tracking-tight">PrintFit</h1>
<p className="text-xs text-gray-400">Генератор органайзеров</p>
</div>
<div className="bg-primary p-2 rounded-lg"><Box className="text-white" size={20} /></div>
<div><h1 className="text-xl font-bold tracking-tight">PrintFit</h1><p className="text-xs text-gray-400">Генератор органайзеров</p></div>
</div>
{/* Progress Stepper */}
<div className="flex items-center gap-4 text-sm font-medium">
{[1, 2, 3].map((num) => (
<React.Fragment key={num}>
<div className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>
{num}
</span>
<span className="hidden md:inline">
{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}
</span>
</div>
{num < 3 && <div className="w-8 h-[1px] bg-slate-700" />}
</React.Fragment>
<div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>{num}</span>
<span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span>
</div>
))}
</div>
</div>
</header>
{/* Main Content */}
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8">
<main className="flex-1 w-full max-w-7xl mx-auto p-4 overflow-hidden flex flex-col min-h-0">
{step === 1 && (
<div className="max-w-4xl mx-auto animate-fade-in">
<ConfigStep config={config} onChange={setConfig} />
</div>
<div className="h-full overflow-y-auto animate-fade-in custom-scrollbar">
<ConfigStep config={config} onChange={setConfig} />
</div>
)}
{step === 2 && (
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in">
<LayoutStep config={config} splits={splits} onChange={setSplits} />
<div className="h-full flex flex-col animate-fade-in min-h-0">
<ErrorBoundary>
<LayoutStep config={config} splits={splits} onChange={setSplits} />
</ErrorBoundary>
</div>
)}
{step === 3 && (
<div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in">
<div className="h-full flex flex-col animate-fade-in min-h-0">
<PreviewStep parts={parts} config={config} splits={splits} />
</div>
)}
</main>
{/* Footer Navigation */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50">
{/* Footer */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 shrink-0 z-50">
<div className="max-w-7xl mx-auto flex justify-between items-center">
<button
disabled={step === 1}
onClick={() => setStep(s => Math.max(1, s - 1))}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"
>
<ChevronLeft size={18} /> Назад
</button>
<div className="text-sm text-gray-500">
{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}
</div>
<button disabled={step === 1} onClick={() => setStep(s => Math.max(1, s - 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"><ChevronLeft size={18} /> Назад</button>
<div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div>
{step < 3 ? (
<button
onClick={() => setStep(s => Math.min(3, s + 1))}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95"
>
Далее <ChevronRight size={18} />
</button>
<button onClick={() => setStep(s => Math.min(3, s + 1))} className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95">Далее <ChevronRight size={18} /></button>
) : (
<button
onClick={() => {
setStep(1);
setSplits({x: [], y: []});
window.history.replaceState({}, '', window.location.pathname);
}}
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700"
>
Новый проект
</button>
<button onClick={() => { setStep(1); setSplits({x: [], y: [], partitions: {}}); 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">Новый проект</button>
)}
</div>
</footer>

View File

@@ -1,6 +1,7 @@
import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';
import { AppConfig, LayoutSplits, Partition } from '../types';
// Добавил Settings, Move и прочее в импорты
import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings, Plus } from 'lucide-react';
interface Props {
config: AppConfig;
@@ -8,186 +9,428 @@ interface Props {
onChange: (splits: LayoutSplits) => void;
}
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y';
type DragTarget =
| { type: 'main'; axis: Axis; index: number }
| { type: 'partition'; cellKey: string; id: string; axis: Axis };
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null);
// State
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null);
// -- STATE --
const [mode, setMode] = useState<EditMode>('lines');
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 [dragging, setDragging] = useState<DragTarget | null>(null);
const [isButtonHovered, setIsButtonHovered] = useState(false);
// Main Grid Hover
const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null);
const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null);
// Partition Hover
const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null);
const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null);
const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null);
const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null);
// -- SAFE DATA --
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {};
const drawerW = Math.max(1, config.drawer.width || 300);
const drawerD = Math.max(1, config.drawer.depth || 400);
const aspectRatio = drawerD / drawerW;
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]);
// --- Глобальный обработчик (для пустого места и перетаскивания) ---
const handleGlobalMouseMove = (e: React.MouseEvent) => {
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// -- HELPER: Get Selected --
const getSelectedPartition = () => {
if (!selectedPartitionId) return null;
for (const key in safePartitions) {
const part = safePartitions[key].find(p => p.id === selectedPartitionId);
if (part) return { key, part };
}
return null;
};
const selectedData = getSelectedPartition();
// -- LOGIC: T-Junction Limits --
// Находит ближайшие стенки, чтобы ограничить новую перегородку
const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => {
let minX = 0, maxX = 1;
let minY = 0, maxY = 1;
parts.forEach(p => {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (p.axis === 'x') {
// Вертикальная стенка (x=offset, y=min..max)
// Проверяем, находится ли мышь в её диапазоне по Y
if (ly >= pMin && ly <= pMax) {
if (p.offset < lx) minX = Math.max(minX, p.offset);
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
}
} else {
// Горизонтальная стенка (y=offset, x=min..max)
// Проверяем, находится ли мышь в её диапазоне по X
if (lx >= pMin && lx <= pMax) {
if (p.offset < ly) minY = Math.max(minY, p.offset);
if (p.offset > ly) maxY = Math.min(maxY, p.offset);
}
}
});
return { minX, maxX, minY, maxY };
};
// -- ACTIONS --
const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => {
const key = `${i}-${j}`;
const current = safePartitions[key] || [];
const newPart: Partition = {
id: Math.random().toString(36).substr(2, 9),
axis,
offset,
min,
max,
height: config.drawer.height || 80,
rounded: false
};
// Обновляем стейт, но НЕ сбрасываем mode, так как ErrorBoundary теперь снаружи
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
setSelectedPartitionId(newPart.id);
};
const updatePartition = (key: string, id: string, updates: Partial<Partition>) => {
const current = safePartitions[key] || [];
const updated = current.map(p => p.id === id ? { ...p, ...updates } : p);
onChange({ ...splits, partitions: { ...safePartitions, [key]: updated } });
};
const removePartition = (key: string, id: string) => {
const current = safePartitions[key] || [];
onChange({ ...splits, partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) } });
if (selectedPartitionId === id) setSelectedPartitionId(null);
setHoveredPartition(null);
};
const removeMainSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits);
setHoveredMainSplit(null);
setDragging(null);
};
// -- MOUSE HANDLER --
const handleMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect();
if (rect.width === 0) return;
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
setMousePos({ x: nx, y: ny });
// 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);
if (dragging.type === 'main') {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits);
} else {
const [iStr, jStr] = dragging.cellKey.split('-');
const i = parseInt(iStr); const j = parseInt(jStr);
const cellX1 = sortedX[i]; const cellX2 = sortedX[i+1];
const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1];
let newOffset = 0;
if (dragging.axis === 'x') {
newOffset = (nx - cellX1) / (cellX2 - cellX1);
} else {
newOffset = (ny - cellY1) / (cellY2 - cellY1);
}
// Ограничиваем в пределах "родительской" зоны (0-1) внутри ячейки
// В идеале тут тоже надо проверять коллизии, но пока просто границы ячейки
newOffset = Math.max(0.02, Math.min(0.98, newOffset));
if (!isNaN(newOffset)) {
updatePartition(dragging.cellKey, dragging.id, { offset: newOffset });
}
}
return;
}
// 2. Если мы здесь, значит мышка НЕ на существующей линии
// (иначе событие было бы перехвачено в handleSplitHover)
setHoveredSplit(null);
if (isButtonHovered) return;
// 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);
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);
// Определяем ось по близости к краю
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
let valid = true;
if (potentialAxis === 'x') {
if (closeToX || closeToEdgeX) valid = false;
if (mode === 'lines') {
setHoveredMainSplit(null);
const SNAP = 0.015;
if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) {
const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
if (!closeToX && !closeToY) {
const distRight = 1 - nx; const distBottom = 1 - ny;
setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x');
} else { setPhantomMainAxis(null); }
}
} else {
if (closeToY || closeToEdgeY) valid = false;
// Cells Mode
setHoveredPartition(null);
setPhantomPartition(null);
setHoveredCell(null);
// 1. Находим ячейку
let cellIdx = null;
for (let i = 0; i < sortedX.length - 1; i++) {
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
for (let j = 0; j < sortedY.length - 1; j++) {
if (ny >= sortedY[j] && ny <= sortedY[j+1]) {
cellIdx = { i, j };
break;
}
}
}
}
if (cellIdx) {
setHoveredCell(cellIdx);
const key = `${cellIdx.i}-${cellIdx.j}`;
const parts = safePartitions[key] || [];
const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1];
const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1];
const cw = cx2 - cx1; const ch = cy2 - cy1;
const lx = (nx - cx1) / cw;
const ly = (ny - cy1) / ch;
// 2. Проверяем наведение на существующие (для удаления/выделения)
let found = null;
const SNAP = 0.05;
for (const p of parts) {
const pMin = p.min ?? 0; const pMax = p.max ?? 1;
if (p.axis === 'x') {
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
} else {
if (lx >= pMin && lx <= pMax && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
}
}
if (found) {
setHoveredPartition({ id: found.id, cellKey: key });
} else {
// 3. Вычисляем T-образные границы
const bounds = getHoveredBoundaries(lx, ly, parts);
const distL = lx - bounds.minX;
const distR = bounds.maxX - lx;
const distT = ly - bounds.minY;
const distB = bounds.maxY - ly;
const minX = Math.min(distL, distR);
const minY = Math.min(distT, distB);
// Определяем ось перпендикулярно ближайшей стороне
const axis = minX < minY ? 'y' : 'x';
// Проверяем, есть ли место
const width = bounds.maxX - bounds.minX;
const height = bounds.maxY - bounds.minY;
if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) {
const offset = axis === 'x' ? lx : ly;
const min = axis === 'x' ? bounds.minY : bounds.minX;
const max = axis === 'x' ? bounds.maxY : bounds.maxX;
setPhantomPartition({ axis, offset, min, max });
}
}
}
}
if (valid) {
setPhantomAxis(potentialAxis);
} else {
setPhantomAxis(null);
}
};
// --- Обработчик наведения на КОНКРЕТНУЮ линию ---
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
// Если мы тащим линию, позволяем событию всплыть до глобального обработчика,
// чтобы он посчитал координаты.
if (dragging) return;
// Если просто водим мышкой - блокируем всплытие,
// чтобы глобальный обработчик не думал, что мы в пустоте.
e.stopPropagation();
setHoveredSplit({ axis, index });
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);
if (isButtonHovered) return;
if (mode === 'lines') {
if (hoveredMainSplit) {
if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit });
else if (e.button === 2) removeMainSplit(hoveredMainSplit.axis, hoveredMainSplit.index);
} else if (phantomMainAxis) {
const val = phantomMainAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[phantomMainAxis] = [...newSplits[phantomMainAxis], val];
onChange(newSplits);
setDragging({ type: 'main', axis: phantomMainAxis, index: newSplits[phantomMainAxis].length - 1 });
}
} else {
if (hoveredPartition) {
const key = hoveredPartition.cellKey;
const parts = safePartitions[key] || [];
const part = parts.find(p => p.id === hoveredPartition.id);
if (part) {
if (e.button === 0) {
setDragging({ type: 'partition', cellKey: key, id: part.id, axis: part.axis });
setSelectedPartitionId(part.id);
} else if (e.button === 2) {
removePartition(key, part.id);
}
}
} else if (hoveredCell && phantomPartition) {
if (e.button === 0) {
createPartition(
hoveredCell.i,
hoveredCell.j,
phantomPartition.axis,
phantomPartition.offset,
phantomPartition.min,
phantomPartition.max
);
}
} else {
setSelectedPartitionId(null);
}
}
// Клик по пустому месту (создание)
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 });
}
};
const handleMouseUp = () => {
setDragging(null);
};
// --- RENDER ---
const renderCellsAndPartitions = () => {
const elements = [];
for (let i = 0; i < sortedX.length - 1; i++) {
for (let j = 0; j < sortedY.length - 1; j++) {
const x1 = sortedX[i]; const x2 = sortedX[i + 1];
const y1 = sortedY[j]; const y2 = sortedY[j + 1];
const removeSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits);
setHoveredSplit(null);
setDragging(null);
if (y2 === undefined || x2 === undefined) continue;
const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH;
const key = `${i}-${j}`;
const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells';
const parts = safePartitions[key] || [];
const isAnySelected = parts.some(p => p.id === selectedPartitionId);
elements.push(
<g key={key}>
{isHovered && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="rgba(16, 185, 129, 0.05)" stroke="#10b981" strokeWidth="2" strokeDasharray="4,4" className="pointer-events-none"/>}
{isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
{parts.map(p => {
const pMin = p.min ?? 0; const pMax = p.max ?? 1;
let lx1, ly1, lx2, ly2;
if (p.axis === 'x') {
const px = cellX + (cellW * p.offset);
lx1 = px; lx2 = px;
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
} else {
const py = cellY + (cellH * p.offset);
ly1 = py; ly2 = py;
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
}
const isSel = selectedPartitionId === p.id;
const isHov = hoveredPartition?.id === p.id;
return (
<g key={p.id} onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}>
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="30" />
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={isSel ? "#a855f7" : (isHov ? "#d8b4fe" : "#7e22ce")} strokeWidth={isSel ? 6 : 4} strokeLinecap="round" />
</g>
);
})}
{isHovered && phantomPartition && !hoveredPartition && !dragging && (
<g className="pointer-events-none opacity-60">
{(() => {
const pMin = phantomPartition.min; const pMax = phantomPartition.max;
let fx1, fy1, fx2, fy2;
if (phantomPartition.axis === 'x') {
const px = cellX + (cellW * phantomPartition.offset);
fx1 = px; fx2 = px;
fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax);
} else {
const py = cellY + (cellH * phantomPartition.offset);
fy1 = py; fy2 = py;
fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax);
}
return <line x1={fx1} y1={fy1} x2={fx2} y2={fy2} stroke="#34d399" strokeWidth="3" strokeDasharray="6,6"/>;
})()}
</g>
)}
</g>
);
}
}
return elements;
};
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">
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
<Grid size={24} /> 2. Редактор макета
<div className="bg-slate-900 p-4 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative overflow-hidden">
{/* TOOLBAR */}
<div className="flex justify-between items-center mb-2 z-20 shrink-0">
<h2 className="text-lg font-bold flex items-center gap-2 text-primary">
<Grid size={20} /> 2. Редактор макета
</h2>
<button
onClick={() => onChange({ x: [], y: [] })}
className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
>
<RotateCcw size={14} /> Сбросить сетку
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
<button onClick={() => { setMode('lines'); setSelectedPartitionId(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'}`}>
<Move 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'}`}>
<Grid size={14}/> Внутри ячеек
</button>
</div>
<button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1.5 text-xs text-red-400 border border-slate-700 rounded hover:bg-slate-800 transition-colors flex items-center gap-1">
<RotateCcw size={14} /> Сброс
</button>
</div>
<div className="flex flex-col h-full select-none">
<div className="flex-1 bg-slate-800/30 rounded-lg p-6 flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50">
<div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[200px] pointer-events-none">
<div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
<MousePointer2 size={14} className="text-primary"/> Инструкция
</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>
</div>
<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">{config.drawer.width} мм</span>
</div>
<div className="relative flex items-center justify-center w-full h-full">
<div className="h-full max-h-[90%] flex flex-col justify-between py-2 mr-2">
<span className="text-xs text-slate-500 font-mono">0</span>
<span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
</div>
{/* INFO BAR */}
<div className="bg-slate-800/50 rounded-lg px-3 py-2 mb-2 flex items-center gap-3 text-[11px] text-gray-300 border border-slate-700/50 shrink-0">
<MousePointer2 size={14} className="text-primary" />
{mode === 'lines' ? (
<div className="flex gap-3">
<span><b className="text-blue-400">ЛКМ:</b> Линия</span>
<span><b className="text-red-400">ПКМ:</b> Удалить</span>
</div>
) : (
<div className="flex gap-3">
<span><b className="text-green-400">ЛКМ в ячейке:</b> Стенка (T-соединения)</span>
<span><b className="text-purple-400">Драг:</b> Двигать</span>
<span><b className="text-red-400">2КМ:</b> Удалить</span>
</div>
)}
</div>
{/* WORKSPACE */}
<div className="flex-1 bg-slate-800/30 rounded-lg flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50 min-h-0 w-full">
<div className="relative w-full h-full flex items-center justify-center p-4">
<div
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
style={{
width: '100%',
maxWidth: '900px',
style={{
width: aspectRatio > 1 ? 'auto' : '100%',
height: aspectRatio > 1 ? '100%' : 'auto',
aspectRatio: `${1/aspectRatio}`,
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
maxHeight: '75vh'
maxHeight: '100%', maxWidth: '100%',
cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair')
: (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default'),
}}
>
<svg
ref={svgRef}
viewBox={`0 0 ${viewBoxW} ${viewBoxH}`}
className="w-full h-full touch-none"
onMouseMove={handleGlobalMouseMove}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onContextMenu={(e) => e.preventDefault()}
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
preserveAspectRatio="none"
onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
>
<defs>
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
@@ -196,148 +439,77 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- Labels --- */}
{sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => {
const y2 = sortedY[j + 1];
const width = (x2 - x1) * config.drawer.width;
const depth = (y2 - y1) * config.drawer.depth;
const centerX = ((x1 + x2) / 2) * viewBoxW;
const centerY = ((y1 + y2) / 2) * viewBoxH;
const cellWidthSVG = (x2 - x1) * viewBoxW;
const cellHeightSVG = (y2 - y1) * viewBoxH;
{renderCellsAndPartitions()}
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
{/* MAIN GRID X */}
{safeX.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}>
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-col-resize" : ""} />
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
</g>
))}
if (fontSize < 10) return null;
{/* MAIN GRID Y */}
{safeY.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}>
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-row-resize" : ""} />
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
</g>
))}
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>
);
});
})}
{/* --- X Lines (Vertical) --- */}
{splits.x.map((x, i) => {
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'x' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
return (
<g
key={`x-${i}`}
onDoubleClick={() => removeSplit('x', i)}
// ВАЖНО: Событие вешаем на группу
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
>
{/* Невидимая широкая зона захвата (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"/>
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
</g>
)}
</g>
);
})}
{/* --- Y Lines (Horizontal) --- */}
{splits.y.map((y, i) => {
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
const isDragging = dragging?.axis === 'y' && dragging.index === i;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4;
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="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"/>
</g>
)}
</g>
);
})}
{/* --- 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>
</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>
</g>
)}
{/* MAIN PHANTOMS */}
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && <line x1={mousePos.x * viewBoxW} y1="0" x2={mousePos.x * viewBoxW} y2="100%" stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && <line x1="0" y1={mousePos.y * viewBoxH} x2="100%" y2={mousePos.y * viewBoxH} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>}
</svg>
</div>
</div>
{/* --- SIDEBAR FOR EDITING --- */}
{mode === 'cells' && selectedData && (
<div className="absolute top-0 right-0 bottom-0 w-72 bg-slate-900 border-l border-slate-700 p-4 shadow-2xl flex flex-col z-30 animate-in slide-in-from-right duration-200">
<div className="flex justify-between items-center mb-6">
<h3 className="text-sm font-bold text-white flex items-center gap-2">
<Settings size={16} className="text-purple-400"/> Настройки стенки
</h3>
<button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
</div>
<div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6">
{/* Height */}
<div>
<div className="flex justify-between text-xs text-gray-300 mb-2">
<span>Высота</span> <span className="font-mono bg-slate-900 px-1.5 py-0.5 rounded text-xs">{selectedData.part.height} мм</span>
</div>
<input type="range" min="5" max={config.drawer.height || 100} step="1" value={selectedData.part.height}
onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })}
className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"
/>
</div>
{/* Rounded */}
<div className="flex items-center justify-between">
<label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label>
<input type="checkbox" id="rounded-check" checked={selectedData.part.rounded}
onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })}
className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"
/>
</div>
{/* Delete */}
<button
onClick={() => removePartition(selectedData.key, selectedData.part.id)}
className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 rounded text-xs flex items-center justify-center gap-2 transition-colors mt-4"
>
<Trash2 size={14}/> Удалить
</button>
</div>
<div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">
Выделите стенку для настройки.<br/>Двойной клик удаляет её.
</div>
</div>
)}
</div>
</div>
</div>
);
};

View File

@@ -8,7 +8,7 @@ import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryG
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
import { generateShareUrl } from '../utils/share';
// --- DrawerFrame (Каркас) ---
// --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => {
const { width, depth, height } = config.drawer;
const offset = 0.5;
@@ -32,25 +32,37 @@ interface BinMeshProps {
}
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const geometry = useMemo(() => {
return createBinGeometry(part.width, part.depth, part.height, thickness, cornerRadius);
return createBinGeometry(
part.width,
part.depth,
part.height,
thickness,
cornerRadius,
part.internalPartitions // <--- ВАЖНО: передаем перегородки в генератор
);
}, [part, thickness, cornerRadius]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20);
}, [geometry]);
return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
{/* Сама модель */}
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}>
<meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color}
roughness={0.5}
metalness={0.1}
side={THREE.DoubleSide}
side={THREE.DoubleSide} // Рисуем обе стороны стенок
/>
</mesh>
{/* Белая подсветка при выборе */}
{isSelected && (
<lineSegments geometry={edgesGeometry}>
<lineBasicMaterial color="white" linewidth={2} />
@@ -60,7 +72,7 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
);
};
// --- PreviewStep (Основной) ---
// --- PreviewStep (Основной компонент) ---
interface Props {
parts: GeneratedPart[];
config: AppConfig;
@@ -73,25 +85,42 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
const [shareUrlCopied, setShareUrlCopied] = useState(false);
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// Скролл к выбранной детали в списке
useEffect(() => {
if (selectedId && itemRefs.current[selectedId]) {
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [selectedId]);
// Скачивание одной детали
const handleDownload = (part: GeneratedPart) => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius);
const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
};
// Скачивание всего архивом
const handleDownloadAll = async () => {
if (isZipping) return;
setIsZipping(true);
try {
const zip = new JSZip();
parts.forEach(part => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius);
const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions // <--- ВАЖНО для STL
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
const stlData = generateSTL(mesh);
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
@@ -110,6 +139,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
}
};
// Поделиться ссылкой
const handleShare = async () => {
const url = generateShareUrl(config, splits);
let success = false;
@@ -143,8 +173,9 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
return (
<div className="flex flex-col h-full">
{/* Верхняя панель */}
{/* Верхняя панель: Размеры + Поделиться */}
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
<Ruler className="text-primary" size={20} />
@@ -166,6 +197,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
</div>
</div>
<button
onClick={handleShare}
className={`
@@ -261,7 +293,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
`}
onClick={() => setSelectedId(part.id)}
>
{/* Фон-индикатор */}
{/* Индикатор цвета */}
<div
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
style={{ backgroundColor: part.color, opacity: 0.1 }}
@@ -278,12 +310,12 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
/>
</div>
{/* --- РАЗМЕРЫ (НОВОЕ) --- */}
{/* Размеры */}
<div className="text-[10px] text-gray-400 font-mono z-10">
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
</div>
{/* Кнопка */}
{/* Кнопка скачивания */}
<button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"

View File

@@ -1,40 +1,33 @@
import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart } from '../types';
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
/**
* Calculates the final list of bins based on layout.
*/
export const calculateParts = (
config: AppConfig,
splits: LayoutSplits
): GeneratedPart[] => {
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];
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safeParts = splits?.partitions || {};
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
let partCounter = 1;
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 internalPartitions = safeParts[`${i}-${j}`] || [];
// Игнорируем слишком мелкие детали
if (realWidth < 5 || realDepth < 5) {
continue;
}
const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2);
const realY = rawY + (config.printerTolerance / 2);
if (realWidth < 5 || realDepth < 5) continue;
parts.push({
id: `part-${partCounter}`,
@@ -44,35 +37,31 @@ export const calculateParts = (
height: config.drawer.height,
x: realX,
y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
color: `hsl(${Math.random() * 360}, 70%, 50%)`,
internalPartitions: internalPartitions
});
partCounter++;
}
}
return parts;
};
/**
* Создает 2D форму прямоугольника со скругленными краями
*/
// --- ГЕОМЕТРИЯ ---
// 1. Форма скругленного прямоугольника (для дна и внешних стенок)
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,39 +72,39 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
shape.lineTo(x + r, y);
shape.quadraticCurveTo(x, y, x, y + r);
}
return shape;
}
};
// 2. Форма галтели (вогнутого треугольника) для углов
const createFilletShape = (radius: number): THREE.Shape => {
const shape = new THREE.Shape();
// Начинаем из угла (0,0)
shape.moveTo(0, 0);
// Линия вдоль одной стенки
shape.lineTo(radius, 0);
// Вогнутая дуга к другой стенке
// Центр окружности (radius, radius), радиус radius.
// Рисуем дугу от 270 (-PI/2) до 180 (PI) градусов по часовой стрелке
shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true);
// Замыкаем в угол
shape.lineTo(0, 0);
return shape;
};
/**
* Генерирует 3D геометрию ящика
*/
export const createBinGeometry = (
width: number,
depth: number,
height: number,
thickness: number,
radius: number = 0
width: number, depth: number, height: number, thickness: number, radius: number = 0, partitions: Partition[] = []
): THREE.BufferGeometry => {
// 1. ГЕОМЕТРИЯ ДНА (Сплошная)
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, {
depth: thickness, // Выдавливаем на толщину дна
bevelEnabled: false,
curveSegments: 16 // Количество сегментов на скруглениях
});
// Extrude выдавливает по оси Z. Нам нужно повернуть, чтобы "глубина" стала "высотой" (Y).
// Поворот на -90 градусов вокруг X кладет Z на Y.
floorGeo.rotateX(-Math.PI / 2);
// Теперь дно занимает пространство от Y=0 до Y=thickness.
const geometries: THREE.BufferGeometry[] = [];
// 2. ГЕОМЕТРИЯ СТЕНОК (С дыркой)
// ДНО
const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 });
floorGeo.rotateX(-Math.PI / 2);
geometries.push(floorGeo);
// ВНЕШНИЕ СТЕНКИ
const outerShape = createRoundedRectShape(width, depth, radius);
// Вырезаем внутреннюю часть
const innerRadius = Math.max(0, radius - thickness);
const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness);
@@ -125,42 +114,112 @@ export const createBinGeometry = (
outerShape.holes.push(innerHole);
}
// Высота стенок = общая высота минус толщина дна
const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, {
depth: wallHeight,
bevelEnabled: false,
curveSegments: 16
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 12 });
wallGeo.rotateX(-Math.PI / 2);
wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo);
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ И СКРУГЛЕНИЯ
partitions.forEach(p => {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
const lengthRatio = pMax - pMin;
const midRatio = pMin + (lengthRatio / 2);
let pWidth = 0, pDepth = 0, pX = 0, pY = 0;
// Размеры самой стенки
if (p.axis === 'x') {
pWidth = thickness;
pDepth = lengthRatio * innerDepth;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = (-innerDepth / 2) + (innerDepth * midRatio);
} else {
pWidth = lengthRatio * innerWidth;
pDepth = thickness;
pX = (-innerWidth / 2) + (innerWidth * midRatio);
pY = (-innerDepth / 2) + (innerDepth * p.offset);
}
// Создаем стенку
const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); // Чуть-чуть скругляем саму стенку, чтобы не была острой
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 2 });
partGeo.rotateX(-Math.PI / 2);
partGeo.translate(pX, thickness, pY);
geometries.push(partGeo);
// --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) ---
if (p.rounded && radius > 0.5) {
// Радиус скругления такой же, как у углов ящика, но не больше разумного предела
const filletR = Math.min(radius, 6);
const filletShape = createFilletShape(filletR);
const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 };
// Функция для создания и позиционирования одной галтели
const addFillet = (x: number, y: number, rotation: number) => {
const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings);
geo.rotateX(-Math.PI / 2); // Положить на пол
geo.rotateY(rotation); // Повернуть в нужный угол
// Корректировка позиции после вращения вокруг (0,0)
// Нам нужно сместить так, чтобы угол (0,0) галтели совпал с углом стыка
geo.translate(x, thickness, y);
geometries.push(geo);
};
const halfThick = thickness / 2;
if (p.axis === 'x') {
// Вертикальная стенка. Концы: Top (pMin) и Bottom (pMax) (в 2D координатах Y)
// Y координата начала: -innerDepth/2 + innerDepth * pMin
// Y координата конца: -innerDepth/2 + innerDepth * pMax
// X координата центра: pX
const startY = (-innerDepth / 2) + (innerDepth * pMin);
const endY = (-innerDepth / 2) + (innerDepth * pMax);
// 4 Угла:
// 1. Start Left: X = pX - halfThick, Y = startY. Rotation: 0 (смотрит вправо-вверх? нет)
// Галтель рисуется в +X, +Y квадранте от 0,0.
// Нам нужно заполнить угол между стенкой (идет вниз) и перпендикуляром.
// Start (Top in 2D view, actually Min Y in 3D logic here usually means "Back")
// Let's assume standard plan view:
// Min Y is "Top" edge visually in SVG usually 0. In 3D Z is Y.
// Min End (Start of wall):
addFillet(pX - halfThick, startY, 0); // Left side, pointing towards +Z (down in visual)
addFillet(pX + halfThick, startY, -Math.PI/2); // Right side
// Max End (End of wall):
addFillet(pX - halfThick, endY, Math.PI/2); // Left side
addFillet(pX + halfThick, endY, Math.PI); // Right side
} else {
// Горизонтальная стенка
const startX = (-innerWidth / 2) + (innerWidth * pMin);
const endX = (-innerWidth / 2) + (innerWidth * pMax);
// Min End (Left side):
addFillet(startX, pY + halfThick, -Math.PI/2);
addFillet(startX, pY - halfThick, 0);
// Max End (Right side):
addFillet(endX, pY + halfThick, Math.PI);
addFillet(endX, pY - halfThick, Math.PI/2);
}
}
});
// Поворачиваем стенки так же, как дно
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), что идеально для позиционирования.
const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals();
return merged || new THREE.BoxGeometry(1, 1, 1);
};
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter();
const result = exporter.parse(mesh, { binary: true });
if (result instanceof DataView) {
return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
}
if (result instanceof DataView) return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
return result as string;
};

View File

@@ -8,12 +8,23 @@ export interface AppConfig {
drawer: DrawerDimensions;
wallThickness: number;
printerTolerance: number;
cornerRadius: number; // <--- Новое свойство
cornerRadius: number;
}
export interface Partition {
id: string;
axis: 'x' | 'y';
offset: number; // Позиция (0.0 - 1.0)
min: number; // Начало стенки (0.0 - 1.0)
max: number; // Конец стенки (0.0 - 1.0)
height: number;
rounded: boolean;
}
export interface LayoutSplits {
x: number[];
y: number[];
partitions: Record<string, Partition[]>;
}
export interface GeneratedPart {
@@ -25,4 +36,5 @@ export interface GeneratedPart {
x: number;
y: number;
color: string;
internalPartitions: Partition[];
}