5
This commit is contained in:
@@ -10,6 +10,8 @@ interface Props {
|
||||
|
||||
type EditMode = 'lines' | 'cells';
|
||||
type Axis = 'x' | 'y';
|
||||
type Limits = { min: number; max: number };
|
||||
type LimitMap = Record<string, Limits>;
|
||||
|
||||
type DragTarget =
|
||||
| { type: 'main'; axis: Axis; index: number }
|
||||
@@ -24,11 +26,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
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);
|
||||
@@ -61,71 +61,62 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
};
|
||||
const selectedData = getSelectedPartition();
|
||||
|
||||
// 1. Рассчитываем реальные (динамические) границы стенки, основываясь на её соседях.
|
||||
// Это нужно, чтобы отрисовать стенку "обрезанной" по соседним стенкам.
|
||||
const calculateWallLimits = (target: Partition, allParts: Partition[]) => {
|
||||
// --- CORE LOGIC: Two-Pass Limit Calculation (Sync with 3D) ---
|
||||
const calculateLimits = (target: { axis: Axis, offset: number }, allParts: Partition[], limitMap: LimitMap | null) => {
|
||||
let min = 0;
|
||||
let max = 1;
|
||||
|
||||
// Середина стенки (используем сохраненные данные как подсказку центра)
|
||||
const center = ((target.min ?? 0) + (target.max ?? 1)) / 2;
|
||||
const mid = target.offset;
|
||||
|
||||
allParts.forEach(p => {
|
||||
// Ищем только перпендикулярные стенки
|
||||
if (p.axis === target.axis) return;
|
||||
|
||||
// Проверяем, пересекает ли соседка нашу линию движения.
|
||||
// Соседка P (перпендикулярная) имеет offset по своей оси (которая совпадает с нашей осью движения)
|
||||
// И занимает диапазон [p.min, p.max] по нашей перпендикулярной оси.
|
||||
|
||||
const pMin = p.min ?? 0;
|
||||
const pMax = p.max ?? 1;
|
||||
let pMin = p.min ?? 0;
|
||||
let pMax = p.max ?? 1;
|
||||
if (limitMap && limitMap[p.id]) {
|
||||
pMin = limitMap[p.id].min;
|
||||
pMax = limitMap[p.id].max;
|
||||
}
|
||||
|
||||
// target.offset - это наша позиция. Попадает ли она в диапазон длины соседки?
|
||||
if (target.offset > pMin && target.offset < pMax) {
|
||||
// Да, соседка стоит на нашем пути.
|
||||
// Где она? Сзади (уменьшает min) или спереди (уменьшает max)?
|
||||
if (p.offset < center) {
|
||||
min = Math.max(min, p.offset);
|
||||
} else if (p.offset > center) {
|
||||
max = Math.min(max, p.offset);
|
||||
}
|
||||
if (p.offset < mid) min = Math.max(min, p.offset);
|
||||
else if (p.offset > mid) max = Math.min(max, p.offset);
|
||||
}
|
||||
});
|
||||
return { min, max };
|
||||
};
|
||||
|
||||
// 2. Рассчитываем "коробку" под курсором мыши для создания НОВОЙ стенки.
|
||||
// Используем Raycasting: ищем ближайшие стенки во всех 4 направлениях.
|
||||
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
|
||||
// Helper to get final limits for a list of parts
|
||||
const getFinalLimitsMap = (parts: Partition[]): LimitMap => {
|
||||
const map: LimitMap = {};
|
||||
// Pass 1
|
||||
parts.forEach(p => { map[p.id] = calculateLimits(p, parts, null); });
|
||||
// Pass 2
|
||||
parts.forEach(p => { map[p.id] = calculateLimits(p, parts, map); });
|
||||
return map;
|
||||
};
|
||||
|
||||
// Calculate phantom box under cursor using Raycasting
|
||||
const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => {
|
||||
let minX = 0, maxX = 1;
|
||||
let minY = 0, maxY = 1;
|
||||
|
||||
// Сначала рассчитываем актуальные границы для всех существующих стенок,
|
||||
// чтобы знать их реальную длину.
|
||||
const processedParts = parts.map(p => ({
|
||||
...p,
|
||||
...calculateWallLimits(p, parts) // Добавляем min/max calculated
|
||||
}));
|
||||
parts.forEach(p => {
|
||||
const { min: pMin, max: pMax } = limitMap[p.id];
|
||||
// Ignore collapsed walls
|
||||
if (pMax - pMin < 0.001) return;
|
||||
|
||||
processedParts.forEach(p => {
|
||||
if (p.axis === 'x') {
|
||||
// Вертикальная стенка (препятствие по X)
|
||||
// Проверяем, перекрывает ли она наш Y (курсор)
|
||||
if (ly > p.min && ly < p.max) {
|
||||
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)
|
||||
// Проверяем, перекрывает ли она наш X (курсор)
|
||||
if (lx > p.min && lx < p.max) {
|
||||
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 };
|
||||
};
|
||||
|
||||
@@ -226,6 +217,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
setHoveredCell(cellIdx);
|
||||
const key = `${cellIdx.i}-${cellIdx.j}`;
|
||||
const parts = safePartitions[key] || [];
|
||||
const limitMap = getFinalLimitsMap(parts); // Calculate limits once per move
|
||||
|
||||
const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1];
|
||||
const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1];
|
||||
@@ -235,9 +227,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
|
||||
let found = null;
|
||||
const SNAP = 0.05;
|
||||
// Check hover over existing (using dynamic limits for precision)
|
||||
for (const p of parts) {
|
||||
const { min, max } = calculateWallLimits(p, parts);
|
||||
const { min, max } = limitMap[p.id];
|
||||
if (max - min < 0.001) continue; // Skip collapsed
|
||||
if (p.axis === 'x') {
|
||||
if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
||||
} else {
|
||||
@@ -248,19 +240,18 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
if (found) {
|
||||
setHoveredPartition({ id: found.id, cellKey: key });
|
||||
} else {
|
||||
// Calculate Phantom Box
|
||||
const box = getCursorBox(lx, ly, parts);
|
||||
const box = getCursorBox(lx, ly, parts, limitMap);
|
||||
|
||||
const distL = lx - box.minX; const distR = box.maxX - lx;
|
||||
const distT = ly - box.minY; const distB = box.maxY - ly;
|
||||
const minX = Math.min(distL, distR);
|
||||
const minY = Math.min(distT, distB);
|
||||
|
||||
const axis = minX < minY ? 'y' : 'x'; // Split shortest distance
|
||||
const axis = minX < minY ? 'y' : 'x';
|
||||
const width = box.maxX - box.minX;
|
||||
const height = box.maxY - box.minY;
|
||||
|
||||
if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) {
|
||||
if ((axis === 'y' && height > 0.05) || (axis === 'x' && width > 0.05)) {
|
||||
const offset = axis === 'x' ? lx : ly;
|
||||
const min = axis === 'x' ? box.minY : box.minX;
|
||||
const max = axis === 'x' ? box.maxY : box.maxX;
|
||||
@@ -326,6 +317,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const realW = (x2 - x1) * drawerW;
|
||||
const realD = (y2 - y1) * drawerD;
|
||||
|
||||
// Calculate limits for rendering
|
||||
const limitMap = getFinalLimitsMap(parts);
|
||||
|
||||
if (parts.length === 0) {
|
||||
const labelX = cellX + cellW / 2;
|
||||
const labelY = cellY + cellH / 2;
|
||||
@@ -346,30 +340,25 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
{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 => {
|
||||
// Используем ту же логику Limits, что и для мыши, чтобы отрисовка совпадала с поведением
|
||||
const { min, max } = calculateWallLimits(p, parts);
|
||||
|
||||
const { min, max } = limitMap[p.id];
|
||||
if (max - min < 0.001) return null; // Don't render collapsed
|
||||
|
||||
let lx1, ly1, lx2, ly2;
|
||||
let dist1 = 0, dist2 = 0;
|
||||
let midX, midY;
|
||||
const isVertical = p.axis === 'x';
|
||||
|
||||
// Для расчета размеров нам нужны границы "коробки", в которой находится эта стенка
|
||||
// Это по сути то же самое, что и getCursorBox, но для точки на стенке.
|
||||
// Чтобы не дублировать код, используем пределы самой стенки и пределы перпендикулярного пространства
|
||||
|
||||
if (isVertical) {
|
||||
const px = cellX + (cellW * p.offset);
|
||||
lx1 = px; lx2 = px;
|
||||
ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max);
|
||||
|
||||
// Чтобы найти расстояние до левой/правой стенки, берем центр этой стенки
|
||||
const cy = (min + max) / 2;
|
||||
const box = getCursorBox(p.offset, cy, parts); // Используем Box-логику для поиска соседей
|
||||
// Use already calculated limits for neighbors
|
||||
const box = getCursorBox(p.offset, cy, parts, limitMap);
|
||||
|
||||
dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick;
|
||||
dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick;
|
||||
|
||||
midX = px; midY = (ly1 + ly2) / 2;
|
||||
} else {
|
||||
const py = cellY + (cellH * p.offset);
|
||||
@@ -377,11 +366,10 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max);
|
||||
|
||||
const cx = (min + max) / 2;
|
||||
const box = getCursorBox(cx, p.offset, parts);
|
||||
const box = getCursorBox(cx, p.offset, parts, limitMap);
|
||||
|
||||
dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick;
|
||||
dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick;
|
||||
|
||||
midX = (lx1 + lx2) / 2; midY = py;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user