4
This commit is contained in:
@@ -24,9 +24,11 @@ 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);
|
||||
@@ -48,54 +50,82 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
|
||||
const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
|
||||
|
||||
// -- LOGIC: Dynamic Neighbors Calculation --
|
||||
// Эта функция пересчитывает реальные границы стенки на лету
|
||||
const calculateDynamicLimits = (target: { axis: Axis, offset: number, min?: number, max?: number }, parts: Partition[]) => {
|
||||
// -- HELPERS --
|
||||
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();
|
||||
|
||||
// 1. Рассчитываем реальные (динамические) границы стенки, основываясь на её соседях.
|
||||
// Это нужно, чтобы отрисовать стенку "обрезанной" по соседним стенкам.
|
||||
const calculateWallLimits = (target: Partition, allParts: Partition[]) => {
|
||||
let min = 0;
|
||||
let max = 1;
|
||||
// Используем сохраненные min/max только как "подсказку" где центр стенки
|
||||
const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2;
|
||||
|
||||
// Середина стенки (используем сохраненные данные как подсказку центра)
|
||||
const center = ((target.min ?? 0) + (target.max ?? 1)) / 2;
|
||||
|
||||
parts.forEach(p => {
|
||||
if (p.axis === target.axis) return; // Игнорируем параллельные
|
||||
allParts.forEach(p => {
|
||||
// Ищем только перпендикулярные стенки
|
||||
if (p.axis === target.axis) return;
|
||||
|
||||
// Границы соседки (статические, но для соседки они тоже могут быть динамическими - тут упрощение для производительности)
|
||||
// В идеале нужен рекурсивный солвер, но для 2D UI достаточно проверить попадание
|
||||
// Проверяем, пересекает ли соседка нашу линию движения.
|
||||
// Соседка P (перпендикулярная) имеет offset по своей оси (которая совпадает с нашей осью движения)
|
||||
// И занимает диапазон [p.min, p.max] по нашей перпендикулярной оси.
|
||||
|
||||
const pMin = p.min ?? 0;
|
||||
const pMax = p.max ?? 1;
|
||||
|
||||
// target.offset - это наша позиция. Попадает ли она в диапазон длины соседки?
|
||||
if (target.offset > pMin && target.offset < pMax) {
|
||||
if (p.offset < mid) min = Math.max(min, p.offset);
|
||||
else if (p.offset > mid) max = Math.min(max, p.offset);
|
||||
// Да, соседка стоит на нашем пути.
|
||||
// Где она? Сзади (уменьшает min) или спереди (уменьшает max)?
|
||||
if (p.offset < center) {
|
||||
min = Math.max(min, p.offset);
|
||||
} else if (p.offset > center) {
|
||||
max = Math.min(max, p.offset);
|
||||
}
|
||||
}
|
||||
});
|
||||
return { min, max };
|
||||
};
|
||||
|
||||
// Поиск границ для НОВОЙ стенки (под курсором)
|
||||
const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => {
|
||||
return calculateDynamicLimits({ axis: 'x', offset: lx, min: ly, max: ly }, parts); // Hack: передаем ly как min/max чтобы найти соседей по Y для X-стенки?
|
||||
// Нет, для новой стенки логика чуть другая - мы ищем ближайшие стенки вокруг точки (lx, ly)
|
||||
|
||||
// 2. Рассчитываем "коробку" под курсором мыши для создания НОВОЙ стенки.
|
||||
// Используем Raycasting: ищем ближайшие стенки во всех 4 направлениях.
|
||||
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
|
||||
let minX = 0, maxX = 1;
|
||||
let minY = 0, maxY = 1;
|
||||
|
||||
parts.forEach(p => {
|
||||
// Вычисляем ДИНАМИЧЕСКИЕ границы для соседки, чтобы знать её реальную длину
|
||||
const { min: pMin, max: pMax } = calculateDynamicLimits(p, parts);
|
||||
// Сначала рассчитываем актуальные границы для всех существующих стенок,
|
||||
// чтобы знать их реальную длину.
|
||||
const processedParts = parts.map(p => ({
|
||||
...p,
|
||||
...calculateWallLimits(p, parts) // Добавляем min/max calculated
|
||||
}));
|
||||
|
||||
processedParts.forEach(p => {
|
||||
if (p.axis === 'x') {
|
||||
if (ly >= pMin && ly <= pMax) {
|
||||
// Вертикальная стенка (препятствие по X)
|
||||
// Проверяем, перекрывает ли она наш Y (курсор)
|
||||
if (ly > p.min && ly < p.max) {
|
||||
if (p.offset < lx) minX = Math.max(minX, p.offset);
|
||||
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
|
||||
}
|
||||
} else {
|
||||
if (lx >= pMin && lx <= pMax) {
|
||||
// Горизонтальная стенка (препятствие по Y)
|
||||
// Проверяем, перекрывает ли она наш X (курсор)
|
||||
if (lx > p.min && lx < p.max) {
|
||||
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 };
|
||||
};
|
||||
|
||||
@@ -106,7 +136,8 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const newPart: Partition = {
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
axis, offset, min, max,
|
||||
height: config.drawer.height || 80, rounded: false
|
||||
height: config.drawer.height || 80,
|
||||
rounded: false
|
||||
};
|
||||
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
|
||||
setSelectedPartitionId(newPart.id);
|
||||
@@ -133,17 +164,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
setDragging(null);
|
||||
};
|
||||
|
||||
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();
|
||||
|
||||
// -- MOUSE --
|
||||
// -- MOUSE HANDLERS --
|
||||
const handleMouseMove = (e: React.MouseEvent) => {
|
||||
if (!svgRef.current) return;
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
@@ -214,33 +235,35 @@ 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: pMin, max: pMax } = calculateDynamicLimits(p, parts);
|
||||
const { min, max } = calculateWallLimits(p, parts);
|
||||
if (p.axis === 'x') {
|
||||
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
||||
if (ly >= min && ly <= max && 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 (lx >= min && lx <= max && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
setHoveredPartition({ id: found.id, cellKey: key });
|
||||
} else {
|
||||
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;
|
||||
// Calculate Phantom Box
|
||||
const box = getCursorBox(lx, ly, parts);
|
||||
|
||||
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';
|
||||
const width = bounds.maxX - bounds.minX;
|
||||
const height = bounds.maxY - bounds.minY;
|
||||
const axis = minX < minY ? 'y' : 'x'; // Split shortest distance
|
||||
const width = box.maxX - box.minX;
|
||||
const height = box.maxY - box.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;
|
||||
const min = axis === 'x' ? box.minY : box.minX;
|
||||
const max = axis === 'x' ? box.maxY : box.maxX;
|
||||
setPhantomPartition({ axis, offset, min, max });
|
||||
}
|
||||
}
|
||||
@@ -284,6 +307,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// --- RENDER ---
|
||||
const renderCellsAndPartitions = () => {
|
||||
const elements = [];
|
||||
for (let i = 0; i < sortedX.length - 1; i++) {
|
||||
@@ -319,74 +343,46 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
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 { min: pMin, max: pMax } = calculateDynamicLimits(p, parts);
|
||||
// Используем ту же логику Limits, что и для мыши, чтобы отрисовка совпадала с поведением
|
||||
const { min, max } = calculateWallLimits(p, parts);
|
||||
|
||||
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 * pMin); ly2 = cellY + (cellH * pMax);
|
||||
ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max);
|
||||
|
||||
// Для X-стенки, p.offset - это X координата.
|
||||
// pMin/pMax - это границы по Y.
|
||||
// Чтобы найти расстояние по бокам, нам нужны границы по X.
|
||||
// Мы ищем ВЕРТИКАЛЬНЫХ соседей в диапазоне Y [pMin, pMax]
|
||||
// calculateDynamicLimits дает границы ВДОЛЬ самой стенки. Это нам дало высоту.
|
||||
// Чтобы найти расстояние до левой/правой стенки, берем центр этой стенки
|
||||
const cy = (min + max) / 2;
|
||||
const box = getCursorBox(p.offset, cy, parts); // Используем Box-логику для поиска соседей
|
||||
|
||||
// Теперь найдем ширину (слева/справа).
|
||||
// Мы берем точку в центре стенки и ищем ближайших вертикальных соседей
|
||||
const { min: leftLim, max: rightLim } = calculateDynamicLimits({ axis: 'y', offset: (pMin + pMax)/2, min: 0, max: 1 }, parts.filter(pp => pp.axis === 'x'));
|
||||
// Это хак. Правильнее:
|
||||
let left = 0, right = 1;
|
||||
const cy = (pMin + pMax)/2;
|
||||
parts.forEach(n => {
|
||||
if (n.axis === 'x') {
|
||||
// Соседка перекрывает нас по высоте?
|
||||
// Нужно найти её реальные границы
|
||||
const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts);
|
||||
if (cy > nMin && cy < nMax) {
|
||||
if (n.offset < p.offset) left = Math.max(left, n.offset);
|
||||
if (n.offset > p.offset) right = Math.min(right, n.offset);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
dist1 = (p.offset - left) * realW - wallThick;
|
||||
dist2 = (right - p.offset) * realW - wallThick;
|
||||
dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick;
|
||||
dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick;
|
||||
|
||||
midX = px;
|
||||
midY = (ly1 + ly2) / 2;
|
||||
|
||||
midX = px; midY = (ly1 + ly2) / 2;
|
||||
} else {
|
||||
const py = cellY + (cellH * p.offset);
|
||||
ly1 = py; ly2 = py;
|
||||
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
|
||||
lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max);
|
||||
|
||||
let top = 0, bot = 1;
|
||||
const cx = (pMin + pMax)/2;
|
||||
parts.forEach(n => {
|
||||
if (n.axis === 'y') {
|
||||
const { min: nMin, max: nMax } = calculateDynamicLimits(n, parts);
|
||||
if (cx > nMin && cx < nMax) {
|
||||
if (n.offset < p.offset) top = Math.max(top, n.offset);
|
||||
if (n.offset > p.offset) bot = Math.min(bot, n.offset);
|
||||
}
|
||||
}
|
||||
});
|
||||
const cx = (min + max) / 2;
|
||||
const box = getCursorBox(cx, p.offset, parts);
|
||||
|
||||
dist1 = (p.offset - top) * realD - wallThick;
|
||||
dist2 = (bot - p.offset) * realD - wallThick;
|
||||
dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick;
|
||||
dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick;
|
||||
|
||||
midX = (lx1 + lx2) / 2;
|
||||
midY = py;
|
||||
midX = (lx1 + lx2) / 2; midY = py;
|
||||
}
|
||||
|
||||
const isSel = selectedPartitionId === p.id;
|
||||
@@ -399,7 +395,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="40" />
|
||||
<line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={isSel ? "#a855f7" : (isHov ? "#d8b4fe" : "#7e22ce")} strokeWidth={isSel ? 6 : 4} strokeLinecap="round" />
|
||||
</g>
|
||||
|
||||
<g className="pointer-events-none select-none font-mono text-[14px] font-bold fill-white" style={{ textShadow: '0px 0px 3px #000' }}>
|
||||
{isVertical ? (
|
||||
<>
|
||||
@@ -420,14 +415,14 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
{isHovered && phantomPartition && !hoveredPartition && !dragging && (
|
||||
<g className="pointer-events-none opacity-60">
|
||||
{(() => {
|
||||
const { min: pMin, max: pMax } = phantomPartition;
|
||||
const { min, max } = phantomPartition;
|
||||
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);
|
||||
fx1 = px; fx2 = px; fy1 = cellY + (cellH * min); fy2 = cellY + (cellH * max);
|
||||
} else {
|
||||
const py = cellY + (cellH * phantomPartition.offset);
|
||||
fy1 = py; fy2 = py; fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax);
|
||||
fy1 = py; fy2 = py; fx1 = cellX + (cellW * min); fx2 = cellX + (cellW * max);
|
||||
}
|
||||
return <line x1={fx1} y1={fy1} x2={fx2} y2={fy2} stroke="#34d399" strokeWidth="3" strokeDasharray="6,6"/>;
|
||||
})()}
|
||||
|
||||
Reference in New Issue
Block a user