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

Merged
rust merged 32 commits from test into main 2026-01-10 23:56:10 +03:00
4 changed files with 97 additions and 118 deletions
Showing only changes of commit 8d3841ae1f - Show all commits
+17 -67
View File
@@ -7,47 +7,8 @@ import { PreviewStep } from './components/PreviewStep';
import { parseShareUrl } from './utils/share'; import { parseShareUrl } from './utils/share';
import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react'; import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
// --- ERROR BOUNDARY (Ловец ошибок) ---
class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean, error: string}> {
constructor(props: any) {
super(props);
this.state = { hasError: false, error: '' };
}
static getDerivedStateFromError(error: any) {
return { hasError: true, error: error.toString() };
}
componentDidCatch(error: any, errorInfo: any) {
console.error("CRITICAL UI ERROR:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="p-8 bg-red-900/50 border border-red-500 rounded-xl text-white m-4">
<h2 className="text-xl font-bold flex items-center gap-2 mb-4">
<AlertTriangle /> Что-то сломалось в этом компоненте
</h2>
<pre className="bg-black/50 p-4 rounded text-xs font-mono overflow-auto">
{this.state.error}
</pre>
<button
onClick={() => window.location.reload()}
className="mt-4 px-4 py-2 bg-red-600 hover:bg-red-500 rounded font-bold"
>
Перезагрузить страницу
</button>
</div>
);
}
return this.props.children;
}
}
const App = () => { const App = () => {
const [step, setStep] = useState(1); const [step, setStep] = useState(1);
const [isLoadedFromUrl, setIsLoadedFromUrl] = useState(false);
const [config, setConfig] = useState<AppConfig>({ const [config, setConfig] = useState<AppConfig>({
drawer: { width: 300, depth: 400, height: 80 }, drawer: { width: 300, depth: 400, height: 80 },
@@ -62,16 +23,10 @@ const App = () => {
partitions: {} partitions: {}
}); });
// Логируем состояние при каждом изменении
useEffect(() => {
console.log("APP STATE UPDATE:", { step, splits, config });
}, [step, splits, config]);
useEffect(() => { useEffect(() => {
try { try {
const sharedData = parseShareUrl(); const sharedData = parseShareUrl();
if (sharedData) { if (sharedData) {
console.log("Loaded from URL:", sharedData);
setConfig(sharedData.config); setConfig(sharedData.config);
setSplits({ setSplits({
x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [], x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
@@ -79,11 +34,10 @@ const App = () => {
partitions: sharedData.splits.partitions || {} partitions: sharedData.splits.partitions || {}
}); });
setStep(3); setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname); window.history.replaceState({}, '', window.location.pathname);
} }
} catch (e) { } catch (e) {
console.error("Url Parse Error", e); console.error("URL load error", e);
} }
}, []); }, []);
@@ -91,11 +45,21 @@ const App = () => {
try { try {
return calculateParts(config, splits); return calculateParts(config, splits);
} catch (e) { } catch (e) {
console.error("Geometry Calc Error:", e); console.error("Geometry calculation failed", e);
return []; return [];
} }
}, [config, splits]); }, [config, splits]);
// Error Boundary component for safety
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="p-4 text-red-500 flex items-center gap-2"><AlertTriangle/> Ошибка отрисовки. Нажмите "Новый проект".</div>;
return this.props.children;
}
}
return ( return (
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950"> <div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950">
<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 sticky top-0 z-50">
@@ -120,32 +84,18 @@ const App = () => {
</div> </div>
</header> </header>
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8"> <main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8 flex flex-col">
{step === 1 && ( {step === 1 && <div className="max-w-4xl mx-auto w-full animate-fade-in"><ConfigStep config={config} onChange={setConfig} /></div>}
<div className="max-w-4xl mx-auto animate-fade-in">
<ConfigStep config={config} onChange={setConfig} />
</div>
)}
{step === 2 && ( {step === 2 && (
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in"> <div className="flex-1 flex flex-col min-h-[500px] animate-fade-in">
{/* Оборачиваем LayoutStep в ErrorBoundary */}
<ErrorBoundary> <ErrorBoundary>
<LayoutStep <LayoutStep config={config} splits={splits} onChange={setSplits} />
key="layout-step-v3" // Force remount
config={config}
splits={splits}
onChange={setSplits}
/>
</ErrorBoundary> </ErrorBoundary>
</div> </div>
)} )}
{step === 3 && ( {step === 3 && <div className="flex-1 flex flex-col min-h-[600px] animate-fade-in"><PreviewStep parts={parts} config={config} splits={splits} /></div>}
<div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in">
<PreviewStep parts={parts} config={config} splits={splits} />
</div>
)}
</main> </main>
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50"> <footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50">
+73 -36
View File
@@ -1,7 +1,7 @@
import React, { useRef, useState, useMemo } from 'react'; import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits, Partition } from '../types'; import { AppConfig, LayoutSplits, Partition } from '../types';
// ИСПОЛЬЗУЕМ ТОЛЬКО БАЗОВЫЕ ИКОНКИ (чтобы не ломать билд) // Только используемые иконки!
import { Grid, MousePointer2, Trash2, RotateCcw, X, Plus } from 'lucide-react'; import { Grid, MousePointer2, Trash2, RotateCcw, X } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -12,7 +12,7 @@ interface Props {
type EditMode = 'lines' | 'cells'; type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y'; type Axis = 'x' | 'y';
// Тип для перетаскивания // Типы для перетаскивания
type DragTarget = type DragTarget =
| { type: 'main'; axis: Axis; index: number } | { type: 'main'; axis: Axis; index: number }
| { type: 'partition'; cellKey: string; id: string; axis: Axis }; | { type: 'partition'; cellKey: string; id: string; axis: Axis };
@@ -22,25 +22,27 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const [mode, setMode] = useState<EditMode>('lines'); const [mode, setMode] = useState<EditMode>('lines');
// Состояния мыши и взаимодействия
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const [isButtonHovered, setIsButtonHovered] = useState(false); const [isButtonHovered, setIsButtonHovered] = useState(false);
const [dragging, setDragging] = useState<DragTarget | null>(null);
// States // Состояния Main Grid
const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null); const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null);
const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null);
// Состояния Partitions
const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null); const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null);
const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null); const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null);
const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number } | null>(null); const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number } | null>(null);
const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null); const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null);
const [dragging, setDragging] = useState<DragTarget | null>(null);
// --- Safe Data Access --- // --- Safe Data ---
const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : []; const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {}; const safePartitions = splits?.partitions || {};
// Расчет размеров
const drawerW = Math.max(1, config.drawer.width || 300); const drawerW = Math.max(1, config.drawer.width || 300);
const drawerD = Math.max(1, config.drawer.depth || 400); const drawerD = Math.max(1, config.drawer.depth || 400);
const aspectRatio = drawerD / drawerW; const aspectRatio = drawerD / drawerW;
@@ -51,7 +53,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]); const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- Helpers --- // --- Helper: Get Selected Data ---
const getSelectedPartition = () => { const getSelectedPartition = () => {
if (!selectedPartitionId) return null; if (!selectedPartitionId) return null;
for (const key in safePartitions) { for (const key in safePartitions) {
@@ -109,6 +111,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height)); const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
setMousePos({ x: nx, y: ny }); setMousePos({ x: nx, y: ny });
// Dragging
if (dragging) { if (dragging) {
if (dragging.type === 'main') { if (dragging.type === 'main') {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] }; const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
@@ -116,7 +119,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
newSplits[dragging.axis][dragging.index] = val; newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits); onChange(newSplits);
} else { } else {
// Явное приведение типа для TS, чтобы не ругался при билде // Drag Partition
const pDrag = dragging as { type: 'partition'; cellKey: string; id: string; axis: Axis }; const pDrag = dragging as { type: 'partition'; cellKey: string; id: string; axis: Axis };
const [iStr, jStr] = pDrag.cellKey.split('-'); const [iStr, jStr] = pDrag.cellKey.split('-');
const i = parseInt(iStr); const j = parseInt(jStr); const i = parseInt(iStr); const j = parseInt(jStr);
@@ -138,7 +141,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
if (isButtonHovered) return; if (isButtonHovered) return;
// --- MODE: LINES --- // Mode: Lines
if (mode === 'lines') { if (mode === 'lines') {
setHoveredMainSplit(null); setHoveredMainSplit(null);
const SNAP = 0.015; const SNAP = 0.015;
@@ -151,12 +154,13 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
} else { setPhantomMainAxis(null); } } else { setPhantomMainAxis(null); }
} }
} }
// --- MODE: CELLS --- // Mode: Cells
else if (mode === 'cells') { else if (mode === 'cells') {
setHoveredPartition(null); setHoveredPartition(null);
setPhantomPartition(null); setPhantomPartition(null);
setHoveredCell(null); setHoveredCell(null);
// Find cell
let cellIndex = null; let cellIndex = null;
for(let i=0; i<sortedX.length-1; i++) { for(let i=0; i<sortedX.length-1; i++) {
if (nx >= sortedX[i] && nx <= sortedX[i+1]) { if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
@@ -181,9 +185,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const lx = (nx - cx1) / cw; const lx = (nx - cx1) / cw;
const ly = (ny - cy1) / ch; const ly = (ny - cy1) / ch;
// Check hovered partitions
let foundPart = null; let foundPart = null;
const PART_SNAP = 0.05; const PART_SNAP = 0.05;
for (const p of parts) { for (const p of parts) {
if (p.axis === 'x') { if (p.axis === 'x') {
if (Math.abs(lx - p.offset) < PART_SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) foundPart = p; if (Math.abs(lx - p.offset) < PART_SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) foundPart = p;
@@ -195,11 +199,21 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
if (foundPart) { if (foundPart) {
setHoveredPartition({ id: foundPart.id, cellKey: key }); setHoveredPartition({ id: foundPart.id, cellKey: key });
} else { } else {
// Determine split direction based on mouse proximity to center/edges
// Simple heuristic: If moving horizontally -> vertical split (x), else horizontal (y)
// Let's use distance to edges. Closer to left/right edge -> Vertical split.
const distLeft = lx; const distRight = 1 - lx; const distLeft = lx; const distRight = 1 - lx;
const distTop = ly; const distBottom = 1 - ly; const distTop = ly; const distBottom = 1 - ly;
const minX = Math.min(distLeft, distRight); const minX = Math.min(distLeft, distRight);
const minY = Math.min(distTop, distBottom); const minY = Math.min(distTop, distBottom);
const axis = minX < minY ? 'y' : 'x';
// If closer to X edges, create Y split (horizontal)? No.
// If closer to top/bottom edges, we want to split vertically (connect top-bottom)?
// Let's create a split PERPENDICULAR to the closest edge.
// If closest edge is Left(vertical), we want a Horizontal line?
// No, typically we want a line PARALLEL to the closest edge.
const axis = minX < minY ? 'x' : 'y'; // Parallel to closest edge
if (lx > 0.05 && lx < 0.95 && ly > 0.05 && ly < 0.95) { if (lx > 0.05 && lx < 0.95 && ly > 0.05 && ly < 0.95) {
setPhantomPartition({ axis, offset: axis === 'x' ? lx : ly }); setPhantomPartition({ axis, offset: axis === 'x' ? lx : ly });
@@ -247,13 +261,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
} }
}; };
const handleMainSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
if (mode !== 'lines' || dragging) return;
e.stopPropagation();
setHoveredMainSplit({ axis, index });
setPhantomMainAxis(null);
};
return ( return (
<div className="bg-slate-900 p-4 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative overflow-hidden"> <div className="bg-slate-900 p-4 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col relative overflow-hidden">
@@ -266,11 +273,11 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700"> <div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
<button onClick={() => { setMode('lines'); setSelectedPartitionId(null); }} <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'}`}> 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'}`}>
<MousePointer2 size={14}/> Границы Границы
</button> </button>
<button onClick={() => setMode('cells')} <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'}`}> 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> </button>
</div> </div>
@@ -279,7 +286,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</button> </button>
</div> </div>
{/* --- INSTRUCTIONS --- */} {/* INSTRUCTIONS */}
<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"> <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" /> <MousePointer2 size={14} className="text-primary" />
{mode === 'lines' ? ( {mode === 'lines' ? (
@@ -289,14 +296,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</div> </div>
) : ( ) : (
<div className="flex gap-3"> <div className="flex gap-3">
<span><b className="text-green-400">ЛКМ в ячейке:</b> Создать перегородку</span> <span><b className="text-green-400">ЛКМ в ячейке:</b> Создать стенку</span>
<span><b className="text-purple-400">Драг:</b> Двигать</span> <span><b className="text-purple-400">Драг:</b> Двигать</span>
<span><b className="text-red-400">2xЛКМ:</b> Удалить</span> <span><b className="text-red-400">2xЛКМ:</b> Удалить</span>
</div> </div>
)} )}
</div> </div>
{/* --- CANVAS --- */} {/* CANVAS */}
<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="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 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" <div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
@@ -311,7 +318,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
> >
<svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block" <svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
preserveAspectRatio="none" preserveAspectRatio="none"
onMouseMove={handleGlobalMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} onMouseMove={handleMouseMove} onMouseDown={handleMouseDown} onMouseUp={() => setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}
> >
<defs> <defs>
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse"> <pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
@@ -320,13 +327,16 @@ 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)" />
{/* --- CELLS & PARTITIONS --- */} {/* CELLS & PARTITIONS */}
{sortedX.slice(0, -1).map((x1, i) => { {sortedX.slice(0, -1).map((x1, i) => {
const x2 = sortedX[i + 1]; const x2 = sortedX[i + 1];
return sortedY.slice(0, -1).map((y1, j) => { return sortedY.slice(0, -1).map((y1, j) => {
const y2 = sortedY[j + 1]; // Гарантированно определена // FIX: Добавлено определение y2
const y2 = sortedY[j + 1];
const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH; const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH;
const key = `${i}-${j}`; const key = `${i}-${j}`;
const parts = safePartitions[key] || []; const parts = safePartitions[key] || [];
const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells';
@@ -334,14 +344,19 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
return ( return (
<g key={`cell-${key}`}> <g key={`cell-${key}`}>
{/* Highlight Cell */}
{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"/>} {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"/>}
{isAnyPartSelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>} {isAnyPartSelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
{/* Existing Partitions */}
{parts.map(p => { {parts.map(p => {
const isSelected = selectedPartitionId === p.id; const isSelected = selectedPartitionId === p.id;
const isHoveredPart = hoveredPartition?.id === p.id; const isHoveredPart = hoveredPartition?.id === p.id;
let lx1, ly1, lx2, ly2; let lx1, ly1, lx2, ly2;
if (p.axis === 'x') { const px = cellX + (cellW * p.offset); lx1 = px; ly1 = cellY; lx2 = px; ly2 = cellY + cellH; } if (p.axis === 'x') { const px = cellX + (cellW * p.offset); lx1 = px; ly1 = cellY; lx2 = px; ly2 = cellY + cellH; }
else { const py = cellY + (cellH * p.offset); lx1 = cellX; ly1 = py; lx2 = cellX + cellW; ly2 = py; } else { const py = cellY + (cellH * p.offset); lx1 = cellX; ly1 = py; lx2 = cellX + cellW; ly2 = py; }
return ( return (
<g key={p.id} onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}> <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="transparent" strokeWidth="30" />
@@ -349,6 +364,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
</g> </g>
); );
})} })}
{/* Phantom Partition */}
{isHovered && phantomPartition && !hoveredPartition && !dragging && ( {isHovered && phantomPartition && !hoveredPartition && !dragging && (
<g className="pointer-events-none opacity-60"> <g className="pointer-events-none opacity-60">
{phantomPartition.axis === 'x' ? {phantomPartition.axis === 'x' ?
@@ -362,26 +379,35 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
}); });
})} })}
{/* --- MAIN GRID --- */} {/* MAIN GRID X */}
{safeX.map((x, i) => { {safeX.map((x, i) => {
const isHovered = hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i; const isHovered = hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i;
return ( return (
<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); }}> <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="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-col-resize" : ""} />
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" /> <line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" />
</g> </g>
); );
})} })}
{/* MAIN GRID Y */}
{safeY.map((y, i) => { {safeY.map((y, i) => {
const isHovered = hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i; const isHovered = hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i;
return ( return (
<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); }}> <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="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-row-resize" : ""} />
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" /> <line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={isHovered ? "#f59e0b" : "#64748b"} strokeWidth={isHovered ? 6 : 4} className="pointer-events-none" />
</g> </g>
); );
})} })}
{/* 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 === '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"/>} {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> </svg>
@@ -393,24 +419,35 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
<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="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"> <div className="flex justify-between items-center mb-6">
<h3 className="text-sm font-bold text-white flex items-center gap-2"> <h3 className="text-sm font-bold text-white flex items-center gap-2">
<Grid size={16} className="text-purple-400"/> Настройки стенки Настройки стенки
</h3> </h3>
<button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button> <button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button>
</div> </div>
<div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6"> <div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6">
<div> <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> <div className="flex justify-between text-xs text-gray-300 mb-2">
<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"/> <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> </div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label> <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"/> <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> </div>
<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"> <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}/> Удалить <Trash2 size={14}/> Удалить
</button> </button>
</div> </div>
<div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">Выделите стенку для настройки.<br/>Двойной клик удаляет её.</div> <div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">
Выделите стенку для настройки.<br/>Двойной клик удаляет её.
</div>
</div> </div>
)} )}
</div> </div>
+2 -9
View File
@@ -4,11 +4,9 @@ import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
const parts: GeneratedPart[] = []; const parts: GeneratedPart[] = [];
// ЗАЩИТА ОТ ОШИБОК ДАННЫХ
const safeX = Array.isArray(splits?.x) ? splits.x : []; const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : []; const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {}; const safeParts = splits?.partitions || {};
const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1]; const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1]; const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
@@ -17,16 +15,13 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
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 rawX = xPoints[i] * config.drawer.width; const rawX = xPoints[i] * config.drawer.width;
const rawY = yPoints[j] * config.drawer.depth; const rawY = yPoints[j] * config.drawer.depth;
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
// Получаем перегородки const internalPartitions = safeParts[`${i}-${j}`] || [];
const internalPartitions = safePartitions[`${i}-${j}`] || [];
// Допуски
const realWidth = rawW - config.printerTolerance; const realWidth = rawW - config.printerTolerance;
const realDepth = rawD - config.printerTolerance; const realDepth = rawD - config.printerTolerance;
const realX = rawX + (config.printerTolerance / 2); const realX = rawX + (config.printerTolerance / 2);
@@ -51,8 +46,6 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
return parts; return parts;
}; };
// ... Вспомогательные функции (createBinGeometry, exportSTL) ...
// (Они остаются без изменений из прошлого ответа, там всё верно)
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;
+2 -3
View File
@@ -11,11 +11,10 @@ export interface AppConfig {
cornerRadius: number; cornerRadius: number;
} }
// Описание внутренней перегородки
export interface Partition { export interface Partition {
id: string; id: string;
axis: 'x' | 'y'; axis: 'x' | 'y';
offset: number; // 0.1 - 0.9 offset: number; // 0.0 - 1.0
height: number; height: number;
rounded: boolean; rounded: boolean;
} }
@@ -23,7 +22,7 @@ export interface Partition {
export interface LayoutSplits { export interface LayoutSplits {
x: number[]; x: number[];
y: number[]; y: number[];
// Ключ: "i-j", Значение: массив перегородок // Ключ "i-j", Значение - массив перегородок
partitions: Record<string, Partition[]>; partitions: Record<string, Partition[]>;
} }