Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

у меня есть вот такой код import { IPoint } from '../models/infrastucture/point'; import…

  1. 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} мне придется так много менять на доступ к этим самым тайп, а мне так не хочется переписывать все вызовы

  2. Assistant

    Вы можете создать объект для возвращаемых значений из функции, который будет включать как массив точек, так и тип линии. Это позволит вам эффективно передавать оба значения без необходимости переписывать весь код. Конечно, это потребует небольших изменений, но они будут минимальными.

    Вот как это можно сделать:

    1. Создайте интерфейс для результата, который будет содержать массив точек и тип линии.
    2. Измените возвращаемые значения функций, чтобы они возвращали этот новый объект.

    Вот пример изменений, которые нужно внести:

    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.

  3. 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;

    множественный кейс не работает как мне затолкать в один кейс два условия или не работает

  4. 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.

  5. 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; };

  6. 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;
    };
    

    Основные изменения:

    1. Выделение логики в переменные: Условия проверки вынесены в отдельные переменные с понятными названиями, что улучшает читабельность и понимание кода.
    2. Уменьшение вложенности: Некоторые условия были упрощены, что уменьшило количество уровней вложенности и сделало структуру кода более линейной.
    3. Чистота кода: Логика теперь более очевидна, и при необходимости изменения условий это будет проще реализовать.

    Такие изменения помогут вам легче понять, что делает код, и упростят его дальнейшую поддержку.

  7. 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;

      возможно без расчетов для таргет у 
      как просто выбрать тип?
    
  8. 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;
    

    Объяснение изменений:

    1. Определение границ: Мы вычисляем верхнюю (upperBound) и нижнюю (lowerBound) границы объектов один раз в начале.
    2. Упрощение логики возврата: Теперь можно вернуть тип соединителя, сравнивая sourceConnector.y с верхней границей, добавленной shift, что делает логику более ясной и сжатой.

    В результате код становится чище, и его проще понять. Однако, поскольку вы работаете с вертикальным положением объектов, убедитесь, что значение shift корректно, чтобы этот подход продолжал работать как ожидалось.

  9. 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;
    
  10. Assistant

    В вашем коде можно упростить выбор значения targetX, так как вам не нужно вычислять его с помощью условной операции, если конечный результат уже может быть определен на основании позиции sourceConnector. Вместо этого можно использовать sourceObject и targetConnector для определения направления.

    Вот как можно упростить этот фрагмент:

    const isLeftBracket = sourceConnector.x < targetConnector.x;
    
    return isLeftBracket ? ConnectionTypes.LeftBracket : ConnectionTypes.RightBracket;
    

    Объяснение изменений:

    1. Логическое сравнение: Прямо сравнивая sourceConnector.x и targetConnector.x, мы можем определить, какой тип соединения нужно вернуть.
    2. Упрощение логики: Мы избегаем лишнего условного выражения и преобразования, заменив его на простое логическое выражение.

    Это делает код более читаемым и сокращает использование лишних переменных, сохраняя прозрачность логики.

  11. 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;
    
  12. 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;
    }
    

    Объяснение изменений:

    1. Упрощение логики: Вместо вычисления конкретного targetY мы проверяем, выше ли sourceConnector.y обоих объектов, и в зависимости от этого определяем тип соединения.
    2. Чистый возврат: Теперь возвращаемое значение зависит от двух простых условий.

    Такой подход делает код более понятным и уменьшает количество операций. Вы также можете рассмотреть более сложные логические проверки в зависимости от ваших конкретных бизнес-требований, но общий принцип — это упрощение и ясность.

  13. 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.

  14. Assistant

    Чтобы решить вашу проблему с использованием оператора распространения (spread operator) при вызове функции, вам нужно убедиться, что возвращаемый объект из функции getArguments соответствует нужному типу. Судя по вашему коду, getArguments возвращает объект с несколькими свойствами (координаты, идентификаторы и т.д.).

    Чтобы корректно использовать оператор распространения, вы можете сделать следующее:

    1. Убедитесь, что функция возвращает объект с соответствующими свойствами: Убедитесь, что ваше свойство, возвращаемое из getArguments, содержит значения, соответствующие ожидаемым аргументам для getConnectionType.
    2. Преобразуйте возвращаемый объект в массив значений, если он не является кортежем: Если вы хотите использовать оператор распространения, можно преобразовать объект в массив.

    Вот как это можно сделать:

    Способ 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 может быть удобно использовать, если вы хотите работать с массивами и готовы адаптировать вашу функцию для возврата кортежа.

    Каждый из методов имеет свои плюсы, и выбор зависит от вашей дальнейшей работы с аргументами функции.

  15. User

    я взяла второй и получила TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.

  16. 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);
    }
    

    Объяснение:

    1. Тип возвращаемого значения: Мы создаем тип GetArgumentsReturnType, который представляет ваш массив, содержащий значения, которые ожидает функция getConnectionType.
    2. Код getArguments: Возвращаем массив, который соответствует нашему типу.
    3. Использование spread: Теперь, когда getArguments возвращает массив с корректным типом, вы можете безопасно использовать оператор spread.

    Примечание

    Убедитесь, что у вас есть все необходимые импорты и типы в вашей области видимости, а также что вы обрабатываете все возможные случаи, включая возможность undefined, когда ни один родитель не найден.

  17. 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);

    мне надо сделать так, чтобы связь переисовывалась при перетягивании только если изменился ее тип. в противном случае мне надо чтобы при перемщении по вертикали растягивался только ближайший вертикальный сегмент при перемещении по горизонтали -- ближайший горизонтальный сегмент там есть условие для этого но в нем пока что ничего не происходит сделай это

  18. Assistant

    Чтобы реализовать поведение, при котором связь переиспысывается только при изменении её типа, и при этом при перемещении по вертикали растягивается только ближайший вертикальный сегмент, а при перемещении по горизонтали — ближайший горизонтальный сегмент, нам нужно внести изменения в обработчик onDragMove компонента Rect, который отвечает за перетаскивание излома.

    Основные шаги:

    1. Найти ближайший сегмент (горизонтальный или вертикальный), который должен быть изменен в зависимости от направления движения.
    2. В случае, если тип связи изменился, пересчитать все точки и обновить состояние; в противном случае, обновить только ближайший сегмент.

    Вот как вы можете внести изменения в ваш код:

    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,
      });
    }}
    

    Изменения и объяснения:

    1. Выбор ближайшего сегмента: Мы используем findIndex для поиска ближайшего вертикального или горизонтального сегмента в зависимости от направления движения. Если сегмент найден, его координаты обновляются.
    2. Проверка изменения типа: Если происходит переключение между вертикальным и горизонтальным перемещением, флаг typeChanged устанавливается в true, что означает, что необходимо пересчитать точки и обновить соединение.
    3. Пересчет линии: Если typeChanged равно true, выполняется пересчет линий и обновление состояния.

    Эти изменения позволят вам добиться необходимого поведения: если тип соединения не изменился, обновляется только ближайший сегмент, а если изменился — пересчитывается вся линия.

  19. User

    нет не правильно у меня все подготовлено в функции апдейт сегментс вот тут if (type === connectionType) { setConnectionType(type); return; мне надо дописать продление последнего сегмента

  20. 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,
    ]);
    

    Объяснение изменений

    1. Обновление последнего сегмента: Если тип соединения не изменился, и у нас есть текущий сегмент, мы проверяем его ориентацию (горизонтальная или вертикальная) и обновляем его координаты (end.x или end.y) в зависимости от перемещения.

    2. Обновление состояния точек: Если сегмент был обновлён, мы вызываем setStatePoints, чтобы обновить массив points, где мы изменяем y или x конца последнего сегмента.

    3. Проверка на изменение типа: Если тип соединения изменился, то вызываем пересчет всех точек с помощью calculateLinePoints, чтобы обновить все сегменты.

    Эти изменения помогут вам добиться требуемого поведения: при перемещении по горизонтали или вертикали растягивается только ближайший сегмент, если тип связи не изменился, и в противном случае происходит пересчет всей линии.

  21. 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(); }, []); вот это не работает потому что во время вызова лэер не определен что делать?

  22. 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]);
    

    Заключение

    Выберите тот метод, который лучше всего соответствует вашему коду и логике приложения. Важно, чтобы данные были готовы к моменту, когда происходит вызов функций, чтобы избежать перерисовки соединений или неправильных значений в состоянии.

  23. 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);

    в теории когда меняется груп реф и там перестает лежать налл функция должна вызываться но этого почему-то не происходит юзэффект срабатывает только раз при старте

  24. 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 из зависимости
    

    Почему это сработает

    1. Проверка layer: Мы проверяем, есть ли у нас валидный layer, а не проверяем сам реф. Это должно произойти после того, как реф был установлен.

    2. Условия срабатывания: Когда будет обновлён реф, React перерисует компонент, и useLayoutEffect будет запущен снова, когда editorDocument.activePage будет изменяться.

    Альтернативный подход

    Если вы хотите отслеживать изменения конкретного элемента в groupRef, вы можете положить состояние в реф, но это может быть более сложным и менее предпочтительным, чем простая проверка существования layer.

    Полная реализация

    Вот ваша изменённая часть кода:

    useLayoutEffect(() => {
      const layer = groupRef.current?.getLayer();
      
      // Убедимся, что layer существует и есть активная страница
      if (layer && editorDocument.activePage?.id) {
        updateConnectionSegments(); // Вызов функции
      }
    }, [editorDocument.activePage?.id]); // Зависимость только от activePage
    

    Это изменение должно позволить вашему коду работать так, как вы хотите, вызывая updateConnectionSegments когда это необходимо.

    Дополнительно

    1. Убедитесь, что updateConnectionSegments не зависит от состояния, которое вы изменяете, поскольку это может привести к бесконечным вызовам.
    2. Если по-прежнему будут возникать проблемы, проверьте, правильно ли устанавливается реф и не происходит ли никаких других ошибок, мешающих его установке.
  25. 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; };

    первоначально я хотела при вызове передать ей слой но проблема в том что так перебирать все это очень долго а я не остановлюсь с перебором даже если найду примитив

    как мне организовать поиск иначе? чтобы возвращать только одно значение -- найденную координату примитива. и чтобы не пришлось продолжать заниматься перебором когда мы уже нашли наш коннектор

  26. 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;
    };
    

    Основные изменения:

    1. Ранний выход: Если вы находите нужный коннектор, вы сразу возвращаете его координаты и прекращаете выполнение функции. Это предотвращает дальнейшие рекурсивные вызовы.

    2. Использование 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; // Если коннектор не найден
    };
    

    Преимущества этого подхода:

    • Избежание переполнения стека: Этот метод будет работать лучше на глубоком дереве узлов, так как он не зависит от глубины рекурсии.
    • Читабельность: Код остаётся читаемым и понятным, при этом реализуя ту же самую логику поиска.

    Вы можете выбрать тот вариант, который лучше подходит для вашего кода и вашей архитектуры.

  27. User

    но эта функция вренет мне кучу всего она будет возвращать мне и коннектор и налы что мне делать чтобы вернуть только 1 значкение точку

  28. 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;
    };
    

    Объяснение изменений:

    1. Возвращение undefined: Вместо null, мы возвращаем undefined, когда коннектор не найден. Это более безопасное значение, так как позволяет проверить, было ли что-то найдено.

    2. Проверка результата: В местах, где вызывается функция, вы можете теперь проверять результат так:

    const point = getConnectorPoint(connectorId, node);
    if (point) {
      // Работаем с найденными координатами
    } else {
      // Коннектор не найден
    }
    
    1. Ранняя остановка: Используя return сразу после нахождения коннектора, вы прерываете выполнение функции, и больше не продолжаете искать другие узлы.

    Итог

    Теперь getConnectorPoint будет работать так, что, если коннектор с заданным connectorId найден, он вернет его координаты, а если нет - вернет undefined. Это исключает все лишние возвращаемые значения и упрощает проверку на наличие результата.