у меня есть вот такой код import { IPoint } from '../models/infrastucture/point'; import…
- User
у меня есть вот такой код import { IPoint } from '../models/infrastucture/point'; import Konva from 'konva'; import { ConnectorTypes } from '../models/primitives/enums/connector-types'; import { LineTypes } from './lineTypes';
/**
- Рассчитывает точки для построения связи между двумя коннекторами
- @param fromAbsolute Абсолютная позиция источника.
- @param toAbsolute Абсолютная позиция назначения.
- @param fromId — id начального объекта
- @param toId — id конечного объекта
- @param scale — масштабирование
- @param stagePoint — точка позиционирования канвы
- @param obstacles — массив препятствий
- @param type
- @returns Массив чисел, представляющих точки линии. */ export const calculateLinePoints = ( fromAbsolute: IPoint, toAbsolute: IPoint, fromId: string | number, toId: string | number, scale: number, stagePoint: IPoint, obstacles: Array<{ x: number; y: number; width: number; height: number; id: string | number }>, type?: LineTypes, ): number[] => { const sourceConnector = { x: (fromAbsolute.x - stagePoint.x) / scale, y: (fromAbsolute.y - stagePoint.y) / scale }; const targetConnector = { x: (toAbsolute.x - stagePoint.x) / scale, y: (toAbsolute.y - stagePoint.y) / scale };
const sourceObject = obstacles.find((x) => x.id === fromId); const targetObject = obstacles.find((x) => x.id === toId); if (!sourceObject || !targetObject) { return []; } const points: number[] = []; const shift = 6;
// Если коннекторы смотрят в разные стороны if ( (sourceObject.x < sourceConnector.x && Math.abs(targetObject.x - targetConnector.x) < 25) || (Math.abs(sourceConnector.x - sourceObject.x) < 25 && targetObject.x < targetConnector.x) ) { //Если они друг напротив друга if ( (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x) ) { // Если объекты на одном уровне (связь — прямая линия) if (sourceConnector.y === targetConnector.y) { if (type) { type = LineTypes.Straight; } return [sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y]; } } // Если примитивы "спиной" друг к другу else { // Если объекты на одном уровне // Если объекты на разных уровнях, но по вертикали между ними нет свободного расстояния // Связь — скобка if ( sourceConnector.y === targetConnector.y || (sourceObject.y + sourceObject.height >= targetObject.y && sourceObject.y + sourceObject.height <= targetObject.y + targetObject.height) || (targetObject.y + targetObject.height >= sourceObject.y && targetObject.y + targetObject.height <= sourceObject.y + sourceObject.height) ) { // Начальная точка points.push(sourceConnector.x, sourceConnector.y);
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const secondPoint = { x: sourceConnector.x, y: Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift, }; points.push(secondPoint.x, secondPoint.y); // Горизонтальный отрезок const thirdPoint = { x: targetConnector.x, y: secondPoint.y }; points.push(thirdPoint.x, thirdPoint.y); // Конечная точка points.push(targetConnector.x, targetConnector.y); if (type) { type = sourceConnector.y < secondPoint.y ? LineTypes.BottomBracket : LineTypes.TopBracket; } return points; } } // Если между объектами есть расстояние (связь из трех отрезков) if ( (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x) ) { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Горизонтальный сегмент до средней точки по X const midX = (sourceConnector.x + targetConnector.x) / 2; points.push(midX, sourceConnector.y); // Вертикальный сегмент до уровня второго коннектора points.push(midX, targetConnector.y); // Горизонтальный сегмент до второго коннектора points.push(targetConnector.x, targetConnector.y); if (type) { type = LineTypes.ThreeSegments; } return points; } // Если объекты расположены внахлест (связь из 5 отрезков) if ( (sourceObject.x < sourceConnector.x && sourceConnector.x > targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x > sourceConnector.x && sourceConnector.x < sourceObject.x) ) { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Первый горизонтальный сегмент, продлевающий коннектор const secondPoint = { x: sourceConnector.x + (sourceObject.x < sourceConnector.x ? shift : -shift), y: sourceConnector.y, }; points.push(secondPoint.x, secondPoint.y); // Вертикальный сегмент до середины расстояния между примитивами const thirdPoint = { x: secondPoint.x, y: targetConnector.y > sourceConnector.y ? (targetConnector.y - sourceConnector.y) / 2 + sourceConnector.y : (sourceConnector.y - targetConnector.y) / 2 + targetConnector.y, }; points.push(thirdPoint.x, thirdPoint.y); // Центральный горизонтальный сегмент const fourthPoint = { x: targetConnector.x + (targetConnector.x < targetObject.x ? -shift : shift), y: thirdPoint.y, }; points.push(fourthPoint.x, fourthPoint.y); // Вертикальный сегмент до уровня конечного коннектора const fifthPoint = { x: fourthPoint.x, y: targetConnector.y }; points.push(fifthPoint.x, fifthPoint.y); // Горизонтальный сегмент до конечного коннектора points.push(targetConnector.x, targetConnector.y); if (type) { type = LineTypes.Overlapping; } return points; }}
// Если коннекторы направлены в одну сторону else { // Если объекты расположены на одном уровне if ( (sourceConnector.y > targetObject.y && sourceConnector.y < targetObject.y + targetObject.height) || (targetConnector.y > sourceObject.y && targetConnector.y < sourceObject.y + sourceObject.height) ) { // Начальная точка points.push(sourceConnector.x, sourceConnector.y);
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const secondPoint = { x: sourceConnector.x, y: Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) + shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) - shift, }; points.push(secondPoint.x, secondPoint.y); // Горизонтальный отрезок const thirdPoint = { x: targetConnector.x, y: secondPoint.y }; points.push(thirdPoint.x, thirdPoint.y); // Конечная точка points.push(targetConnector.x, targetConnector.y); return points; } // Если объекты расположены на разном уровне else { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Горизонтальная линия длиной до целевого коннектора const secondPoint = { x: sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x), y: sourceConnector.y, }; // Вертикальная линия до целевого коннектора points.push(secondPoint.x, secondPoint.y); // Горизонтальная линия до конечной точки points.push(targetConnector.x, targetConnector.y); return points; }} return [sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y]; };
/**
- Рассчитывает точки для превью связи, не доведенной до конечного коннектора
- @param connectorPositionAbsolute — абсолютная координата стартового коннектора
- @param connectorType — тип стартового коннектора
- @param pointerPositionAbsolute — абсолютная координата указателя мыши на сцене
- @param scale — масштабирование
- @param stagePoint — точка позиционирования канвы */ export const calculatePreviewLinePoints = ( connectorPositionAbsolute: IPoint, connectorType: ConnectorTypes, pointerPositionAbsolute: IPoint, scale: number, stagePoint: IPoint, ): number[] => { const connectorPosition = { x: (connectorPositionAbsolute.x - stagePoint.x) / scale, y: (connectorPositionAbsolute.y - stagePoint.y) / scale, }; const pointerPosition = { x: (pointerPositionAbsolute.x - stagePoint.x) / scale, y: (pointerPositionAbsolute.y - stagePoint.y) / scale, }; const points: number[] = [];
points.push(connectorPosition.x, connectorPosition.y); if ( (connectorType === ConnectorTypes.Output && pointerPosition.x >= connectorPosition.x) || (connectorType === ConnectorTypes.Input && pointerPosition.x <= connectorPosition.x) ) { const secondPoint = { x: (connectorPosition.x + pointerPosition.x) / 2, y: connectorPosition.y }; points.push(secondPoint.x, secondPoint.y);
const thirdPoint = { x: secondPoint.x, y: pointerPosition.y }; points.push(thirdPoint.x, thirdPoint.y); points.push(pointerPosition.x, pointerPosition.y);} else { const secondPoint = { x: connectorPosition.x, y: pointerPosition.y > connectorPosition.y ? (pointerPosition.y - connectorPosition.y) / 2 + connectorPosition.y : (connectorPosition.y - pointerPosition.y) / 2 + pointerPosition.y, }; points.push(secondPoint.x, secondPoint.y);
const thirdPoint = { x: pointerPosition.x, y: secondPoint.y, }; points.push(thirdPoint.x, thirdPoint.y); points.push(pointerPosition.x, pointerPosition.y);} return points; };
/**
- Ищет Id примитива, которому принадлежит коннектор
- @param node
- @param parentId
- @param connectorId
*/
export const findParentPrimitiveOfConnector = (
node: Konva.Shape | Konva.Group,
parentId: string | number,
connectorId: string | number,
): { x: number; y: number; id: string | number } | null => {
if (node.id() ===
connector-${connectorId}) { const position = node.getAbsolutePosition(); return { x: position.x, y: position.y, id: parentId }; }
if ('children' in node) { for (const child of node.getChildren()) { const foundId = findParentPrimitiveOfConnector(child, parentId, connectorId); if (foundId) { return foundId; } } } return null; };
сейчас тут тип линии возвращается плохо -- я подаю перменную в аргументы и меняю его внутри функции но я бы хотела возвращать тип вместе с массивом. чтобы мне возвращалось иногда два значения массив и тип а иногда одно только -- массив при этом у меня реализовано много кода. если я верну numbers[] | {points: numbers[], type: LineType} мне придется так много менять на доступ к этим самым тайп, а мне так не хочется переписывать все вызовы
- Assistant
Вы можете создать объект для возвращаемых значений из функции, который будет включать как массив точек, так и тип линии. Это позволит вам эффективно передавать оба значения без необходимости переписывать весь код. Конечно, это потребует небольших изменений, но они будут минимальными.
Вот как это можно сделать:
- Создайте интерфейс для результата, который будет содержать массив точек и тип линии.
- Измените возвращаемые значения функций, чтобы они возвращали этот новый объект.
Вот пример изменений, которые нужно внести:
interface LineCalculationResult { points: number[]; type?: LineTypes; } /** * Рассчитывает точки для построения связи между двумя коннекторами */ export const calculateLinePoints = ( fromAbsolute: IPoint, toAbsolute: IPoint, fromId: string | number, toId: string | number, scale: number, stagePoint: IPoint, obstacles: Array<{ x: number; y: number; width: number; height: number; id: string | number }>, type?: LineTypes, ): LineCalculationResult => { // ... ваш код if (type) { type = LineTypes.Straight; } return { points: [sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y], type }; } /** * Рассчитывает точки для превью связи, не доведенной до конечного коннектора */ export const calculatePreviewLinePoints = ( connectorPositionAbsolute: IPoint, connectorType: ConnectorTypes, pointerPositionAbsolute: IPoint, scale: number, stagePoint: IPoint, ): LineCalculationResult => { // ... ваш код return { points: points }; } /** * ... другие функции аналогично */Теперь в других частях вашего кода, где вы вызываете эти функции, вы будете получать объект
LineCalculationResult. Например:const result = calculateLinePoints(...); const points = result.points; const lineType = result.type; // может быть undefinedЭтот подход минимизирует изменения в вашем коде и позволяет вам вернуть оба значения более структурированным способом. Если в какой-то момент требуется только массив точек, вы можете просто получить значения из объекта и игнорировать
type. - User
вот этоработает неправильно
switch (type) { case ConnectionTypes.Straight: points.push(sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y); break; case ConnectionTypes.ThreeSegments: { // Начальная точка points.push(sourceConnector.x, sourceConnector.y);
// Горизонтальный сегмент до средней точки по X const midX = (sourceConnector.x + targetConnector.x) / 2; points.push(midX, sourceConnector.y); // Вертикальный сегмент до уровня второго коннектора points.push(midX, targetConnector.y); // Горизонтальный сегмент до второго коннектора points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.Overlapping: { // Если объекты расположены внахлест (связь из 5 отрезков) // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Первый горизонтальный сегмент, продлевающий коннектор const secondPoint = { x: sourceConnector.x + (sourceObject.x < sourceConnector.x ? shift : -shift), y: sourceConnector.y, }; points.push(secondPoint.x, secondPoint.y); // Вертикальный сегмент до середины расстояния между примитивами const thirdPoint = { x: secondPoint.x, y: targetConnector.y > sourceConnector.y ? (targetConnector.y - sourceConnector.y) / 2 + sourceConnector.y : (sourceConnector.y - targetConnector.y) / 2 + targetConnector.y, }; points.push(thirdPoint.x, thirdPoint.y); // Центральный горизонтальный сегмент const fourthPoint = { x: targetConnector.x + (targetConnector.x < targetObject.x ? -shift : shift), y: thirdPoint.y, }; points.push(fourthPoint.x, fourthPoint.y); // Вертикальный сегмент до уровня конечного коннектора const fifthPoint = { x: fourthPoint.x, y: targetConnector.y }; points.push(fifthPoint.x, fifthPoint.y); // Горизонтальный сегмент до конечного коннектора points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.TopBracket || ConnectionTypes.BottomBracket: { // Если объекты на одном уровне // Если объекты на разных уровнях, но по вертикали между ними нет свободного расстояния // Связь — скобка // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const secondPoint = { x: sourceConnector.x, y: Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift, }; points.push(secondPoint.x, secondPoint.y); // Горизонтальный отрезок const thirdPoint = { x: targetConnector.x, y: secondPoint.y }; points.push(thirdPoint.x, thirdPoint.y); // Конечная точка points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.RightBracket || ConnectionTypes.LeftBracket: { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Горизонтальная линия длиной до целевого коннектора const secondPoint = { x: sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x), y: sourceConnector.y, }; // Вертикальная линия до целевого коннектора points.push(secondPoint.x, secondPoint.y); // Горизонтальная линия до конечной точки points.push(targetConnector.x, targetConnector.y); break; } default: { points.push(sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y); break; }} return points;
множественный кейс не работает как мне затолкать в один кейс два условия или не работает
- Assistant
В JavaScript и TypeScript операторы
||(логическое или) не могут использоваться внутри конструкцииswitchдля объединения нескольких условий. Вместо этого вы можете использовать несколькоcaseподряд, чтобы обработать одно и то же действие для нескольких значений.Чтобы ваш код работал правильно, вы можете изменить конструкцию
caseследующим образом:switch (type) { case ConnectionTypes.Straight: points.push(sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y); break; case ConnectionTypes.ThreeSegments: { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Горизонтальный сегмент до средней точки по X const midX = (sourceConnector.x + targetConnector.x) / 2; points.push(midX, sourceConnector.y); // Вертикальный сегмент до уровня второго коннектора points.push(midX, targetConnector.y); // Горизонтальный сегмент до второго коннектора points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.Overlapping: { // Если объекты расположены внахлест (связь из 5 отрезков) // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Первый горизонтальный сегмент, продлевающий коннектор const secondPoint = { x: sourceConnector.x + (sourceObject.x < sourceConnector.x ? shift : -shift), y: sourceConnector.y, }; points.push(secondPoint.x, secondPoint.y); // Вертикальный сегмент до середины расстояния между примитивами const thirdPoint = { x: secondPoint.x, y: targetConnector.y > sourceConnector.y ? (targetConnector.y - sourceConnector.y) / 2 + sourceConnector.y : (sourceConnector.y - targetConnector.y) / 2 + targetConnector.y, }; points.push(thirdPoint.x, thirdPoint.y); // Центральный горизонтальный сегмент const fourthPoint = { x: targetConnector.x + (targetConnector.x < targetObject.x ? -shift : shift), y: thirdPoint.y, }; points.push(fourthPoint.x, fourthPoint.y); // Вертикальный сегмент до уровня конечного коннектора const fifthPoint = { x: fourthPoint.x, y: targetConnector.y }; points.push(fifthPoint.x, fifthPoint.y); // Горизонтальный сегмент до конечного коннектора points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.TopBracket: case ConnectionTypes.BottomBracket: { // Если объекты на одном уровне // Если объекты на разных уровнях, но по вертикали между ними нет свободного расстояния // Связь — скобка // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const secondPoint = { x: sourceConnector.x, y: Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift, }; points.push(secondPoint.x, secondPoint.y); // Горизонтальный отрезок const thirdPoint = { x: targetConnector.x, y: secondPoint.y }; points.push(thirdPoint.x, thirdPoint.y); // Конечная точка points.push(targetConnector.x, targetConnector.y); break; } case ConnectionTypes.RightBracket: case ConnectionTypes.LeftBracket: { // Начальная точка points.push(sourceConnector.x, sourceConnector.y); // Горизонтальная линия длиной до целевого коннектора const secondPoint = { x: sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x), y: sourceConnector.y, }; // Вертикальная линия до целевого коннектора points.push(secondPoint.x, secondPoint.y); // Горизонтальная линия до конечной точки points.push(targetConnector.x, targetConnector.y); break; } default: { points.push(sourceConnector.x, sourceConnector.y, targetConnector.x, targetConnector.y); break; } }В этом обновлённом коде
case ConnectionTypes.TopBracket:иcase ConnectionTypes.BottomBracket:теперь обрабатываются одним и тем же блоком кода, что позволяет удобно управлять несколькими условиями. То же самое проделано дляRightBracketиLeftBracket. - User
можешь упростить тут условия где поулчится? import { IPoint } from '../models/infrastucture/point'; import { shift } from '../constants';
export enum ConnectionTypes { Straight, ThreeSegments, Overlapping, RightBracket, LeftBracket, TopBracket, BottomBracket, }
export const getConnectionType = ( fromAbsolute: IPoint, toAbsolute: IPoint, fromId: string | number, toId: string | number, scale: number, stagePoint: IPoint, obstacles: Array<{ x: number; y: number; width: number; height: number; id: string | number }>, ): ConnectionTypes | null => { const sourceConnector = { x: (fromAbsolute.x - stagePoint.x) / scale, y: (fromAbsolute.y - stagePoint.y) / scale }; const targetConnector = { x: (toAbsolute.x - stagePoint.x) / scale, y: (toAbsolute.y - stagePoint.y) / scale };
const sourceObject = obstacles.find((x) => x.id === fromId); const targetObject = obstacles.find((x) => x.id === toId); if (!sourceObject || !targetObject) { return null; } // Если коннекторы смотрят в разные стороны if ( (sourceObject.x < sourceConnector.x && Math.abs(targetObject.x - targetConnector.x) < 25) || (Math.abs(sourceConnector.x - sourceObject.x) < 25 && targetObject.x < targetConnector.x) ) { //Если они друг напротив друга if ( (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x) ) { // Если объекты на одном уровне (связь — прямая линия) if (sourceConnector.y === targetConnector.y) { return ConnectionTypes.Straight; } } // Если примитивы "спиной" друг к другу else { // Если объекты на одном уровне // Если объекты на разных уровнях, но по вертикали между ними нет свободного расстояния // Связь — скобка if ( sourceConnector.y === targetConnector.y || (sourceObject.y + sourceObject.height >= targetObject.y && sourceObject.y + sourceObject.height <= targetObject.y + targetObject.height) || (targetObject.y + targetObject.height >= sourceObject.y && targetObject.y + targetObject.height <= sourceObject.y + sourceObject.height) ) { const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift;
return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket; } } // Если между объектами есть расстояние (связь из трех отрезков) if ( (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x) ) { return ConnectionTypes.ThreeSegments; } // Если объекты расположены внахлест (связь из 5 отрезков) if ( (sourceObject.x < sourceConnector.x && sourceConnector.x > targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x > sourceConnector.x && sourceConnector.x < sourceObject.x) ) { return ConnectionTypes.Overlapping; }}
// Если коннекторы направлены в одну сторону else { // Если объекты расположены на одном уровне if ( (sourceConnector.y > targetObject.y && sourceConnector.y < targetObject.y + targetObject.height) || (targetConnector.y > sourceObject.y && targetConnector.y < sourceObject.y + sourceObject.height) ) { // Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) + shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) - shift; return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket; }
// Если объекты расположены на разном уровне else { // Горизонтальная линия длиной до целевого коннектора const targetX = sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x); return sourceConnector.x < targetX ? ConnectionTypes.LeftBracket : ConnectionTypes.RightBracket; }} return null; };
- Assistant
Конечно! Упрощение условий — это хороший способ улучшить читаемость кода. Мы можем начать с вынесения повторяющихся вычислений в отдельные переменные и упростить некоторые сложные условия. Вот пример того, как можно сделать код более понятным:
import { IPoint } from '../models/infrastucture/point'; import { shift } from '../constants'; export enum ConnectionTypes { Straight, ThreeSegments, Overlapping, RightBracket, LeftBracket, TopBracket, BottomBracket, } export const getConnectionType = ( fromAbsolute: IPoint, toAbsolute: IPoint, fromId: string | number, toId: string | number, scale: number, stagePoint: IPoint, obstacles: Array<{ x: number; y: number; width: number; height: number; id: string | number }> ): ConnectionTypes | null => { const sourceConnector = { x: (fromAbsolute.x - stagePoint.x) / scale, y: (fromAbsolute.y - stagePoint.y) / scale }; const targetConnector = { x: (toAbsolute.x - stagePoint.x) / scale, y: (toAbsolute.y - stagePoint.y) / scale }; const sourceObject = obstacles.find((x) => x.id === fromId); const targetObject = obstacles.find((x) => x.id === toId); if (!sourceObject || !targetObject) { return null; } const isFacingDifferentDirections = (sourceObject.x < sourceConnector.x && Math.abs(targetObject.x - targetConnector.x) < 25) || (Math.abs(sourceConnector.x - sourceObject.x) < 25 && targetObject.x < targetConnector.x); // Если коннекторы смотрят в разные стороны if (isFacingDifferentDirections) { const areDirectlyOpposite = (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x); if (areDirectlyOpposite) { if (sourceConnector.y === targetConnector.y) { return ConnectionTypes.Straight; } const onSameLevelOrNoClearance = sourceConnector.y === targetConnector.y || (sourceObject.y + sourceObject.height >= targetObject.y && sourceObject.y + sourceObject.height <= targetObject.y + targetObject.height) || (targetObject.y + targetObject.height >= sourceObject.y && targetObject.y + targetObject.height <= sourceObject.y + sourceObject.height); if (onSameLevelOrNoClearance) { const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift; return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket; } } const isThreeSegments = (sourceObject.x < sourceConnector.x && sourceConnector.x < targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x < sourceConnector.x && sourceConnector.x < sourceObject.x); if (isThreeSegments) { return ConnectionTypes.ThreeSegments; } const isOverlapping = (sourceObject.x < sourceConnector.x && sourceConnector.x > targetConnector.x && targetConnector.x < targetObject.x) || (targetObject.x < targetConnector.x && targetConnector.x > sourceConnector.x && sourceConnector.x < sourceObject.x); if (isOverlapping) { return ConnectionTypes.Overlapping; } } else { // Если коннекторы направлены в одну сторону const isSameLevel = (sourceConnector.y > targetObject.y && sourceConnector.y < targetObject.y + targetObject.height) || (targetConnector.y > sourceObject.y && targetConnector.y < sourceObject.y + sourceObject.height); if (isSameLevel) { const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) + shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) - shift; return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket; } else { const targetX = sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x); return sourceConnector.x < targetX ? ConnectionTypes.LeftBracket : ConnectionTypes.RightBracket; } } return null; };Основные изменения:
- Выделение логики в переменные: Условия проверки вынесены в отдельные переменные с понятными названиями, что улучшает читабельность и понимание кода.
- Уменьшение вложенности: Некоторые условия были упрощены, что уменьшило количество уровней вложенности и сделало структуру кода более линейной.
- Чистота кода: Логика теперь более очевидна, и при необходимости изменения условий это будет проще реализовать.
Такие изменения помогут вам легче понять, что делает код, и упростят его дальнейшую поддержку.
- User
как мне упросить вот это // Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) + shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) - shift; return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket;
возможно без расчетов для таргет у как просто выбрать тип? - Assistant
Да, вы можете упростить этот участок кода, избавившись от лишних расчетов для
targetY. Вместо этого вы можете использовать существующие значенияsourceObjectиtargetObjectдля определения типа линии, не рассчитывая дополнительные координаты.Основная идея заключается в том, что вам необходимо определить, находится ли
sourceConnector.yвыше или ниже вертикальной границы, определенной высотой объектов. В этом случае вы можете использовать минимальное и максимальное значение y для определения типа, не вводя дополнительную переменную.Вот как это можно сделать:
// Определяем верхнюю и нижнюю границы объектов const upperBound = Math.min(sourceObject.y, targetObject.y); const lowerBound = Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height); // Возвращаем тип соединения на основе позиции connector return sourceConnector.y < upperBound + shift ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket;Объяснение изменений:
- Определение границ: Мы вычисляем верхнюю (
upperBound) и нижнюю (lowerBound) границы объектов один раз в начале. - Упрощение логики возврата: Теперь можно вернуть тип соединителя, сравнивая
sourceConnector.yс верхней границей, добавленнойshift, что делает логику более ясной и сжатой.
В результате код становится чище, и его проще понять. Однако, поскольку вы работаете с вертикальным положением объектов, убедитесь, что значение
shiftкорректно, чтобы этот подход продолжал работать как ожидалось. - Определение границ: Мы вычисляем верхнюю (
- User
а это const targetX = sourceConnector.x < sourceObject.x ? Math.min(sourceConnector.x, targetConnector.x) : Math.max(sourceConnector.x, targetConnector.x);
return sourceConnector.x < targetX ? ConnectionTypes.LeftBracket : ConnectionTypes.RightBracket; - Assistant
В вашем коде можно упростить выбор значения
targetX, так как вам не нужно вычислять его с помощью условной операции, если конечный результат уже может быть определен на основании позицииsourceConnector. Вместо этого можно использоватьsourceObjectиtargetConnectorдля определения направления.Вот как можно упростить этот фрагмент:
const isLeftBracket = sourceConnector.x < targetConnector.x; return isLeftBracket ? ConnectionTypes.LeftBracket : ConnectionTypes.RightBracket;Объяснение изменений:
- Логическое сравнение: Прямо сравнивая
sourceConnector.xиtargetConnector.x, мы можем определить, какой тип соединения нужно вернуть. - Упрощение логики: Мы избегаем лишнего условного выражения и преобразования, заменив его на простое логическое выражение.
Это делает код более читаемым и сокращает использование лишних переменных, сохраняя прозрачность логики.
- Логическое сравнение: Прямо сравнивая
- User
а это const targetY = Math.min(sourceObject.y, targetObject.y) > shift ? Math.min(sourceObject.y, targetObject.y) - shift : Math.max(sourceObject.y + sourceObject.height, targetObject.y + targetObject.height) + shift;
return sourceConnector.y < targetY ? ConnectionTypes.BottomBracket : ConnectionTypes.TopBracket; - Assistant
Можно упростить данный участок кода, избегая лишних расчетов для
targetY, как вы уже делали раньше. Главное здесь — определить, выходит лиsourceConnector.yза пределы верхней или нижней границы объектов, без необходимости вычислятьtargetY.Вот как это можно упростить:
const aboveSource = sourceConnector.y < sourceObject.y; const aboveTarget = sourceConnector.y < targetObject.y; if (aboveSource && aboveTarget) { return ConnectionTypes.BottomBracket; } else { return ConnectionTypes.TopBracket; }Объяснение изменений:
- Упрощение логики: Вместо вычисления конкретного
targetYмы проверяем, выше лиsourceConnector.yобоих объектов, и в зависимости от этого определяем тип соединения. - Чистый возврат: Теперь возвращаемое значение зависит от двух простых условий.
Такой подход делает код более понятным и уменьшает количество операций. Вы также можете рассмотреть более сложные логические проверки в зависимости от ваших конкретных бизнес-требований, но общий принцип — это упрощение и ясность.
- Упрощение логики: Вместо вычисления конкретного
- User
у меня есть вот такая функция const getArguments = () => { const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } return { fromAbsolute: { x: sourceParentPosition.x, y: sourceParentPosition.y }, toAbsolute: { x: targetParentPosition.x, y: targetParentPosition.y }, fromId: sourceParentPosition.id, toId: targetParentPosition.id, scale: stageInteraction.scale, stagePoint: stageInteraction.point, obstacles: getObstacles(layer), };};
теперь мне надо вызвать функцию с точно такими же аргументами но я не могу применить спред const type = getConnectionType(...arg); TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.
- Assistant
Чтобы решить вашу проблему с использованием оператора распространения (spread operator) при вызове функции, вам нужно убедиться, что возвращаемый объект из функции
getArgumentsсоответствует нужному типу. Судя по вашему коду,getArgumentsвозвращает объект с несколькими свойствами (координаты, идентификаторы и т.д.).Чтобы корректно использовать оператор распространения, вы можете сделать следующее:
- Убедитесь, что функция возвращает объект с соответствующими свойствами: Убедитесь, что ваше свойство, возвращаемое из
getArguments, содержит значения, соответствующие ожидаемым аргументам дляgetConnectionType. - Преобразуйте возвращаемый объект в массив значений, если он не является кортежем: Если вы хотите использовать оператор распространения, можно преобразовать объект в массив.
Вот как это можно сделать:
Способ 1: Использование деструктуризации
const args = getArguments(); if (args) { const { fromAbsolute, toAbsolute, fromId, toId, scale, stagePoint, obstacles } = args; const type = getConnectionType( fromAbsolute, toAbsolute, fromId, toId, scale, stagePoint, obstacles ); }Способ 2: Упаковка аргументов в массив
Если вы по-прежнему хотите использовать оператор расширения, вы можете изменить возвращаемую структуру в
getArgumentsдля возврата стандартного кортежа:return [ { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ]; // Вызов функции const args = getArguments(); if (args) { const type = getConnectionType(...args); }Выбор подхода
- Способ 1 подходит, если вы хотите сохранить ясность и структуру кода, и не хотите изменять возвращаемую структуру
getArguments. - Способ 2 может быть удобно использовать, если вы хотите работать с массивами и готовы адаптировать вашу функцию для возврата кортежа.
Каждый из методов имеет свои плюсы, и выбор зависит от вашей дальнейшей работы с аргументами функции.
- Убедитесь, что функция возвращает объект с соответствующими свойствами: Убедитесь, что ваше свойство, возвращаемое из
- User
я взяла второй и получила TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.
- Assistant
Ошибка
TS2556: A spread argument must either have a tuple type or be passed to a rest parameterвозникает, если TypeScript не распознаёт значение, которое вы пытаетесь развернуть, как массив (или кортеж) с предопределённой длиной.Чтобы избежать этой ошибки, надо убедиться, что возвращаемый массив действительно соответствует требуемому типу, который ожидает ваша функция. В данном случае необходимо использовать деструктуризацию, как я описал ранее, или указать тип для вашего возвращаемого массива, чтобы TypeScript понимал, какие именно значения и в каком порядке он получит.
Если вы все же хотите использовать spread, в коде
getArgumentsубедитесь, что вы возвращаете массив правильного типа. Вот как это можно сделать, чтобы указать правильный тип:Пример кода
type GetArgumentsReturnType = [ IPoint, // fromAbsolute IPoint, // toAbsolute string | number, // fromId string | number, // toId number, // scale IPoint, // stagePoint Array<{ x: number; y: number; width: number; height: number; id: string | number }> // obstacles ]; const getArguments = (): GetArgumentsReturnType | undefined => { const layer = groupRef.current?.getLayer(); // Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } return [ { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ]; }; // Вызов функции const args = getArguments(); if (args) { const type = getConnectionType(...args); }Объяснение:
- Тип возвращаемого значения: Мы создаем тип
GetArgumentsReturnType, который представляет ваш массив, содержащий значения, которые ожидает функцияgetConnectionType. - Код
getArguments: Возвращаем массив, который соответствует нашему типу. - Использование spread: Теперь, когда
getArgumentsвозвращает массив с корректным типом, вы можете безопасно использовать оператор spread.
Примечание
Убедитесь, что у вас есть все необходимые импорты и типы в вашей области видимости, а также что вы обрабатываете все возможные случаи, включая возможность
undefined, когда ни один родитель не найден. - Тип возвращаемого значения: Мы создаем тип
- User
у меня есть вот такой код import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Group, Line, Rect } from 'react-konva'; import { IPoint } from '../models/infrastucture/point'; import Konva from 'konva'; import { Subject, tap } from 'rxjs'; import { LinePrimitive } from '../models/primitives/primitives'; import { useSelectionStore } from '../store'; import { useStageInteractionContext } from '../hooks/useStageInteractionContext'; import { calculateLinePoints, findParentPrimitiveOfConnector } from '../utils/calculateLinePoints'; import { getObstacles } from '../utils/getObstacles'; import { useDocumentContext } from '../hooks/useDocumentContext'; import withSnap from '../hoc/withSnap'; import { connectorPosition } from '../hooks/useSnap'; import Shape = Konva.Shape; import Stage = Konva.Stage; import KonvaEventObject = Konva.KonvaEventObject; import { break } from '../components/GraphEditor'; import { ConnectionTypes, getConnectionType } from '../utils/getConnectionType';
const pointsSource = new Subject<{ id: string | number; pageId: string | number; points: number[] }>(); export const points$ = pointsSource.asObservable();
// Разделение точек на сегменты interface Segment { start: IPoint; end: IPoint; index: number; isVertical: boolean; isHorizontal: boolean; points: number[]; center: IPoint; }
interface SnapConnectionLineProps extends LinePrimitive { connectionId: string | number; sourceId: string | number; targetId: string | number; isExporting?: boolean; }
const SnapConnectionLine: React.FC = (props) => { const ref = useRef<Shape | Stage | null>(null); const [statePoints, setStatePoints] = useState<number[]>(props.points); const initialPointerPosition = useRef<{ x: number; y: number } | null>(null); const [hoveredSegmentIndex, setHoveredSegmentIndex] = useState<number | null>(null); const [segments, setSegments] = useState<Segment[]>([]); const editorDocument = useDocumentContext();
const stageInteraction = useStageInteractionContext(); const groupRef = useRef<Konva.Group | null>(null); const { selectedIds, setSelectedIds } = useSelectionStore(); const [color, setColor] = useState(props.strokeColor); const [connectionType, setConnectionType] = useState<ConnectionTypes | null>(null);
const calculateSegments = useCallback( (points: number[]) => { // Преобразование массива чисел в массив объектов IPoint const pointObjects: IPoint[] = []; for (let i = 0; i < points.length; i += 2) { pointObjects.push({ x: points[i], y: points[i + 1] }); }
const newSegments: Segment[] = []; for (let i = 0; i < pointObjects.length - 1; i++) { const start = pointObjects[i]; const end = pointObjects[i + 1]; const isVertical = start.x === end.x; const isHorizontal = start.y === end.y; const points = [start.x, start.y, end.x, end.y]; const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2, }; newSegments.push({ start, end, index: i, isVertical, isHorizontal, points, center }); } setSegments(newSegments); }, [statePoints],);
useEffect(() => { setStatePoints(props.points); }, [props.points]);
useEffect(() => { calculateSegments(statePoints); }, [statePoints]);
useLayoutEffect(() => { updateConnectionSegments(); }, []);
const getPointerPosition = (e: KonvaEventObject): IPoint => { const stage = e.target.getStage(); if (!stage || !initialPointerPosition.current) return { x: 0, y: 0 };
const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return { x: 0, y: 0 }; } const scale = stage.scaleX(); const stagePosition = stage.position(); return { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, };};
const updateConnectionSegments = useCallback(() => { const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } const type = getConnectionType( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ); if (type === connectionType) { setConnectionType(type); return; } else { // Рассчитаем точки для линии, если оба родителя и позиции найдены const newPoints = calculateLinePoints( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ); pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); setConnectionType(type); }}, [ editorDocument.activePage?.id, stageInteraction.scale, stageInteraction.point, connectionType, props.sourceId, props.targetId, props.id, ]);
const handleClick = (e: Konva.KonvaEventObject) => { e.evt.preventDefault(); e.currentTarget.stopDrag();
const id = e.currentTarget.id(); if (e.evt.ctrlKey || e.evt.metaKey) { const isSelected = selectedIds.includes(id); if (isSelected) { setSelectedIds(selectedIds.filter((x) => x !== id)); } else { setSelectedIds([...selectedIds, id]); } } else { setSelectedIds([id]); }};
useEffect(() => { setColor( selectedIds.some((id) => id.toString().includes(props.id.toString())) ? '#0099D3' : (props.strokeColor ?? 'black'), ); }, [props.id, props.strokeColor, selectedIds]);
useEffect(() => { const subscription = connectorPosition$ .pipe( tap(() => { updateConnectionSegments(); }), ) .subscribe({ error: (err) => console.log(err) });
return () => subscription.unsubscribe();}, [updateConnectionSegments]);
/**
-
Обработчик добавления излома */ useEffect(() => { const subscription = break$.subscribe(({ id, position }) => { const match = id.toString().match(/connection-([a-zA-Z0-9\-]+)-segment-(\d+)/); if (!match || match.length < 3) { return; } const connectionId = match[1]; const segmentIndex = parseInt(match[2]);
if (connectionId !== props.id) { return; } const segment = segments[segmentIndex];
// Обновляем точки линии связи setStatePoints((prevPoints) => { const newPoints = [...prevPoints];
if (!editorDocument.activePage || !editorDocument.activePage.width || !editorDocument.activePage.height) { return newPoints; }
// Добавляем излом if (segment.isVertical) { // Для вертикального сегмента добавляем горизонтальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = position.x + 20 < editorDocument.activePage.width ? 20 : -20; const deltaY = segment.start.y > segment.end.y ? -20 : 20; newPoints.splice( 2 * (segmentIndex + 1), 0, segment.start.x, position.y, segment.start.x + deltaX, position.y, segment.start.x + deltaX, position.y + deltaY, segment.start.x, position.y + deltaY, ); } else { // Для горизонтального сегмента добавляем вертикальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = segment.start.x > segment.end.x ? -20 : 20; const deltaY = position.y - 20 < 0 ? 20 : -20; newPoints.splice( 2 * (segmentIndex + 1), 0, position.x, segment.start.y, position.x, segment.start.y + deltaY, position.x + deltaX, segment.start.y + deltaY, position.x + deltaX, segment.start.y, ); }
pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); return newPoints; }); });
return () => {subscription.unsubscribe(); };}, [editorDocument.activePage, props.id, segments, statePoints]);
return ( <> {segments.map((segment) => { const isFirst = segment.index === 0; const isLast = segment.index === segments.length - 1; const isDraggable = !isFirst && !isLast;
return ( <Group onClick={handleClick} ref={(ref) => { if (!groupRef.current) { groupRef.current = ref; } }} targetId={props.targetId} sourceId={props.sourceId} id={`connection-${props.id}-segment-${segment.index}`} key={`group-${props.connectionId}-${segment.index}`} onMouseEnter={() => setHoveredSegmentIndex(segment.index)} onMouseLeave={() => setHoveredSegmentIndex((prev) => (prev === segment.index ? null : prev))} > <Line {...props} stroke={color} points={segment.points} hitStrokeWidth={20} strokeScaleEnabled={false} draggable={false} /> {isDraggable && hoveredSegmentIndex === segment.index && ( <Rect x={segment.center.x - 5} y={segment.center.y - 5} width={10} height={10} fill='green' draggable onDragStart={(e) => { ref.current = e.target; const stage = e.target.getStage(); if (stage) { const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return; } const scale = stage.scaleX(); // Предполагаем, что scaleX === scaleY const stagePosition = stage.position(); // Преобразуем координаты указателя в координаты модели initialPointerPosition.current = { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, }; } }} onDragEnd={() => { if (editorDocument.activePage) { pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: statePoints }); const isEdited = new Map<string | number, boolean>(); isEdited.set(props.id, true); //addIsConnectionsEdited(isEdited); } ref.current = null; initialPointerPosition.current = null; setHoveredSegmentIndex(null); }} onDragMove={(e) => { if (!initialPointerPosition.current) { return; } const currentPointerPosition = getPointerPosition(e); if (currentPointerPosition.x < 0) currentPointerPosition.x = 0; if (editorDocument.activePage?.width && currentPointerPosition.x > editorDocument.activePage?.width) currentPointerPosition.x = editorDocument.activePage?.width; if (currentPointerPosition.y < 0) currentPointerPosition.y = 0; if (editorDocument.activePage?.height && currentPointerPosition.y > editorDocument.activePage?.height) currentPointerPosition.y = editorDocument.activePage?.height; // Вычисляем дельту перемещения в координатах модели const deltaX = currentPointerPosition.x - initialPointerPosition.current.x; const deltaY = currentPointerPosition.y - initialPointerPosition.current.y; const isVertical = segment.isVertical; const delta = isVertical ? deltaX : deltaY; // Обновляем точки линии setStatePoints((prevPoints) => { if (!editorDocument.activePage?.id) { return prevPoints; } const newPointsArray = [...prevPoints]; if (isVertical) { // Обновляем координаты x начальной и конечной точек сегмента newPointsArray[2 * segment.index] += delta; // x1 newPointsArray[2 * (segment.index + 1)] += delta; // x2 } else { // Обновляем координаты y начальной и конечной точек сегмента newPointsArray[2 * segment.index + 1] += delta; // y1 newPointsArray[2 * (segment.index + 1) + 1] += delta; // y2 } setStatePoints(newPointsArray); return newPointsArray; }); // Обновляем начальную позицию указателя для следующего шага initialPointerPosition.current = currentPointerPosition; // Сбрасываем позицию маркера e.target.setAttrs({ x: segment.center.x - 5, y: segment.center.y - 5, }); }} /> )} </Group> ); })} </>); };
// Устанавливаем displayName для SnapConnectionLine SnapConnectionLine.displayName = 'SnapConnectionLine';
export default withSnap<SnapConnectionLineProps, Konva.Group>(SnapConnectionLine);
мне надо сделать так, чтобы связь переисовывалась при перетягивании только если изменился ее тип. в противном случае мне надо чтобы при перемщении по вертикали растягивался только ближайший вертикальный сегмент при перемещении по горизонтали -- ближайший горизонтальный сегмент там есть условие для этого но в нем пока что ничего не происходит сделай это
-
- Assistant
Чтобы реализовать поведение, при котором связь переиспысывается только при изменении её типа, и при этом при перемещении по вертикали растягивается только ближайший вертикальный сегмент, а при перемещении по горизонтали — ближайший горизонтальный сегмент, нам нужно внести изменения в обработчик
onDragMoveкомпонентаRect, который отвечает за перетаскивание излома.Основные шаги:
- Найти ближайший сегмент (горизонтальный или вертикальный), который должен быть изменен в зависимости от направления движения.
- В случае, если тип связи изменился, пересчитать все точки и обновить состояние; в противном случае, обновить только ближайший сегмент.
Вот как вы можете внести изменения в ваш код:
onDragMove={(e) => { if (!initialPointerPosition.current) { return; } const currentPointerPosition = getPointerPosition(e); // Ограничиваем положение указателя по границам страницы const { width, height } = editorDocument.activePage || {}; if (currentPointerPosition.x < 0) currentPointerPosition.x = 0; if (width && currentPointerPosition.x > width) currentPointerPosition.x = width; if (currentPointerPosition.y < 0) currentPointerPosition.y = 0; if (height && currentPointerPosition.y > height) currentPointerPosition.y = height; // Вычисляем дельту перемещения в координатах модели const deltaX = currentPointerPosition.x - initialPointerPosition.current.x; const deltaY = currentPointerPosition.y - initialPointerPosition.current.y; const isVertical = segment.isVertical; const isDraggingVertically = Math.abs(deltaY) > Math.abs(deltaX); // Определяем, больше ли перемещение по вертикали const newSegments = [...segments]; let typeChanged = false; if (isDraggingVertically && isVertical) { // Изменяем ближайший вертикальный сегмент const closestSegmentIndex = newSegments.findIndex(seg => seg.isVertical); if (closestSegmentIndex !== -1) { newSegments[closestSegmentIndex].start.y += deltaY; newSegments[closestSegmentIndex].end.y += deltaY; } } else if (!isDraggingVertically && !isVertical) { // Изменяем ближайший горизонтальный сегмент const closestSegmentIndex = newSegments.findIndex(seg => seg.isHorizontal); if (closestSegmentIndex !== -1) { newSegments[closestSegmentIndex].start.x += deltaX; newSegments[closestSegmentIndex].end.x += deltaX; } } else { // Если переключаем по типу typeChanged = true; if (isVertical) { newSegments[segment.index].start.y += deltaY; newSegments[segment.index].end.y += deltaY; } else { newSegments[segment.index].start.x += deltaX; newSegments[segment.index].end.x += deltaX; } } // Обновляем состояние с новыми сегментами setSegments(newSegments); // Если тип изменился, пересчитываем точки линии if (typeChanged) { const layer = groupRef.current?.getLayer(); const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); if (sourceParentPosition && targetParentPosition) { const newPoints = calculateLinePoints( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ); pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); } } // Обновляем начальную позицию указателя для следующего шага initialPointerPosition.current = currentPointerPosition; // Сбрасываем позицию маркера (опционально) e.target.setAttrs({ x: segment.center.x - 5, y: segment.center.y - 5, }); }}Изменения и объяснения:
- Выбор ближайшего сегмента: Мы используем
findIndexдля поиска ближайшего вертикального или горизонтального сегмента в зависимости от направления движения. Если сегмент найден, его координаты обновляются. - Проверка изменения типа: Если происходит переключение между вертикальным и горизонтальным перемещением, флаг
typeChangedустанавливается вtrue, что означает, что необходимо пересчитать точки и обновить соединение. - Пересчет линии: Если
typeChangedравноtrue, выполняется пересчет линий и обновление состояния.
Эти изменения позволят вам добиться необходимого поведения: если тип соединения не изменился, обновляется только ближайший сегмент, а если изменился — пересчитывается вся линия.
- User
нет не правильно у меня все подготовлено в функции апдейт сегментс вот тут if (type === connectionType) { setConnectionType(type); return; мне надо дописать продление последнего сегмента
- Assistant
Понял, давайте обновим вашу функцию
updateConnectionSegments, чтобы продлить последний сегмент только в том случае, если тип соединения не изменился. Если тип соединения не изменится, то, если будет перемещён сегмент (по горизонтали или вертикали), нужно растянуть только последний сегмент. В противном случае, если тип соединения изменится, пойдет полное обновление всех сегментов.Вот как можно изменить вашу функцию:
const updateConnectionSegments = useCallback(() => { const layer = groupRef.current?.getLayer(); // Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } const type = getConnectionType( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ); if (type === connectionType) { // Если тип не изменился, продолжаем последний сегмент const lastSegmentIndex = segments.length - 1; if (lastSegmentIndex >= 0) { const lastSegment = segments[lastSegmentIndex]; // Обновляем точки последнего сегмента в зависимости от его ориентации if (lastSegment.isVertical) { lastSegment.end.y = targetParentPosition.y; // Растянуть по y, если последний сегмент вертикальный } else if (lastSegment.isHorizontal) { lastSegment.end.x = targetParentPosition.x; // Растянуть по x, если последний сегмент горизонтальный } // Обновляем состояние с новыми координатами setStatePoints((prevPoints) => { const newPoints = [...prevPoints]; newPoints[2 * lastSegmentIndex + 1] = lastSegment.end.y; // Обновляем y конца последнего сегмента newPoints[2 * (lastSegmentIndex + 1)] = lastSegment.end.x; // Обновляем x конца последнего сегмента return newPoints; }); } setConnectionType(type); return; } else { // Если тип изменился, пересчитываем точки const newPoints = calculateLinePoints( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), ); pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); setConnectionType(type); } }, [ editorDocument.activePage?.id, stageInteraction.scale, stageInteraction.point, connectionType, props.sourceId, props.targetId, props.id, ]);Объяснение изменений
-
Обновление последнего сегмента: Если тип соединения не изменился, и у нас есть текущий сегмент, мы проверяем его ориентацию (горизонтальная или вертикальная) и обновляем его координаты (
end.xилиend.y) в зависимости от перемещения. -
Обновление состояния точек: Если сегмент был обновлён, мы вызываем
setStatePoints, чтобы обновить массивpoints, где мы изменяем y или x конца последнего сегмента. -
Проверка на изменение типа: Если тип соединения изменился, то вызываем пересчет всех точек с помощью
calculateLinePoints, чтобы обновить все сегменты.
Эти изменения помогут вам добиться требуемого поведения: при перемещении по горизонтали или вертикали растягивается только ближайший сегмент, если тип связи не изменился, и в противном случае происходит пересчет всей линии.
-
- User
у меня есть вот такой код import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Group, Line, Rect } from 'react-konva'; import { IPoint } from '../models/infrastucture/point'; import Konva from 'konva'; import { Subject, tap } from 'rxjs'; import { LinePrimitive } from '../models/primitives/primitives'; import { useSelectionStore } from '../store'; import { useStageInteractionContext } from '../hooks/useStageInteractionContext'; import { calculateUpdatedLinePoints, findParentPrimitiveOfConnector } from '../utils/calculateLinePoints'; import { getObstacles } from '../utils/getObstacles'; import { useDocumentContext } from '../hooks/useDocumentContext'; import withSnap from '../hoc/withSnap'; import { connectorPosition } from '../hooks/useSnap'; import { break } from '../components/GraphEditor'; import { ConnectionTypes } from '../utils/getConnectionType'; import Shape = Konva.Shape; import Stage = Konva.Stage; import KonvaEventObject = Konva.KonvaEventObject;
const pointsSource = new Subject<{ id: string | number; pageId: string | number; points: number[] }>(); export const points$ = pointsSource.asObservable();
// Разделение точек на сегменты interface Segment { start: IPoint; end: IPoint; index: number; isVertical: boolean; isHorizontal: boolean; points: number[]; center: IPoint; }
interface SnapConnectionLineProps extends LinePrimitive { connectionId: string | number; sourceId: string | number; targetId: string | number; isExporting?: boolean; }
const SnapConnectionLine: React.FC = (props) => { const ref = useRef<Shape | Stage | null>(null); const [statePoints, setStatePoints] = useState<number[]>(props.points); const initialPointerPosition = useRef<{ x: number; y: number } | null>(null); const [hoveredSegmentIndex, setHoveredSegmentIndex] = useState<number | null>(null); const [segments, setSegments] = useState<Segment[]>([]); const editorDocument = useDocumentContext();
const stageInteraction = useStageInteractionContext(); const groupRef = useRef<Konva.Group | null>(null); const { selectedIds, setSelectedIds } = useSelectionStore(); const [color, setColor] = useState(props.strokeColor); const [connectionType, setConnectionType] = useState<ConnectionTypes | null>(null);
const calculateSegments = useCallback( (points: number[]) => { // Преобразование массива чисел в массив объектов IPoint const pointObjects: IPoint[] = []; for (let i = 0; i < points.length; i += 2) { pointObjects.push({ x: points[i], y: points[i + 1] }); }
const newSegments: Segment[] = []; for (let i = 0; i < pointObjects.length - 1; i++) { const start = pointObjects[i]; const end = pointObjects[i + 1]; const isVertical = start.x === end.x; const isHorizontal = start.y === end.y; const points = [start.x, start.y, end.x, end.y]; const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2, }; newSegments.push({ start, end, index: i, isVertical, isHorizontal, points, center }); } setSegments(newSegments); }, [statePoints],);
useEffect(() => { setStatePoints(props.points); }, [props.points]);
useEffect(() => { calculateSegments(statePoints); }, [statePoints]);
useLayoutEffect(() => { updateConnectionSegments(); }, []);
const getPointerPosition = (e: KonvaEventObject): IPoint => { const stage = e.target.getStage(); if (!stage || !initialPointerPosition.current) return { x: 0, y: 0 };
const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return { x: 0, y: 0 }; } const scale = stage.scaleX(); const stagePosition = stage.position(); return { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, };};
const updateConnectionSegments = useCallback( (connectorsPositions?: Map<string | number, IPoint>) => { const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } if (!connectorsPositions) return; const sourcePosition = connectorsPositions.get(props.sourceId); const targetPosition = connectorsPositions.get(props.targetId); if (!sourcePosition && !targetPosition) { return; } const updatedConnectorsIds: (string | number)[] = []; if (sourcePosition) updatedConnectorsIds.push(props.sourceId); if (targetPosition) updatedConnectorsIds.push(props.targetId); const newPoints = calculateUpdatedLinePoints( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, props.sourceId, props.targetId, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), connectionType, statePoints, updatedConnectorsIds, ); setStatePoints(newPoints.points); pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints.points }); setConnectionType(newPoints.type); return; }, [ editorDocument.activePage?.id, stageInteraction.scale, stageInteraction.point, connectionType, props.sourceId, props.targetId, props.id, segments, ],);
const handleClick = (e: Konva.KonvaEventObject) => { e.evt.preventDefault(); e.currentTarget.stopDrag();
const id = e.currentTarget.id(); if (e.evt.ctrlKey || e.evt.metaKey) { const isSelected = selectedIds.includes(id); if (isSelected) { setSelectedIds(selectedIds.filter((x) => x !== id)); } else { setSelectedIds([...selectedIds, id]); } } else { setSelectedIds([id]); }};
useEffect(() => { setColor( selectedIds.some((id) => id.toString().includes(props.id.toString())) ? '#0099D3' : (props.strokeColor ?? 'black'), ); }, [props.id, props.strokeColor, selectedIds]);
useEffect(() => { const subscription = connectorPosition$ .pipe( tap((connectorsPositions) => { updateConnectionSegments(connectorsPositions); }), ) .subscribe({ error: (err) => console.log(err) });
return () => subscription.unsubscribe();}, [updateConnectionSegments]);
/**
-
Обработчик добавления излома */ useEffect(() => { const subscription = break$.subscribe(({ id, position }) => { const match = id.toString().match(/connection-([a-zA-Z0-9\-]+)-segment-(\d+)/); if (!match || match.length < 3) { return; } const connectionId = match[1]; const segmentIndex = parseInt(match[2]);
if (connectionId !== props.id) { return; } const segment = segments[segmentIndex];
// Обновляем точки линии связи setStatePoints((prevPoints) => { const newPoints = [...prevPoints];
if (!editorDocument.activePage || !editorDocument.activePage.width || !editorDocument.activePage.height) { return newPoints; }
// Добавляем излом if (segment.isVertical) { // Для вертикального сегмента добавляем горизонтальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = position.x + 20 < editorDocument.activePage.width ? 20 : -20; const deltaY = segment.start.y > segment.end.y ? -20 : 20; newPoints.splice( 2 * (segmentIndex + 1), 0, segment.start.x, position.y, segment.start.x + deltaX, position.y, segment.start.x + deltaX, position.y + deltaY, segment.start.x, position.y + deltaY, ); } else { // Для горизонтального сегмента добавляем вертикальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = segment.start.x > segment.end.x ? -20 : 20; const deltaY = position.y - 20 < 0 ? 20 : -20; newPoints.splice( 2 * (segmentIndex + 1), 0, position.x, segment.start.y, position.x, segment.start.y + deltaY, position.x + deltaX, segment.start.y + deltaY, position.x + deltaX, segment.start.y, ); }
pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); return newPoints; }); });
return () => {subscription.unsubscribe(); };}, [editorDocument.activePage, props.id, segments, statePoints]);
return ( <> {segments.map((segment) => { const isFirst = segment.index === 0; const isLast = segment.index === segments.length - 1; const isDraggable = !isFirst && !isLast;
return ( <Group onClick={handleClick} ref={(ref) => { if (!groupRef.current) { groupRef.current = ref; } }} targetId={props.targetId} sourceId={props.sourceId} id={`connection-${props.id}-segment-${segment.index}`} key={`group-${props.connectionId}-${segment.index}`} onMouseEnter={() => setHoveredSegmentIndex(segment.index)} onMouseLeave={() => setHoveredSegmentIndex((prev) => (prev === segment.index ? null : prev))} > <Line {...props} stroke={color} points={segment.points} hitStrokeWidth={20} strokeScaleEnabled={false} draggable={false} /> {isDraggable && hoveredSegmentIndex === segment.index && ( <Rect x={segment.center.x - 5} y={segment.center.y - 5} width={10} height={10} fill='green' draggable onDragStart={(e) => { ref.current = e.target; const stage = e.target.getStage(); if (stage) { const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return; } const scale = stage.scaleX(); // Предполагаем, что scaleX === scaleY const stagePosition = stage.position(); // Преобразуем координаты указателя в координаты модели initialPointerPosition.current = { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, }; } }} onDragEnd={() => { if (editorDocument.activePage) { pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: statePoints }); const isEdited = new Map<string | number, boolean>(); isEdited.set(props.id, true); //addIsConnectionsEdited(isEdited); } ref.current = null; initialPointerPosition.current = null; setHoveredSegmentIndex(null); }} onDragMove={(e) => { if (!initialPointerPosition.current) { return; } const currentPointerPosition = getPointerPosition(e); if (currentPointerPosition.x < 0) currentPointerPosition.x = 0; if (editorDocument.activePage?.width && currentPointerPosition.x > editorDocument.activePage?.width) currentPointerPosition.x = editorDocument.activePage?.width; if (currentPointerPosition.y < 0) currentPointerPosition.y = 0; if (editorDocument.activePage?.height && currentPointerPosition.y > editorDocument.activePage?.height) currentPointerPosition.y = editorDocument.activePage?.height; // Вычисляем дельту перемещения в координатах модели const deltaX = currentPointerPosition.x - initialPointerPosition.current.x; const deltaY = currentPointerPosition.y - initialPointerPosition.current.y; const isVertical = segment.isVertical; const delta = isVertical ? deltaX : deltaY; // Обновляем точки линии setStatePoints((prevPoints) => { if (!editorDocument.activePage?.id) { return prevPoints; } const newPointsArray = [...prevPoints]; if (isVertical) { // Обновляем координаты x начальной и конечной точек сегмента newPointsArray[2 * segment.index] += delta; // x1 newPointsArray[2 * (segment.index + 1)] += delta; // x2 } else { // Обновляем координаты y начальной и конечной точек сегмента newPointsArray[2 * segment.index + 1] += delta; // y1 newPointsArray[2 * (segment.index + 1) + 1] += delta; // y2 } setStatePoints(newPointsArray); return newPointsArray; }); // Обновляем начальную позицию указателя для следующего шага initialPointerPosition.current = currentPointerPosition; // Сбрасываем позицию маркера e.target.setAttrs({ x: segment.center.x - 5, y: segment.center.y - 5, }); }} /> )} </Group> ); })} </>); };
// Устанавливаем displayName для SnapConnectionLine SnapConnectionLine.displayName = 'SnapConnectionLine';
export default withSnap<SnapConnectionLineProps, Konva.Group>(SnapConnectionLine);
но у меня есть проблема. после перезагрузки старницы в connectionType лежит налл и первый раз связь всегда будет перерисована useLayoutEffect(() => { updateConnectionSegments(); }, []); вот это не работает потому что во время вызова лэер не определен что делать?
-
- Assistant
Если у вас есть проблема с тем, что
connectionTypeравноnullпосле перезагрузки страницы и нужно, чтобы связь не перерисовывалась, вы можете использовать несколько подходов, чтобы гарантировать, что состояниеconnectionTypeустанавливается корректно, прежде чем вы вызываете функциюupdateConnectionSegments.Вот несколько способов, как это можно сделать:
Способ 1: Добавить проверку на наличие Layer
Вы можете добавить логику проверки на наличие
layerвupdateConnectionSegments, а также выполнить функцию только тогда, когда все необходимые данные (включаяlayerиconnectionType) существуют.useLayoutEffect(() => { const layer = groupRef.current?.getLayer(); if (layer && editorDocument.activePage?.id) { updateConnectionSegments(); } }, [editorDocument.activePage?.id, updateConnectionSegments]);Способ 2: Использовать состояние для управления вызовом функции
Вы можете использовать локальное состояние для управления вызовом
updateConnectionSegments, чтобы дождаться установки всех необходимых данных, прежде чем делать вычисления.const [shouldUpdate, setShouldUpdate] = useState(false); useEffect(() => { if (editorDocument.activePage) { setShouldUpdate(true); } }, [editorDocument.activePage]); useLayoutEffect(() => { if (shouldUpdate) { updateConnectionSegments(); setShouldUpdate(false); // Сбросить состояние после первого вызова } }, [shouldUpdate, updateConnectionSegments]);Способ 3: Вызов
updateConnectionSegmentsвconnectorPosition$Если
connectorPosition$вызывается сразу после загрузки страницы и содержит значения дляconnectorsPositions, вы можете добавить вызовupdateConnectionSegmentsпрямо в обработчикtap:useEffect(() => { const subscription = connectorPosition$ .pipe( tap((connectorsPositions) => { updateConnectionSegments(connectorsPositions); }), ) .subscribe({ error: (err) => console.log(err) }); return () => subscription.unsubscribe(); }, [updateConnectionSegments]);Способ 4: Инициализация типа соединения
Если вы хотите избежать перерисовки на первом рендере, вы можете добавить инициализацию
connectionType, чтобы установить его в "созданный" тип на основе текущих соединений вuseLayoutEffect.useLayoutEffect(() => { const layer = groupRef.current?.getLayer(); if (layer && editorDocument.activePage?.id) { // Логика, чтобы инициализировать connectionType на основании текущих соединений const initialType = getInitialConnectionType(); // Ваш метод для получения начального типа соединения setConnectionType(initialType); updateConnectionSegments(); } }, [editorDocument.activePage?.id, updateConnectionSegments]);Заключение
Выберите тот метод, который лучше всего соответствует вашему коду и логике приложения. Важно, чтобы данные были готовы к моменту, когда происходит вызов функций, чтобы избежать перерисовки соединений или неправильных значений в состоянии.
- User
вот тут я сделала зависимость от груп реф import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Group, Line, Rect } from 'react-konva'; import { IPoint } from '../models/infrastucture/point'; import Konva from 'konva'; import { Subject, tap } from 'rxjs'; import { LinePrimitive } from '../models/primitives/primitives'; import { useSelectionStore } from '../store'; import { useStageInteractionContext } from '../hooks/useStageInteractionContext'; import { calculateUpdatedLinePoints, findParentPrimitiveOfConnector } from '../utils/calculateLinePoints'; import { getObstacles } from '../utils/getObstacles'; import { useDocumentContext } from '../hooks/useDocumentContext'; import withSnap from '../hoc/withSnap'; import { connectorPosition } from '../hooks/useSnap'; import { break } from '../components/GraphEditor'; import { ConnectionTypes } from '../utils/getConnectionType'; import Shape = Konva.Shape; import Stage = Konva.Stage; import KonvaEventObject = Konva.KonvaEventObject;
const pointsSource = new Subject<{ id: string | number; pageId: string | number; points: number[] }>(); export const points$ = pointsSource.asObservable();
// Разделение точек на сегменты interface Segment { start: IPoint; end: IPoint; index: number; isVertical: boolean; isHorizontal: boolean; points: number[]; center: IPoint; }
interface SnapConnectionLineProps extends LinePrimitive { connectionId: string | number; sourceId: string | number; targetId: string | number; isExporting?: boolean; }
const SnapConnectionLine: React.FC = (props) => { const ref = useRef<Shape | Stage | null>(null); const [statePoints, setStatePoints] = useState<number[]>(props.points); const initialPointerPosition = useRef<{ x: number; y: number } | null>(null); const [hoveredSegmentIndex, setHoveredSegmentIndex] = useState<number | null>(null); const [segments, setSegments] = useState<Segment[]>([]); const editorDocument = useDocumentContext();
const stageInteraction = useStageInteractionContext(); const groupRef = useRef<Konva.Group | null>(null); const { selectedIds, setSelectedIds } = useSelectionStore(); const [color, setColor] = useState(props.strokeColor); const [connectionType, setConnectionType] = useState<ConnectionTypes | null>(null);
const calculateSegments = useCallback( (points: number[]) => { // Преобразование массива чисел в массив объектов IPoint const pointObjects: IPoint[] = []; for (let i = 0; i < points.length; i += 2) { pointObjects.push({ x: points[i], y: points[i + 1] }); }
const newSegments: Segment[] = []; for (let i = 0; i < pointObjects.length - 1; i++) { const start = pointObjects[i]; const end = pointObjects[i + 1]; const isVertical = start.x === end.x; const isHorizontal = start.y === end.y; const points = [start.x, start.y, end.x, end.y]; const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2, }; newSegments.push({ start, end, index: i, isVertical, isHorizontal, points, center }); } setSegments(newSegments); }, [statePoints],);
useEffect(() => { setStatePoints(props.points); }, [props.points]);
useEffect(() => { calculateSegments(statePoints); }, [statePoints]);
// const [layer, setLayer] = useState(); useLayoutEffect(() => { updateConnectionSegments(); }, [groupRef, groupRef.current]);
const getPointerPosition = (e: KonvaEventObject): IPoint => { const stage = e.target.getStage(); if (!stage || !initialPointerPosition.current) return { x: 0, y: 0 };
const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return { x: 0, y: 0 }; } const scale = stage.scaleX(); const stagePosition = stage.position(); return { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, };};
const updateConnectionSegments = useCallback( (connectorsPositions?: Map<string | number, IPoint>) => { const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует if (!layer || !editorDocument.activePage?.id) { return; } // Найдем позиции примитивов, которым принадлежат коннекторы const sourceParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.sourceId)) .find((result) => result !== null); const targetParentPosition = layer.children .map((primitive) => findParentPrimitiveOfConnector(primitive, primitive.id(), props.targetId)) .find((result) => result !== null); // Если ни один из родителей не найден, выход if (!sourceParentPosition || !targetParentPosition) { return; } if (!connectorsPositions) return; const sourcePosition = connectorsPositions.get(props.sourceId); const targetPosition = connectorsPositions.get(props.targetId); if (!sourcePosition && !targetPosition) { return; } const updatedConnectorsIds: (string | number)[] = []; if (sourcePosition) updatedConnectorsIds.push(props.sourceId); if (targetPosition) updatedConnectorsIds.push(props.targetId); const newPoints = calculateUpdatedLinePoints( { x: sourceParentPosition.x, y: sourceParentPosition.y }, { x: targetParentPosition.x, y: targetParentPosition.y }, props.sourceId, props.targetId, sourceParentPosition.id, targetParentPosition.id, stageInteraction.scale, stageInteraction.point, getObstacles(layer), connectionType, statePoints, updatedConnectorsIds, ); setStatePoints(newPoints.points); pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints.points }); setConnectionType(newPoints.type); return; }, [ editorDocument.activePage?.id, stageInteraction.scale, stageInteraction.point, connectionType, props.sourceId, props.targetId, props.id, segments, ],);
const handleClick = (e: Konva.KonvaEventObject) => { e.evt.preventDefault(); e.currentTarget.stopDrag();
const id = e.currentTarget.id(); if (e.evt.ctrlKey || e.evt.metaKey) { const isSelected = selectedIds.includes(id); if (isSelected) { setSelectedIds(selectedIds.filter((x) => x !== id)); } else { setSelectedIds([...selectedIds, id]); } } else { setSelectedIds([id]); }};
useEffect(() => { setColor( selectedIds.some((id) => id.toString().includes(props.id.toString())) ? '#0099D3' : (props.strokeColor ?? 'black'), ); }, [props.id, props.strokeColor, selectedIds]);
useEffect(() => { const subscription = connectorPosition$ .pipe( tap((connectorsPositions) => { updateConnectionSegments(connectorsPositions); }), ) .subscribe({ error: (err) => console.log(err) });
return () => subscription.unsubscribe();}, [updateConnectionSegments]);
/**
-
Обработчик добавления излома */ useEffect(() => { const subscription = break$.subscribe(({ id, position }) => { const match = id.toString().match(/connection-([a-zA-Z0-9\-]+)-segment-(\d+)/); if (!match || match.length < 3) { return; } const connectionId = match[1]; const segmentIndex = parseInt(match[2]);
if (connectionId !== props.id) { return; } const segment = segments[segmentIndex];
// Обновляем точки линии связи setStatePoints((prevPoints) => { const newPoints = [...prevPoints];
if (!editorDocument.activePage || !editorDocument.activePage.width || !editorDocument.activePage.height) { return newPoints; }
// Добавляем излом if (segment.isVertical) { // Для вертикального сегмента добавляем горизонтальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = position.x + 20 < editorDocument.activePage.width ? 20 : -20; const deltaY = segment.start.y > segment.end.y ? -20 : 20; newPoints.splice( 2 * (segmentIndex + 1), 0, segment.start.x, position.y, segment.start.x + deltaX, position.y, segment.start.x + deltaX, position.y + deltaY, segment.start.x, position.y + deltaY, ); } else { // Для горизонтального сегмента добавляем вертикальный отрезок. // Выбираем смещение с учетом границ листа и координат начала и конца сегмента const deltaX = segment.start.x > segment.end.x ? -20 : 20; const deltaY = position.y - 20 < 0 ? 20 : -20; newPoints.splice( 2 * (segmentIndex + 1), 0, position.x, segment.start.y, position.x, segment.start.y + deltaY, position.x + deltaX, segment.start.y + deltaY, position.x + deltaX, segment.start.y, ); }
pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: newPoints }); return newPoints; }); });
return () => {subscription.unsubscribe(); };}, [editorDocument.activePage, props.id, segments, statePoints]);
return ( <> {segments.map((segment) => { const isFirst = segment.index === 0; const isLast = segment.index === segments.length - 1; const isDraggable = !isFirst && !isLast;
return ( <Group onClick={handleClick} ref={(ref) => { if (!groupRef.current) { groupRef.current = ref; } }} targetId={props.targetId} sourceId={props.sourceId} id={`connection-${props.id}-segment-${segment.index}`} key={`group-${props.connectionId}-${segment.index}`} onMouseEnter={() => setHoveredSegmentIndex(segment.index)} onMouseLeave={() => setHoveredSegmentIndex((prev) => (prev === segment.index ? null : prev))} > <Line {...props} stroke={color} points={segment.points} hitStrokeWidth={20} strokeScaleEnabled={false} draggable={false} /> {isDraggable && hoveredSegmentIndex === segment.index && ( <Rect x={segment.center.x - 5} y={segment.center.y - 5} width={10} height={10} fill='green' draggable onDragStart={(e) => { ref.current = e.target; const stage = e.target.getStage(); if (stage) { const pointerPosition = stage.getPointerPosition(); if (!pointerPosition) { return; } const scale = stage.scaleX(); // Предполагаем, что scaleX === scaleY const stagePosition = stage.position(); // Преобразуем координаты указателя в координаты модели initialPointerPosition.current = { x: (pointerPosition.x - stagePosition.x) / scale, y: (pointerPosition.y - stagePosition.y) / scale, }; } }} onDragEnd={() => { if (editorDocument.activePage) { pointsSource.next({ id: props.id, pageId: editorDocument.activePage.id, points: statePoints }); const isEdited = new Map<string | number, boolean>(); isEdited.set(props.id, true); //addIsConnectionsEdited(isEdited); } ref.current = null; initialPointerPosition.current = null; setHoveredSegmentIndex(null); }} onDragMove={(e) => { if (!initialPointerPosition.current) { return; } const currentPointerPosition = getPointerPosition(e); if (currentPointerPosition.x < 0) currentPointerPosition.x = 0; if (editorDocument.activePage?.width && currentPointerPosition.x > editorDocument.activePage?.width) currentPointerPosition.x = editorDocument.activePage?.width; if (currentPointerPosition.y < 0) currentPointerPosition.y = 0; if (editorDocument.activePage?.height && currentPointerPosition.y > editorDocument.activePage?.height) currentPointerPosition.y = editorDocument.activePage?.height; // Вычисляем дельту перемещения в координатах модели const deltaX = currentPointerPosition.x - initialPointerPosition.current.x; const deltaY = currentPointerPosition.y - initialPointerPosition.current.y; const isVertical = segment.isVertical; const delta = isVertical ? deltaX : deltaY; // Обновляем точки линии setStatePoints((prevPoints) => { if (!editorDocument.activePage?.id) { return prevPoints; } const newPointsArray = [...prevPoints]; if (isVertical) { // Обновляем координаты x начальной и конечной точек сегмента newPointsArray[2 * segment.index] += delta; // x1 newPointsArray[2 * (segment.index + 1)] += delta; // x2 } else { // Обновляем координаты y начальной и конечной точек сегмента newPointsArray[2 * segment.index + 1] += delta; // y1 newPointsArray[2 * (segment.index + 1) + 1] += delta; // y2 } setStatePoints(newPointsArray); return newPointsArray; }); // Обновляем начальную позицию указателя для следующего шага initialPointerPosition.current = currentPointerPosition; // Сбрасываем позицию маркера e.target.setAttrs({ x: segment.center.x - 5, y: segment.center.y - 5, }); }} /> )} </Group> ); })} </>); };
// Устанавливаем displayName для SnapConnectionLine SnapConnectionLine.displayName = 'SnapConnectionLine';
export default withSnap<SnapConnectionLineProps, Konva.Group>(SnapConnectionLine);
в теории когда меняется груп реф и там перестает лежать налл функция должна вызываться но этого почему-то не происходит юзэффект срабатывает только раз при старте
-
- Assistant
Если вы хотите, чтобы ваш
useLayoutEffectсрабатывал каждый раз, когдаgroupRefобновляется (и, следовательно, не равенnull), вам потребуется изменить логику использования зависимости.Сейчас вы указали в зависимости
groupRefиgroupRef.current, что в этой форме не будет вызывать эффект при изменении значенияcurrent, так как React не отслеживает изменения свойстваcurrentвuseRef.Как только реф будет установлен, вы должны вызвать
updateConnectionSegments, используя простой подход с проверкой наnull. Давайте изменим ваш код следующим образом:Изменение зависимости
useLayoutEffect(() => { const layer = groupRef.current?.getLayer(); // Убедимся, что layer существует и у нас есть активная страница if (layer && editorDocument.activePage?.id) { updateConnectionSegments(); // Вызов функции при наличии layer } }, [editorDocument.activePage?.id, groupRef.current]); // Убрать groupRef из зависимостиПочему это сработает
-
Проверка layer: Мы проверяем, есть ли у нас валидный
layer, а не проверяем сам реф. Это должно произойти после того, как реф был установлен. -
Условия срабатывания: Когда будет обновлён реф, React перерисует компонент, и
useLayoutEffectбудет запущен снова, когдаeditorDocument.activePageбудет изменяться.
Альтернативный подход
Если вы хотите отслеживать изменения конкретного элемента в
groupRef, вы можете положить состояние в реф, но это может быть более сложным и менее предпочтительным, чем простая проверка существованияlayer.Полная реализация
Вот ваша изменённая часть кода:
useLayoutEffect(() => { const layer = groupRef.current?.getLayer(); // Убедимся, что layer существует и есть активная страница if (layer && editorDocument.activePage?.id) { updateConnectionSegments(); // Вызов функции } }, [editorDocument.activePage?.id]); // Зависимость только от activePageЭто изменение должно позволить вашему коду работать так, как вы хотите, вызывая
updateConnectionSegmentsкогда это необходимо.Дополнительно
- Убедитесь, что
updateConnectionSegmentsне зависит от состояния, которое вы изменяете, поскольку это может привести к бесконечным вызовам. - Если по-прежнему будут возникать проблемы, проверьте, правильно ли устанавливается реф и не происходит ли никаких других ошибок, мешающих его установке.
-
- User
я сделала вот таую функцию для поиска коннектора на сцене import Konva from 'konva'; import { IPoint } from '../models/infrastucture/point';
export const getConnectorPoint = (connectorId: string, node: Konva.Shape | Konva.Group): IPoint | null => { if (node.id() ===
connector-${connectorId}) { return node.getAbsolutePosition(); }if ('children' in node) { for (const child of node.getChildren()) { const foundId = getConnectorPoint(connectorId, child); if (foundId) { return foundId; } } } return null; };
первоначально я хотела при вызове передать ей слой но проблема в том что так перебирать все это очень долго а я не остановлюсь с перебором даже если найду примитив
как мне организовать поиск иначе? чтобы возвращать только одно значение -- найденную координату примитива. и чтобы не пришлось продолжать заниматься перебором когда мы уже нашли наш коннектор
- Assistant
Чтобы оптимизировать вашу функцию
getConnectorPoint, вы можете использовать подход, который позволяет прерывать перебор, когда вы находите нужный коннектор, а также использовать подход "глубокого первого поиска" (DFS). Для этого достаточно добавить нужное условие, чтобы сразу возвращать значение, как только оно будет найдено.Вот улучшенная версия вашей функции:
import Konva from 'konva'; import { IPoint } from '../models/infrastucture/point'; export const getConnectorPoint = (connectorId: string, node: Konva.Shape | Konva.Group): IPoint | null => { // Проверяем, соответствует ли текущий узел соединителю if (node.id() === `connector-${connectorId}`) { return node.getAbsolutePosition(); // Возвращаем абсолютную позицию, если нашли } // Проверяем, есть ли у узла дочерние элементы if ('children' in node) { const children = node.getChildren(); // Получаем дочерние элементы for (let i = 0; i < children.length; i++) { const child = children[i]; const foundPoint = getConnectorPoint(connectorId, child); // Рекурсивный вызов if (foundPoint) { return foundPoint; // Если нашли, возвращаем координаты } } } // Если ничего не нашли, возвращаем null return null; };Основные изменения:
-
Ранний выход: Если вы находите нужный коннектор, вы сразу возвращаете его координаты и прекращаете выполнение функции. Это предотвращает дальнейшие рекурсивные вызовы.
-
Использование
letвместоconst: Я спроектировал цикл, который позволяет использоватьlet, так как мы можем использоватьbreakв будущем, если необходимо добавить дополнительные условия.
Альтернативный подход
Если у вас нет строгого требования использовать рекурсию, вы можете реализовать поиск в глубину, используя стек. Это может быть полезно, если количество уровней вложенности велико, и вы хотите избежать проблем с переполнением стека:
export const getConnectorPoint = (connectorId: string, rootNode: Konva.Shape | Konva.Group): IPoint | null => { const stack = [rootNode]; // Инициализируем стек с корневым узлом while (stack.length) { const node = stack.pop(); // Извлекаем последний добавленный узел // Проверяем текущий узел if (node.id() === `connector-${connectorId}`) { return node.getAbsolutePosition(); // Возвращаем позицию, если нашли } // Добавляем дочерние узлы в стек if ('children' in node) { for (const child of node.getChildren()) { stack.push(child); } } } return null; // Если коннектор не найден };Преимущества этого подхода:
- Избежание переполнения стека: Этот метод будет работать лучше на глубоком дереве узлов, так как он не зависит от глубины рекурсии.
- Читабельность: Код остаётся читаемым и понятным, при этом реализуя ту же самую логику поиска.
Вы можете выбрать тот вариант, который лучше подходит для вашего кода и вашей архитектуры.
-
- User
но эта функция вренет мне кучу всего она будет возвращать мне и коннектор и налы что мне делать чтобы вернуть только 1 значкение точку
- Assistant
Если вы хотите, чтобы функция
getConnectorPointвозвращала только одну точку (координаты) и не возвращалаnull, то нужно внести несколько изменений в вашу логику, чтобы гарантировать, что функция будет завершата сразу, как только найдет коннектор, и не продолжает перебор.Чтобы убедиться, что возвращается только одно значение (актуальная позиция коннектора), нужно модифицировать функцию так, чтобы она возвращала
undefined, если искомый коннектор не найден, а также используйте оператор завершения (return) в случае нахождения.Вот улучшенная версия функции:
import Konva from 'konva'; import { IPoint } from '../models/infrastucture/point'; export const getConnectorPoint = (connectorId: string, node: Konva.Shape | Konva.Group): IPoint | undefined => { // Проверяем, соответствует ли текущий узел соединителю if (node.id() === `connector-${connectorId}`) { return node.getAbsolutePosition(); // Возвращаем абсолютную позицию, если нашли } // Проверяем, есть ли у узла дочерние элементы if ('children' in node) { const children = node.getChildren(); // Получаем дочерние элементы for (let i = 0; i < children.length; i++) { const child = children[i]; const foundPoint = getConnectorPoint(connectorId, child); // Рекурсивный вызов if (foundPoint) { return foundPoint; // Если нашли, возвращаем координаты } } } // Если ничего не нашли, возвращаем undefined return undefined; };Объяснение изменений:
-
Возвращение
undefined: Вместоnull, мы возвращаемundefined, когда коннектор не найден. Это более безопасное значение, так как позволяет проверить, было ли что-то найдено. -
Проверка результата: В местах, где вызывается функция, вы можете теперь проверять результат так:
const point = getConnectorPoint(connectorId, node); if (point) { // Работаем с найденными координатами } else { // Коннектор не найден }- Ранняя остановка: Используя
returnсразу после нахождения коннектора, вы прерываете выполнение функции, и больше не продолжаете искать другие узлы.
Итог
Теперь
getConnectorPointбудет работать так, что, если коннектор с заданнымconnectorIdнайден, он вернет его координаты, а если нет - вернетundefined. Это исключает все лишние возвращаемые значения и упрощает проверку на наличие результата. -